Article: Drop partial purge code and constants, deprecated in 1.29
[lhc/web/wiklou.git] / includes / page / WikiPage.php
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Edit\PreparedEdit;
24 use \MediaWiki\Logger\LoggerFactory;
25 use \MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27 use Wikimedia\Rdbms\IDatabase;
28 use Wikimedia\Rdbms\DBError;
29 use Wikimedia\Rdbms\DBUnexpectedError;
30
31 /**
32 * Class representing a MediaWiki article and history.
33 *
34 * Some fields are public only for backwards-compatibility. Use accessors.
35 * In the past, this class was part of Article.php and everything was public.
36 */
37 class WikiPage implements Page, IDBAccessObject {
38 // Constants for $mDataLoadedFrom and related
39
40 /**
41 * @var Title
42 */
43 public $mTitle = null;
44
45 /**@{{
46 * @protected
47 */
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 /**@}}*/
52
53 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
55
56 /**
57 * @var int
58 */
59 protected $mId = null;
60
61 /**
62 * @var int One of the READ_* constants
63 */
64 protected $mDataLoadedFrom = self::READ_NONE;
65
66 /**
67 * @var Title
68 */
69 protected $mRedirectTarget = null;
70
71 /**
72 * @var Revision
73 */
74 protected $mLastRevision = null;
75
76 /**
77 * @var string Timestamp of the current revision or empty string if not loaded
78 */
79 protected $mTimestamp = '';
80
81 /**
82 * @var string
83 */
84 protected $mTouched = '19700101000000';
85
86 /**
87 * @var string
88 */
89 protected $mLinksUpdated = '19700101000000';
90
91 /**
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
94 */
95 public function __construct( Title $title ) {
96 $this->mTitle = $title;
97 }
98
99 /**
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
102 */
103 public function __clone() {
104 $this->mTitle = clone $this->mTitle;
105 }
106
107 /**
108 * Create a WikiPage object of the appropriate class for the given title.
109 *
110 * @param Title $title
111 *
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
114 */
115 public static function factory( Title $title ) {
116 $ns = $title->getNamespace();
117
118 if ( $ns == NS_MEDIA ) {
119 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
120 } elseif ( $ns < 0 ) {
121 throw new MWException( "Invalid or virtual namespace $ns given." );
122 }
123
124 $page = null;
125 if ( !Hooks::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
126 return $page;
127 }
128
129 switch ( $ns ) {
130 case NS_FILE:
131 $page = new WikiFilePage( $title );
132 break;
133 case NS_CATEGORY:
134 $page = new WikiCategoryPage( $title );
135 break;
136 default:
137 $page = new WikiPage( $title );
138 }
139
140 return $page;
141 }
142
143 /**
144 * Constructor from a page id
145 *
146 * @param int $id Article ID to load
147 * @param string|int $from One of the following values:
148 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
150 *
151 * @return WikiPage|null
152 */
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 // page ids are never 0 or negative, see T63166
155 if ( $id < 1 ) {
156 return null;
157 }
158
159 $from = self::convertSelectType( $from );
160 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_REPLICA );
161 $row = $db->selectRow(
162 'page', self::selectFields(), [ 'page_id' => $id ], __METHOD__ );
163 if ( !$row ) {
164 return null;
165 }
166 return self::newFromRow( $row, $from );
167 }
168
169 /**
170 * Constructor from a database row
171 *
172 * @since 1.20
173 * @param object $row Database row containing at least fields returned by selectFields().
174 * @param string|int $from Source of $data:
175 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
176 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
177 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
178 * @return WikiPage
179 */
180 public static function newFromRow( $row, $from = 'fromdb' ) {
181 $page = self::factory( Title::newFromRow( $row ) );
182 $page->loadFromRow( $row, $from );
183 return $page;
184 }
185
186 /**
187 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
188 *
189 * @param object|string|int $type
190 * @return mixed
191 */
192 private static function convertSelectType( $type ) {
193 switch ( $type ) {
194 case 'fromdb':
195 return self::READ_NORMAL;
196 case 'fromdbmaster':
197 return self::READ_LATEST;
198 case 'forupdate':
199 return self::READ_LOCKING;
200 default:
201 // It may already be an integer or whatever else
202 return $type;
203 }
204 }
205
206 /**
207 * @todo Move this UI stuff somewhere else
208 *
209 * @see ContentHandler::getActionOverrides
210 * @return array
211 */
212 public function getActionOverrides() {
213 return $this->getContentHandler()->getActionOverrides();
214 }
215
216 /**
217 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
218 *
219 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
220 *
221 * @return ContentHandler
222 *
223 * @since 1.21
224 */
225 public function getContentHandler() {
226 return ContentHandler::getForModelID( $this->getContentModel() );
227 }
228
229 /**
230 * Get the title object of the article
231 * @return Title Title object of this page
232 */
233 public function getTitle() {
234 return $this->mTitle;
235 }
236
237 /**
238 * Clear the object
239 * @return void
240 */
241 public function clear() {
242 $this->mDataLoaded = false;
243 $this->mDataLoadedFrom = self::READ_NONE;
244
245 $this->clearCacheFields();
246 }
247
248 /**
249 * Clear the object cache fields
250 * @return void
251 */
252 protected function clearCacheFields() {
253 $this->mId = null;
254 $this->mRedirectTarget = null; // Title object if set
255 $this->mLastRevision = null; // Latest revision
256 $this->mTouched = '19700101000000';
257 $this->mLinksUpdated = '19700101000000';
258 $this->mTimestamp = '';
259 $this->mIsRedirect = false;
260 $this->mLatest = false;
261 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
262 // the requested rev ID and content against the cached one for equality. For most
263 // content types, the output should not change during the lifetime of this cache.
264 // Clearing it can cause extra parses on edit for no reason.
265 }
266
267 /**
268 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
269 * @return void
270 * @since 1.23
271 */
272 public function clearPreparedEdit() {
273 $this->mPreparedEdit = false;
274 }
275
276 /**
277 * Return the list of revision fields that should be selected to create
278 * a new page.
279 *
280 * @return array
281 */
282 public static function selectFields() {
283 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
284
285 $fields = [
286 'page_id',
287 'page_namespace',
288 'page_title',
289 'page_restrictions',
290 'page_is_redirect',
291 'page_is_new',
292 'page_random',
293 'page_touched',
294 'page_links_updated',
295 'page_latest',
296 'page_len',
297 ];
298
299 if ( $wgContentHandlerUseDB ) {
300 $fields[] = 'page_content_model';
301 }
302
303 if ( $wgPageLanguageUseDB ) {
304 $fields[] = 'page_lang';
305 }
306
307 return $fields;
308 }
309
310 /**
311 * Fetch a page record with the given conditions
312 * @param IDatabase $dbr
313 * @param array $conditions
314 * @param array $options
315 * @return object|bool Database result resource, or false on failure
316 */
317 protected function pageData( $dbr, $conditions, $options = [] ) {
318 $fields = self::selectFields();
319
320 // Avoid PHP 7.1 warning of passing $this by reference
321 $wikiPage = $this;
322
323 Hooks::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
324
325 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
326
327 Hooks::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
328
329 return $row;
330 }
331
332 /**
333 * Fetch a page record matching the Title object's namespace and title
334 * using a sanitized title string
335 *
336 * @param IDatabase $dbr
337 * @param Title $title
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
340 */
341 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
342 return $this->pageData( $dbr, [
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ], $options );
345 }
346
347 /**
348 * Fetch a page record matching the requested ID
349 *
350 * @param IDatabase $dbr
351 * @param int $id
352 * @param array $options
353 * @return object|bool Database result resource, or false on failure
354 */
355 public function pageDataFromId( $dbr, $id, $options = [] ) {
356 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
357 }
358
359 /**
360 * Load the object from a given source by title
361 *
362 * @param object|string|int $from One of the following:
363 * - A DB query result object.
364 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
365 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
366 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
367 * using SELECT FOR UPDATE.
368 *
369 * @return void
370 */
371 public function loadPageData( $from = 'fromdb' ) {
372 $from = self::convertSelectType( $from );
373 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
374 // We already have the data from the correct location, no need to load it twice.
375 return;
376 }
377
378 if ( is_int( $from ) ) {
379 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
380 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
381 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
382
383 if ( !$data
384 && $index == DB_REPLICA
385 && $loadBalancer->getServerCount() > 1
386 && $loadBalancer->hasOrMadeRecentMasterChanges()
387 ) {
388 $from = self::READ_LATEST;
389 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
390 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
391 }
392 } else {
393 // No idea from where the caller got this data, assume replica DB.
394 $data = $from;
395 $from = self::READ_NORMAL;
396 }
397
398 $this->loadFromRow( $data, $from );
399 }
400
401 /**
402 * Load the object from a database row
403 *
404 * @since 1.20
405 * @param object|bool $data DB row containing fields returned by selectFields() or false
406 * @param string|int $from One of the following:
407 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
408 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
409 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
410 * the master DB using SELECT FOR UPDATE
411 */
412 public function loadFromRow( $data, $from ) {
413 $lc = LinkCache::singleton();
414 $lc->clearLink( $this->mTitle );
415
416 if ( $data ) {
417 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
418
419 $this->mTitle->loadFromRow( $data );
420
421 // Old-fashioned restrictions
422 $this->mTitle->loadRestrictions( $data->page_restrictions );
423
424 $this->mId = intval( $data->page_id );
425 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
426 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
427 $this->mIsRedirect = intval( $data->page_is_redirect );
428 $this->mLatest = intval( $data->page_latest );
429 // T39225: $latest may no longer match the cached latest Revision object.
430 // Double-check the ID of any cached latest Revision object for consistency.
431 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
432 $this->mLastRevision = null;
433 $this->mTimestamp = '';
434 }
435 } else {
436 $lc->addBadLinkObj( $this->mTitle );
437
438 $this->mTitle->loadFromRow( false );
439
440 $this->clearCacheFields();
441
442 $this->mId = 0;
443 }
444
445 $this->mDataLoaded = true;
446 $this->mDataLoadedFrom = self::convertSelectType( $from );
447 }
448
449 /**
450 * @return int Page ID
451 */
452 public function getId() {
453 if ( !$this->mDataLoaded ) {
454 $this->loadPageData();
455 }
456 return $this->mId;
457 }
458
459 /**
460 * @return bool Whether or not the page exists in the database
461 */
462 public function exists() {
463 if ( !$this->mDataLoaded ) {
464 $this->loadPageData();
465 }
466 return $this->mId > 0;
467 }
468
469 /**
470 * Check if this page is something we're going to be showing
471 * some sort of sensible content for. If we return false, page
472 * views (plain action=view) will return an HTTP 404 response,
473 * so spiders and robots can know they're following a bad link.
474 *
475 * @return bool
476 */
477 public function hasViewableContent() {
478 return $this->mTitle->isKnown();
479 }
480
481 /**
482 * Tests if the article content represents a redirect
483 *
484 * @return bool
485 */
486 public function isRedirect() {
487 if ( !$this->mDataLoaded ) {
488 $this->loadPageData();
489 }
490
491 return (bool)$this->mIsRedirect;
492 }
493
494 /**
495 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
496 *
497 * Will use the revisions actual content model if the page exists,
498 * and the page's default if the page doesn't exist yet.
499 *
500 * @return string
501 *
502 * @since 1.21
503 */
504 public function getContentModel() {
505 if ( $this->exists() ) {
506 $cache = ObjectCache::getMainWANInstance();
507
508 return $cache->getWithSetCallback(
509 $cache->makeKey( 'page-content-model', $this->getLatest() ),
510 $cache::TTL_MONTH,
511 function () {
512 $rev = $this->getRevision();
513 if ( $rev ) {
514 // Look at the revision's actual content model
515 return $rev->getContentModel();
516 } else {
517 $title = $this->mTitle->getPrefixedDBkey();
518 wfWarn( "Page $title exists but has no (visible) revisions!" );
519 return $this->mTitle->getContentModel();
520 }
521 }
522 );
523 }
524
525 // use the default model for this page
526 return $this->mTitle->getContentModel();
527 }
528
529 /**
530 * Loads page_touched and returns a value indicating if it should be used
531 * @return bool True if this page exists and is not a redirect
532 */
533 public function checkTouched() {
534 if ( !$this->mDataLoaded ) {
535 $this->loadPageData();
536 }
537 return ( $this->mId && !$this->mIsRedirect );
538 }
539
540 /**
541 * Get the page_touched field
542 * @return string Containing GMT timestamp
543 */
544 public function getTouched() {
545 if ( !$this->mDataLoaded ) {
546 $this->loadPageData();
547 }
548 return $this->mTouched;
549 }
550
551 /**
552 * Get the page_links_updated field
553 * @return string|null Containing GMT timestamp
554 */
555 public function getLinksTimestamp() {
556 if ( !$this->mDataLoaded ) {
557 $this->loadPageData();
558 }
559 return $this->mLinksUpdated;
560 }
561
562 /**
563 * Get the page_latest field
564 * @return int The rev_id of current revision
565 */
566 public function getLatest() {
567 if ( !$this->mDataLoaded ) {
568 $this->loadPageData();
569 }
570 return (int)$this->mLatest;
571 }
572
573 /**
574 * Get the Revision object of the oldest revision
575 * @return Revision|null
576 */
577 public function getOldestRevision() {
578 // Try using the replica DB first, then try the master
579 $rev = $this->mTitle->getFirstRevision();
580 if ( !$rev ) {
581 $rev = $this->mTitle->getFirstRevision( Title::GAID_FOR_UPDATE );
582 }
583 return $rev;
584 }
585
586 /**
587 * Loads everything except the text
588 * This isn't necessary for all uses, so it's only done if needed.
589 */
590 protected function loadLastEdit() {
591 if ( $this->mLastRevision !== null ) {
592 return; // already loaded
593 }
594
595 $latest = $this->getLatest();
596 if ( !$latest ) {
597 return; // page doesn't exist or is missing page_latest info
598 }
599
600 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
601 // T39225: if session S1 loads the page row FOR UPDATE, the result always
602 // includes the latest changes committed. This is true even within REPEATABLE-READ
603 // transactions, where S1 normally only sees changes committed before the first S1
604 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
605 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
606 // happened after the first S1 SELECT.
607 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
608 $flags = Revision::READ_LOCKING;
609 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
610 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
611 // Bug T93976: if page_latest was loaded from the master, fetch the
612 // revision from there as well, as it may not exist yet on a replica DB.
613 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
614 $flags = Revision::READ_LATEST;
615 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
616 } else {
617 $dbr = wfGetDB( DB_REPLICA );
618 $revision = Revision::newKnownCurrent( $dbr, $this->getId(), $latest );
619 }
620
621 if ( $revision ) { // sanity
622 $this->setLastEdit( $revision );
623 }
624 }
625
626 /**
627 * Set the latest revision
628 * @param Revision $revision
629 */
630 protected function setLastEdit( Revision $revision ) {
631 $this->mLastRevision = $revision;
632 $this->mTimestamp = $revision->getTimestamp();
633 }
634
635 /**
636 * Get the latest revision
637 * @return Revision|null
638 */
639 public function getRevision() {
640 $this->loadLastEdit();
641 if ( $this->mLastRevision ) {
642 return $this->mLastRevision;
643 }
644 return null;
645 }
646
647 /**
648 * Get the content of the current revision. No side-effects...
649 *
650 * @param int $audience One of:
651 * Revision::FOR_PUBLIC to be displayed to all users
652 * Revision::FOR_THIS_USER to be displayed to $wgUser
653 * Revision::RAW get the text regardless of permissions
654 * @param User $user User object to check for, only if FOR_THIS_USER is passed
655 * to the $audience parameter
656 * @return Content|null The content of the current revision
657 *
658 * @since 1.21
659 */
660 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
661 $this->loadLastEdit();
662 if ( $this->mLastRevision ) {
663 return $this->mLastRevision->getContent( $audience, $user );
664 }
665 return null;
666 }
667
668 /**
669 * @return string MW timestamp of last article revision
670 */
671 public function getTimestamp() {
672 // Check if the field has been filled by WikiPage::setTimestamp()
673 if ( !$this->mTimestamp ) {
674 $this->loadLastEdit();
675 }
676
677 return wfTimestamp( TS_MW, $this->mTimestamp );
678 }
679
680 /**
681 * Set the page timestamp (use only to avoid DB queries)
682 * @param string $ts MW timestamp of last article revision
683 * @return void
684 */
685 public function setTimestamp( $ts ) {
686 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
687 }
688
689 /**
690 * @param int $audience One of:
691 * Revision::FOR_PUBLIC to be displayed to all users
692 * Revision::FOR_THIS_USER to be displayed to the given user
693 * Revision::RAW get the text regardless of permissions
694 * @param User $user User object to check for, only if FOR_THIS_USER is passed
695 * to the $audience parameter
696 * @return int User ID for the user that made the last article revision
697 */
698 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
699 $this->loadLastEdit();
700 if ( $this->mLastRevision ) {
701 return $this->mLastRevision->getUser( $audience, $user );
702 } else {
703 return -1;
704 }
705 }
706
707 /**
708 * Get the User object of the user who created the page
709 * @param int $audience One of:
710 * Revision::FOR_PUBLIC to be displayed to all users
711 * Revision::FOR_THIS_USER to be displayed to the given user
712 * Revision::RAW get the text regardless of permissions
713 * @param User $user User object to check for, only if FOR_THIS_USER is passed
714 * to the $audience parameter
715 * @return User|null
716 */
717 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
718 $revision = $this->getOldestRevision();
719 if ( $revision ) {
720 $userName = $revision->getUserText( $audience, $user );
721 return User::newFromName( $userName, false );
722 } else {
723 return null;
724 }
725 }
726
727 /**
728 * @param int $audience One of:
729 * Revision::FOR_PUBLIC to be displayed to all users
730 * Revision::FOR_THIS_USER to be displayed to the given user
731 * Revision::RAW get the text regardless of permissions
732 * @param User $user User object to check for, only if FOR_THIS_USER is passed
733 * to the $audience parameter
734 * @return string Username of the user that made the last article revision
735 */
736 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
737 $this->loadLastEdit();
738 if ( $this->mLastRevision ) {
739 return $this->mLastRevision->getUserText( $audience, $user );
740 } else {
741 return '';
742 }
743 }
744
745 /**
746 * @param int $audience One of:
747 * Revision::FOR_PUBLIC to be displayed to all users
748 * Revision::FOR_THIS_USER to be displayed to the given user
749 * Revision::RAW get the text regardless of permissions
750 * @param User $user User object to check for, only if FOR_THIS_USER is passed
751 * to the $audience parameter
752 * @return string Comment stored for the last article revision
753 */
754 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
755 $this->loadLastEdit();
756 if ( $this->mLastRevision ) {
757 return $this->mLastRevision->getComment( $audience, $user );
758 } else {
759 return '';
760 }
761 }
762
763 /**
764 * Returns true if last revision was marked as "minor edit"
765 *
766 * @return bool Minor edit indicator for the last article revision.
767 */
768 public function getMinorEdit() {
769 $this->loadLastEdit();
770 if ( $this->mLastRevision ) {
771 return $this->mLastRevision->isMinor();
772 } else {
773 return false;
774 }
775 }
776
777 /**
778 * Determine whether a page would be suitable for being counted as an
779 * article in the site_stats table based on the title & its content
780 *
781 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
782 * if false, the current database state will be used
783 * @return bool
784 */
785 public function isCountable( $editInfo = false ) {
786 global $wgArticleCountMethod;
787
788 if ( !$this->mTitle->isContentPage() ) {
789 return false;
790 }
791
792 if ( $editInfo ) {
793 $content = $editInfo->pstContent;
794 } else {
795 $content = $this->getContent();
796 }
797
798 if ( !$content || $content->isRedirect() ) {
799 return false;
800 }
801
802 $hasLinks = null;
803
804 if ( $wgArticleCountMethod === 'link' ) {
805 // nasty special case to avoid re-parsing to detect links
806
807 if ( $editInfo ) {
808 // ParserOutput::getLinks() is a 2D array of page links, so
809 // to be really correct we would need to recurse in the array
810 // but the main array should only have items in it if there are
811 // links.
812 $hasLinks = (bool)count( $editInfo->output->getLinks() );
813 } else {
814 $hasLinks = (bool)wfGetDB( DB_REPLICA )->selectField( 'pagelinks', 1,
815 [ 'pl_from' => $this->getId() ], __METHOD__ );
816 }
817 }
818
819 return $content->isCountable( $hasLinks );
820 }
821
822 /**
823 * If this page is a redirect, get its target
824 *
825 * The target will be fetched from the redirect table if possible.
826 * If this page doesn't have an entry there, call insertRedirect()
827 * @return Title|null Title object, or null if this page is not a redirect
828 */
829 public function getRedirectTarget() {
830 if ( !$this->mTitle->isRedirect() ) {
831 return null;
832 }
833
834 if ( $this->mRedirectTarget !== null ) {
835 return $this->mRedirectTarget;
836 }
837
838 // Query the redirect table
839 $dbr = wfGetDB( DB_REPLICA );
840 $row = $dbr->selectRow( 'redirect',
841 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
842 [ 'rd_from' => $this->getId() ],
843 __METHOD__
844 );
845
846 // rd_fragment and rd_interwiki were added later, populate them if empty
847 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
848 $this->mRedirectTarget = Title::makeTitle(
849 $row->rd_namespace, $row->rd_title,
850 $row->rd_fragment, $row->rd_interwiki
851 );
852 return $this->mRedirectTarget;
853 }
854
855 // This page doesn't have an entry in the redirect table
856 $this->mRedirectTarget = $this->insertRedirect();
857 return $this->mRedirectTarget;
858 }
859
860 /**
861 * Insert an entry for this page into the redirect table if the content is a redirect
862 *
863 * The database update will be deferred via DeferredUpdates
864 *
865 * Don't call this function directly unless you know what you're doing.
866 * @return Title|null Title object or null if not a redirect
867 */
868 public function insertRedirect() {
869 $content = $this->getContent();
870 $retval = $content ? $content->getUltimateRedirectTarget() : null;
871 if ( !$retval ) {
872 return null;
873 }
874
875 // Update the DB post-send if the page has not cached since now
876 $latest = $this->getLatest();
877 DeferredUpdates::addCallableUpdate(
878 function () use ( $retval, $latest ) {
879 $this->insertRedirectEntry( $retval, $latest );
880 },
881 DeferredUpdates::POSTSEND,
882 wfGetDB( DB_MASTER )
883 );
884
885 return $retval;
886 }
887
888 /**
889 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
890 * @param Title $rt Redirect target
891 * @param int|null $oldLatest Prior page_latest for check and set
892 */
893 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
894 $dbw = wfGetDB( DB_MASTER );
895 $dbw->startAtomic( __METHOD__ );
896
897 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
898 $dbw->upsert(
899 'redirect',
900 [
901 'rd_from' => $this->getId(),
902 'rd_namespace' => $rt->getNamespace(),
903 'rd_title' => $rt->getDBkey(),
904 'rd_fragment' => $rt->getFragment(),
905 'rd_interwiki' => $rt->getInterwiki(),
906 ],
907 [ 'rd_from' ],
908 [
909 'rd_namespace' => $rt->getNamespace(),
910 'rd_title' => $rt->getDBkey(),
911 'rd_fragment' => $rt->getFragment(),
912 'rd_interwiki' => $rt->getInterwiki(),
913 ],
914 __METHOD__
915 );
916 }
917
918 $dbw->endAtomic( __METHOD__ );
919 }
920
921 /**
922 * Get the Title object or URL this page redirects to
923 *
924 * @return bool|Title|string False, Title of in-wiki target, or string with URL
925 */
926 public function followRedirect() {
927 return $this->getRedirectURL( $this->getRedirectTarget() );
928 }
929
930 /**
931 * Get the Title object or URL to use for a redirect. We use Title
932 * objects for same-wiki, non-special redirects and URLs for everything
933 * else.
934 * @param Title $rt Redirect target
935 * @return bool|Title|string False, Title object of local target, or string with URL
936 */
937 public function getRedirectURL( $rt ) {
938 if ( !$rt ) {
939 return false;
940 }
941
942 if ( $rt->isExternal() ) {
943 if ( $rt->isLocal() ) {
944 // Offsite wikis need an HTTP redirect.
945 // This can be hard to reverse and may produce loops,
946 // so they may be disabled in the site configuration.
947 $source = $this->mTitle->getFullURL( 'redirect=no' );
948 return $rt->getFullURL( [ 'rdfrom' => $source ] );
949 } else {
950 // External pages without "local" bit set are not valid
951 // redirect targets
952 return false;
953 }
954 }
955
956 if ( $rt->isSpecialPage() ) {
957 // Gotta handle redirects to special pages differently:
958 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
959 // Some pages are not valid targets.
960 if ( $rt->isValidRedirectTarget() ) {
961 return $rt->getFullURL();
962 } else {
963 return false;
964 }
965 }
966
967 return $rt;
968 }
969
970 /**
971 * Get a list of users who have edited this article, not including the user who made
972 * the most recent revision, which you can get from $article->getUser() if you want it
973 * @return UserArrayFromResult
974 */
975 public function getContributors() {
976 // @todo FIXME: This is expensive; cache this info somewhere.
977
978 $dbr = wfGetDB( DB_REPLICA );
979
980 $tables = [ 'revision', 'user' ];
981
982 $fields = [
983 'user_id' => 'rev_user',
984 'user_name' => 'rev_user_text',
985 'user_real_name' => 'MIN(user_real_name)',
986 'timestamp' => 'MAX(rev_timestamp)',
987 ];
988
989 $conds = [ 'rev_page' => $this->getId() ];
990
991 // The user who made the top revision gets credited as "this page was last edited by
992 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
993 $user = $this->getUser();
994 if ( $user ) {
995 $conds[] = "rev_user != $user";
996 } else {
997 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
998 }
999
1000 // Username hidden?
1001 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1002
1003 $jconds = [
1004 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1005 ];
1006
1007 $options = [
1008 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1009 'ORDER BY' => 'timestamp DESC',
1010 ];
1011
1012 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1013 return new UserArrayFromResult( $res );
1014 }
1015
1016 /**
1017 * Should the parser cache be used?
1018 *
1019 * @param ParserOptions $parserOptions ParserOptions to check
1020 * @param int $oldId
1021 * @return bool
1022 */
1023 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1024 return $parserOptions->getStubThreshold() == 0
1025 && $this->exists()
1026 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1027 && $this->getContentHandler()->isParserCacheSupported();
1028 }
1029
1030 /**
1031 * Get a ParserOutput for the given ParserOptions and revision ID.
1032 *
1033 * The parser cache will be used if possible. Cache misses that result
1034 * in parser runs are debounced with PoolCounter.
1035 *
1036 * @since 1.19
1037 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1038 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1039 * get the current revision (default value)
1040 * @param bool $forceParse Force reindexing, regardless of cache settings
1041 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1042 */
1043 public function getParserOutput(
1044 ParserOptions $parserOptions, $oldid = null, $forceParse = false
1045 ) {
1046 $useParserCache =
1047 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1048
1049 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1050 throw new InvalidArgumentException(
1051 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1052 );
1053 }
1054
1055 wfDebug( __METHOD__ .
1056 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1057 if ( $parserOptions->getStubThreshold() ) {
1058 wfIncrStats( 'pcache.miss.stub' );
1059 }
1060
1061 if ( $useParserCache ) {
1062 $parserOutput = MediaWikiServices::getInstance()->getParserCache()
1063 ->get( $this, $parserOptions );
1064 if ( $parserOutput !== false ) {
1065 return $parserOutput;
1066 }
1067 }
1068
1069 if ( $oldid === null || $oldid === 0 ) {
1070 $oldid = $this->getLatest();
1071 }
1072
1073 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1074 $pool->execute();
1075
1076 return $pool->getParserOutput();
1077 }
1078
1079 /**
1080 * Do standard deferred updates after page view (existing or missing page)
1081 * @param User $user The relevant user
1082 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1083 */
1084 public function doViewUpdates( User $user, $oldid = 0 ) {
1085 if ( wfReadOnly() ) {
1086 return;
1087 }
1088
1089 Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1090 // Update newtalk / watchlist notification status
1091 try {
1092 $user->clearNotification( $this->mTitle, $oldid );
1093 } catch ( DBError $e ) {
1094 // Avoid outage if the master is not reachable
1095 MWExceptionHandler::logException( $e );
1096 }
1097 }
1098
1099 /**
1100 * Perform the actions of a page purging
1101 * @return bool
1102 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1103 * controlled how much purging was done.
1104 */
1105 public function doPurge() {
1106 // Avoid PHP 7.1 warning of passing $this by reference
1107 $wikiPage = $this;
1108
1109 if ( !Hooks::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1110 return false;
1111 }
1112
1113 $this->mTitle->invalidateCache();
1114
1115 // Clear file cache
1116 HTMLFileCache::clearFileCache( $this->getTitle() );
1117 // Send purge after above page_touched update was committed
1118 DeferredUpdates::addUpdate(
1119 new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1120 DeferredUpdates::PRESEND
1121 );
1122
1123 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1124 $messageCache = MessageCache::singleton();
1125 $messageCache->updateMessageOverride( $this->mTitle, $this->getContent() );
1126 }
1127
1128 return true;
1129 }
1130
1131 /**
1132 * Insert a new empty page record for this article.
1133 * This *must* be followed up by creating a revision
1134 * and running $this->updateRevisionOn( ... );
1135 * or else the record will be left in a funky state.
1136 * Best if all done inside a transaction.
1137 *
1138 * @param IDatabase $dbw
1139 * @param int|null $pageId Custom page ID that will be used for the insert statement
1140 *
1141 * @return bool|int The newly created page_id key; false if the row was not
1142 * inserted, e.g. because the title already existed or because the specified
1143 * page ID is already in use.
1144 */
1145 public function insertOn( $dbw, $pageId = null ) {
1146 $pageIdForInsert = $pageId ? [ 'page_id' => $pageId ] : [];
1147 $dbw->insert(
1148 'page',
1149 [
1150 'page_namespace' => $this->mTitle->getNamespace(),
1151 'page_title' => $this->mTitle->getDBkey(),
1152 'page_restrictions' => '',
1153 'page_is_redirect' => 0, // Will set this shortly...
1154 'page_is_new' => 1,
1155 'page_random' => wfRandom(),
1156 'page_touched' => $dbw->timestamp(),
1157 'page_latest' => 0, // Fill this in shortly...
1158 'page_len' => 0, // Fill this in shortly...
1159 ] + $pageIdForInsert,
1160 __METHOD__,
1161 'IGNORE'
1162 );
1163
1164 if ( $dbw->affectedRows() > 0 ) {
1165 $newid = $pageId ? (int)$pageId : $dbw->insertId();
1166 $this->mId = $newid;
1167 $this->mTitle->resetArticleID( $newid );
1168
1169 return $newid;
1170 } else {
1171 return false; // nothing changed
1172 }
1173 }
1174
1175 /**
1176 * Update the page record to point to a newly saved revision.
1177 *
1178 * @param IDatabase $dbw
1179 * @param Revision $revision For ID number, and text used to set
1180 * length and redirect status fields
1181 * @param int $lastRevision If given, will not overwrite the page field
1182 * when different from the currently set value.
1183 * Giving 0 indicates the new page flag should be set on.
1184 * @param bool $lastRevIsRedirect If given, will optimize adding and
1185 * removing rows in redirect table.
1186 * @return bool Success; false if the page row was missing or page_latest changed
1187 */
1188 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1189 $lastRevIsRedirect = null
1190 ) {
1191 global $wgContentHandlerUseDB;
1192
1193 // Assertion to try to catch T92046
1194 if ( (int)$revision->getId() === 0 ) {
1195 throw new InvalidArgumentException(
1196 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1197 );
1198 }
1199
1200 $content = $revision->getContent();
1201 $len = $content ? $content->getSize() : 0;
1202 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1203
1204 $conditions = [ 'page_id' => $this->getId() ];
1205
1206 if ( !is_null( $lastRevision ) ) {
1207 // An extra check against threads stepping on each other
1208 $conditions['page_latest'] = $lastRevision;
1209 }
1210
1211 $row = [ /* SET */
1212 'page_latest' => $revision->getId(),
1213 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1214 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1215 'page_is_redirect' => $rt !== null ? 1 : 0,
1216 'page_len' => $len,
1217 ];
1218
1219 if ( $wgContentHandlerUseDB ) {
1220 $row['page_content_model'] = $revision->getContentModel();
1221 }
1222
1223 $dbw->update( 'page',
1224 $row,
1225 $conditions,
1226 __METHOD__ );
1227
1228 $result = $dbw->affectedRows() > 0;
1229 if ( $result ) {
1230 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1231 $this->setLastEdit( $revision );
1232 $this->mLatest = $revision->getId();
1233 $this->mIsRedirect = (bool)$rt;
1234 // Update the LinkCache.
1235 LinkCache::singleton()->addGoodLinkObj(
1236 $this->getId(),
1237 $this->mTitle,
1238 $len,
1239 $this->mIsRedirect,
1240 $this->mLatest,
1241 $revision->getContentModel()
1242 );
1243 }
1244
1245 return $result;
1246 }
1247
1248 /**
1249 * Add row to the redirect table if this is a redirect, remove otherwise.
1250 *
1251 * @param IDatabase $dbw
1252 * @param Title $redirectTitle Title object pointing to the redirect target,
1253 * or NULL if this is not a redirect
1254 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1255 * removing rows in redirect table.
1256 * @return bool True on success, false on failure
1257 * @private
1258 */
1259 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1260 // Always update redirects (target link might have changed)
1261 // Update/Insert if we don't know if the last revision was a redirect or not
1262 // Delete if changing from redirect to non-redirect
1263 $isRedirect = !is_null( $redirectTitle );
1264
1265 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1266 return true;
1267 }
1268
1269 if ( $isRedirect ) {
1270 $this->insertRedirectEntry( $redirectTitle );
1271 } else {
1272 // This is not a redirect, remove row from redirect table
1273 $where = [ 'rd_from' => $this->getId() ];
1274 $dbw->delete( 'redirect', $where, __METHOD__ );
1275 }
1276
1277 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1278 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1279 }
1280
1281 return ( $dbw->affectedRows() != 0 );
1282 }
1283
1284 /**
1285 * If the given revision is newer than the currently set page_latest,
1286 * update the page record. Otherwise, do nothing.
1287 *
1288 * @deprecated since 1.24, use updateRevisionOn instead
1289 *
1290 * @param IDatabase $dbw
1291 * @param Revision $revision
1292 * @return bool
1293 */
1294 public function updateIfNewerOn( $dbw, $revision ) {
1295 $row = $dbw->selectRow(
1296 [ 'revision', 'page' ],
1297 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1298 [
1299 'page_id' => $this->getId(),
1300 'page_latest=rev_id' ],
1301 __METHOD__ );
1302
1303 if ( $row ) {
1304 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1305 return false;
1306 }
1307 $prev = $row->rev_id;
1308 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1309 } else {
1310 // No or missing previous revision; mark the page as new
1311 $prev = 0;
1312 $lastRevIsRedirect = null;
1313 }
1314
1315 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1316
1317 return $ret;
1318 }
1319
1320 /**
1321 * Get the content that needs to be saved in order to undo all revisions
1322 * between $undo and $undoafter. Revisions must belong to the same page,
1323 * must exist and must not be deleted
1324 * @param Revision $undo
1325 * @param Revision $undoafter Must be an earlier revision than $undo
1326 * @return Content|bool Content on success, false on failure
1327 * @since 1.21
1328 * Before we had the Content object, this was done in getUndoText
1329 */
1330 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1331 $handler = $undo->getContentHandler();
1332 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1333 }
1334
1335 /**
1336 * Returns true if this page's content model supports sections.
1337 *
1338 * @return bool
1339 *
1340 * @todo The skin should check this and not offer section functionality if
1341 * sections are not supported.
1342 * @todo The EditPage should check this and not offer section functionality
1343 * if sections are not supported.
1344 */
1345 public function supportsSections() {
1346 return $this->getContentHandler()->supportsSections();
1347 }
1348
1349 /**
1350 * @param string|int|null|bool $sectionId Section identifier as a number or string
1351 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1352 * or 'new' for a new section.
1353 * @param Content $sectionContent New content of the section.
1354 * @param string $sectionTitle New section's subject, only if $section is "new".
1355 * @param string $edittime Revision timestamp or null to use the current revision.
1356 *
1357 * @throws MWException
1358 * @return Content|null New complete article content, or null if error.
1359 *
1360 * @since 1.21
1361 * @deprecated since 1.24, use replaceSectionAtRev instead
1362 */
1363 public function replaceSectionContent(
1364 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1365 ) {
1366 $baseRevId = null;
1367 if ( $edittime && $sectionId !== 'new' ) {
1368 $dbr = wfGetDB( DB_REPLICA );
1369 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1370 // Try the master if this thread may have just added it.
1371 // This could be abstracted into a Revision method, but we don't want
1372 // to encourage loading of revisions by timestamp.
1373 if ( !$rev
1374 && wfGetLB()->getServerCount() > 1
1375 && wfGetLB()->hasOrMadeRecentMasterChanges()
1376 ) {
1377 $dbw = wfGetDB( DB_MASTER );
1378 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1379 }
1380 if ( $rev ) {
1381 $baseRevId = $rev->getId();
1382 }
1383 }
1384
1385 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1386 }
1387
1388 /**
1389 * @param string|int|null|bool $sectionId Section identifier as a number or string
1390 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1391 * or 'new' for a new section.
1392 * @param Content $sectionContent New content of the section.
1393 * @param string $sectionTitle New section's subject, only if $section is "new".
1394 * @param int|null $baseRevId
1395 *
1396 * @throws MWException
1397 * @return Content|null New complete article content, or null if error.
1398 *
1399 * @since 1.24
1400 */
1401 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1402 $sectionTitle = '', $baseRevId = null
1403 ) {
1404 if ( strval( $sectionId ) === '' ) {
1405 // Whole-page edit; let the whole text through
1406 $newContent = $sectionContent;
1407 } else {
1408 if ( !$this->supportsSections() ) {
1409 throw new MWException( "sections not supported for content model " .
1410 $this->getContentHandler()->getModelID() );
1411 }
1412
1413 // T32711: always use current version when adding a new section
1414 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1415 $oldContent = $this->getContent();
1416 } else {
1417 $rev = Revision::newFromId( $baseRevId );
1418 if ( !$rev ) {
1419 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1420 $this->getId() . "; section: $sectionId)\n" );
1421 return null;
1422 }
1423
1424 $oldContent = $rev->getContent();
1425 }
1426
1427 if ( !$oldContent ) {
1428 wfDebug( __METHOD__ . ": no page text\n" );
1429 return null;
1430 }
1431
1432 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1433 }
1434
1435 return $newContent;
1436 }
1437
1438 /**
1439 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1440 * @param int $flags
1441 * @return int Updated $flags
1442 */
1443 public function checkFlags( $flags ) {
1444 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1445 if ( $this->exists() ) {
1446 $flags |= EDIT_UPDATE;
1447 } else {
1448 $flags |= EDIT_NEW;
1449 }
1450 }
1451
1452 return $flags;
1453 }
1454
1455 /**
1456 * Change an existing article or create a new article. Updates RC and all necessary caches,
1457 * optionally via the deferred update array.
1458 *
1459 * @param Content $content New content
1460 * @param string $summary Edit summary
1461 * @param int $flags Bitfield:
1462 * EDIT_NEW
1463 * Article is known or assumed to be non-existent, create a new one
1464 * EDIT_UPDATE
1465 * Article is known or assumed to be pre-existing, update it
1466 * EDIT_MINOR
1467 * Mark this edit minor, if the user is allowed to do so
1468 * EDIT_SUPPRESS_RC
1469 * Do not log the change in recentchanges
1470 * EDIT_FORCE_BOT
1471 * Mark the edit a "bot" edit regardless of user rights
1472 * EDIT_AUTOSUMMARY
1473 * Fill in blank summaries with generated text where possible
1474 * EDIT_INTERNAL
1475 * Signal that the page retrieve/save cycle happened entirely in this request.
1476 *
1477 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1478 * article will be detected. If EDIT_UPDATE is specified and the article
1479 * doesn't exist, the function will return an edit-gone-missing error. If
1480 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1481 * error will be returned. These two conditions are also possible with
1482 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1483 *
1484 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1485 * This is not the parent revision ID, rather the revision ID for older
1486 * content used as the source for a rollback, for example.
1487 * @param User $user The user doing the edit
1488 * @param string $serialFormat Format for storing the content in the
1489 * database.
1490 * @param array|null $tags Change tags to apply to this edit
1491 * Callers are responsible for permission checks
1492 * (with ChangeTags::canAddTagsAccompanyingChange)
1493 * @param Int $undidRevId Id of revision that was undone or 0
1494 *
1495 * @throws MWException
1496 * @return Status Possible errors:
1497 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1498 * set the fatal flag of $status.
1499 * edit-gone-missing: In update mode, but the article didn't exist.
1500 * edit-conflict: In update mode, the article changed unexpectedly.
1501 * edit-no-change: Warning that the text was the same as before.
1502 * edit-already-exists: In creation mode, but the article already exists.
1503 *
1504 * Extensions may define additional errors.
1505 *
1506 * $return->value will contain an associative array with members as follows:
1507 * new: Boolean indicating if the function attempted to create a new article.
1508 * revision: The revision object for the inserted revision, or null.
1509 *
1510 * @since 1.21
1511 * @throws MWException
1512 */
1513 public function doEditContent(
1514 Content $content, $summary, $flags = 0, $baseRevId = false,
1515 User $user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1516 ) {
1517 global $wgUser, $wgUseAutomaticEditSummaries;
1518
1519 // Old default parameter for $tags was null
1520 if ( $tags === null ) {
1521 $tags = [];
1522 }
1523
1524 // Low-level sanity check
1525 if ( $this->mTitle->getText() === '' ) {
1526 throw new MWException( 'Something is trying to edit an article with an empty title' );
1527 }
1528 // Make sure the given content type is allowed for this page
1529 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1530 return Status::newFatal( 'content-not-allowed-here',
1531 ContentHandler::getLocalizedName( $content->getModel() ),
1532 $this->mTitle->getPrefixedText()
1533 );
1534 }
1535
1536 // Load the data from the master database if needed.
1537 // The caller may already loaded it from the master or even loaded it using
1538 // SELECT FOR UPDATE, so do not override that using clear().
1539 $this->loadPageData( 'fromdbmaster' );
1540
1541 $user = $user ?: $wgUser;
1542 $flags = $this->checkFlags( $flags );
1543
1544 // Avoid PHP 7.1 warning of passing $this by reference
1545 $wikiPage = $this;
1546
1547 // Trigger pre-save hook (using provided edit summary)
1548 $hookStatus = Status::newGood( [] );
1549 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1550 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1551 // Check if the hook rejected the attempted save
1552 if ( !Hooks::run( 'PageContentSave', $hook_args ) ) {
1553 if ( $hookStatus->isOK() ) {
1554 // Hook returned false but didn't call fatal(); use generic message
1555 $hookStatus->fatal( 'edit-hook-aborted' );
1556 }
1557
1558 return $hookStatus;
1559 }
1560
1561 $old_revision = $this->getRevision(); // current revision
1562 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1563
1564 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1565 $tags[] = 'mw-contentmodelchange';
1566 }
1567
1568 // Provide autosummaries if one is not provided and autosummaries are enabled
1569 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1570 $handler = $content->getContentHandler();
1571 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1572 }
1573
1574 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1575 if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1576 $useCache = false;
1577 } else {
1578 $useCache = true;
1579 }
1580
1581 // Get the pre-save transform content and final parser output
1582 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1583 $pstContent = $editInfo->pstContent; // Content object
1584 $meta = [
1585 'bot' => ( $flags & EDIT_FORCE_BOT ),
1586 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1587 'serialized' => $pstContent->serialize( $serialFormat ),
1588 'serialFormat' => $serialFormat,
1589 'baseRevId' => $baseRevId,
1590 'oldRevision' => $old_revision,
1591 'oldContent' => $old_content,
1592 'oldId' => $this->getLatest(),
1593 'oldIsRedirect' => $this->isRedirect(),
1594 'oldCountable' => $this->isCountable(),
1595 'tags' => ( $tags !== null ) ? (array)$tags : [],
1596 'undidRevId' => $undidRevId
1597 ];
1598
1599 // Actually create the revision and create/update the page
1600 if ( $flags & EDIT_UPDATE ) {
1601 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1602 } else {
1603 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1604 }
1605
1606 // Promote user to any groups they meet the criteria for
1607 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1608 $user->addAutopromoteOnceGroups( 'onEdit' );
1609 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1610 } );
1611
1612 return $status;
1613 }
1614
1615 /**
1616 * @param Content $content Pre-save transform content
1617 * @param int $flags
1618 * @param User $user
1619 * @param string $summary
1620 * @param array $meta
1621 * @return Status
1622 * @throws DBUnexpectedError
1623 * @throws Exception
1624 * @throws FatalError
1625 * @throws MWException
1626 */
1627 private function doModify(
1628 Content $content, $flags, User $user, $summary, array $meta
1629 ) {
1630 global $wgUseRCPatrol;
1631
1632 // Update article, but only if changed.
1633 $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1634
1635 // Convenience variables
1636 $now = wfTimestampNow();
1637 $oldid = $meta['oldId'];
1638 /** @var Content|null $oldContent */
1639 $oldContent = $meta['oldContent'];
1640 $newsize = $content->getSize();
1641
1642 if ( !$oldid ) {
1643 // Article gone missing
1644 $status->fatal( 'edit-gone-missing' );
1645
1646 return $status;
1647 } elseif ( !$oldContent ) {
1648 // Sanity check for T39225
1649 throw new MWException( "Could not find text for current revision {$oldid}." );
1650 }
1651
1652 // @TODO: pass content object?!
1653 $revision = new Revision( [
1654 'page' => $this->getId(),
1655 'title' => $this->mTitle, // for determining the default content model
1656 'comment' => $summary,
1657 'minor_edit' => $meta['minor'],
1658 'text' => $meta['serialized'],
1659 'len' => $newsize,
1660 'parent_id' => $oldid,
1661 'user' => $user->getId(),
1662 'user_text' => $user->getName(),
1663 'timestamp' => $now,
1664 'content_model' => $content->getModel(),
1665 'content_format' => $meta['serialFormat'],
1666 ] );
1667
1668 $changed = !$content->equals( $oldContent );
1669
1670 $dbw = wfGetDB( DB_MASTER );
1671
1672 if ( $changed ) {
1673 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1674 $status->merge( $prepStatus );
1675 if ( !$status->isOK() ) {
1676 return $status;
1677 }
1678
1679 $dbw->startAtomic( __METHOD__ );
1680 // Get the latest page_latest value while locking it.
1681 // Do a CAS style check to see if it's the same as when this method
1682 // started. If it changed then bail out before touching the DB.
1683 $latestNow = $this->lockAndGetLatest();
1684 if ( $latestNow != $oldid ) {
1685 $dbw->endAtomic( __METHOD__ );
1686 // Page updated or deleted in the mean time
1687 $status->fatal( 'edit-conflict' );
1688
1689 return $status;
1690 }
1691
1692 // At this point we are now comitted to returning an OK
1693 // status unless some DB query error or other exception comes up.
1694 // This way callers don't have to call rollback() if $status is bad
1695 // unless they actually try to catch exceptions (which is rare).
1696
1697 // Save the revision text
1698 $revisionId = $revision->insertOn( $dbw );
1699 // Update page_latest and friends to reflect the new revision
1700 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1701 throw new MWException( "Failed to update page row to use new revision." );
1702 }
1703
1704 Hooks::run( 'NewRevisionFromEditComplete',
1705 [ $this, $revision, $meta['baseRevId'], $user ] );
1706
1707 // Update recentchanges
1708 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1709 // Mark as patrolled if the user can do so
1710 $patrolled = $wgUseRCPatrol && !count(
1711 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1712 // Add RC row to the DB
1713 RecentChange::notifyEdit(
1714 $now,
1715 $this->mTitle,
1716 $revision->isMinor(),
1717 $user,
1718 $summary,
1719 $oldid,
1720 $this->getTimestamp(),
1721 $meta['bot'],
1722 '',
1723 $oldContent ? $oldContent->getSize() : 0,
1724 $newsize,
1725 $revisionId,
1726 $patrolled,
1727 $meta['tags']
1728 );
1729 }
1730
1731 $user->incEditCount();
1732
1733 $dbw->endAtomic( __METHOD__ );
1734 $this->mTimestamp = $now;
1735 } else {
1736 // T34948: revision ID must be set to page {{REVISIONID}} and
1737 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1738 $revision->setId( $this->getLatest() );
1739 $revision->setUserIdAndName(
1740 $this->getUser( Revision::RAW ),
1741 $this->getUserText( Revision::RAW )
1742 );
1743 }
1744
1745 if ( $changed ) {
1746 // Return the new revision to the caller
1747 $status->value['revision'] = $revision;
1748 } else {
1749 $status->warning( 'edit-no-change' );
1750 // Update page_touched as updateRevisionOn() was not called.
1751 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1752 $this->mTitle->invalidateCache( $now );
1753 }
1754
1755 // Do secondary updates once the main changes have been committed...
1756 DeferredUpdates::addUpdate(
1757 new AtomicSectionUpdate(
1758 $dbw,
1759 __METHOD__,
1760 function () use (
1761 $revision, &$user, $content, $summary, &$flags,
1762 $changed, $meta, &$status
1763 ) {
1764 // Update links tables, site stats, etc.
1765 $this->doEditUpdates(
1766 $revision,
1767 $user,
1768 [
1769 'changed' => $changed,
1770 'oldcountable' => $meta['oldCountable'],
1771 'oldrevision' => $meta['oldRevision']
1772 ]
1773 );
1774 // Avoid PHP 7.1 warning of passing $this by reference
1775 $wikiPage = $this;
1776 // Trigger post-save hook
1777 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR,
1778 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1779 $meta['undidRevId'] ];
1780 Hooks::run( 'PageContentSaveComplete', $params );
1781 }
1782 ),
1783 DeferredUpdates::PRESEND
1784 );
1785
1786 return $status;
1787 }
1788
1789 /**
1790 * @param Content $content Pre-save transform content
1791 * @param int $flags
1792 * @param User $user
1793 * @param string $summary
1794 * @param array $meta
1795 * @return Status
1796 * @throws DBUnexpectedError
1797 * @throws Exception
1798 * @throws FatalError
1799 * @throws MWException
1800 */
1801 private function doCreate(
1802 Content $content, $flags, User $user, $summary, array $meta
1803 ) {
1804 global $wgUseRCPatrol, $wgUseNPPatrol;
1805
1806 $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1807
1808 $now = wfTimestampNow();
1809 $newsize = $content->getSize();
1810 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1811 $status->merge( $prepStatus );
1812 if ( !$status->isOK() ) {
1813 return $status;
1814 }
1815
1816 $dbw = wfGetDB( DB_MASTER );
1817 $dbw->startAtomic( __METHOD__ );
1818
1819 // Add the page record unless one already exists for the title
1820 $newid = $this->insertOn( $dbw );
1821 if ( $newid === false ) {
1822 $dbw->endAtomic( __METHOD__ ); // nothing inserted
1823 $status->fatal( 'edit-already-exists' );
1824
1825 return $status; // nothing done
1826 }
1827
1828 // At this point we are now comitted to returning an OK
1829 // status unless some DB query error or other exception comes up.
1830 // This way callers don't have to call rollback() if $status is bad
1831 // unless they actually try to catch exceptions (which is rare).
1832
1833 // @TODO: pass content object?!
1834 $revision = new Revision( [
1835 'page' => $newid,
1836 'title' => $this->mTitle, // for determining the default content model
1837 'comment' => $summary,
1838 'minor_edit' => $meta['minor'],
1839 'text' => $meta['serialized'],
1840 'len' => $newsize,
1841 'user' => $user->getId(),
1842 'user_text' => $user->getName(),
1843 'timestamp' => $now,
1844 'content_model' => $content->getModel(),
1845 'content_format' => $meta['serialFormat'],
1846 ] );
1847
1848 // Save the revision text...
1849 $revisionId = $revision->insertOn( $dbw );
1850 // Update the page record with revision data
1851 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1852 throw new MWException( "Failed to update page row to use new revision." );
1853 }
1854
1855 Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1856
1857 // Update recentchanges
1858 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1859 // Mark as patrolled if the user can do so
1860 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1861 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1862 // Add RC row to the DB
1863 RecentChange::notifyNew(
1864 $now,
1865 $this->mTitle,
1866 $revision->isMinor(),
1867 $user,
1868 $summary,
1869 $meta['bot'],
1870 '',
1871 $newsize,
1872 $revisionId,
1873 $patrolled,
1874 $meta['tags']
1875 );
1876 }
1877
1878 $user->incEditCount();
1879
1880 $dbw->endAtomic( __METHOD__ );
1881 $this->mTimestamp = $now;
1882
1883 // Return the new revision to the caller
1884 $status->value['revision'] = $revision;
1885
1886 // Do secondary updates once the main changes have been committed...
1887 DeferredUpdates::addUpdate(
1888 new AtomicSectionUpdate(
1889 $dbw,
1890 __METHOD__,
1891 function () use (
1892 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1893 ) {
1894 // Update links, etc.
1895 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1896 // Avoid PHP 7.1 warning of passing $this by reference
1897 $wikiPage = $this;
1898 // Trigger post-create hook
1899 $params = [ &$wikiPage, &$user, $content, $summary,
1900 $flags & EDIT_MINOR, null, null, &$flags, $revision ];
1901 Hooks::run( 'PageContentInsertComplete', $params );
1902 // Trigger post-save hook
1903 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1904 Hooks::run( 'PageContentSaveComplete', $params );
1905 }
1906 ),
1907 DeferredUpdates::PRESEND
1908 );
1909
1910 return $status;
1911 }
1912
1913 /**
1914 * Get parser options suitable for rendering the primary article wikitext
1915 *
1916 * @see ContentHandler::makeParserOptions
1917 *
1918 * @param IContextSource|User|string $context One of the following:
1919 * - IContextSource: Use the User and the Language of the provided
1920 * context
1921 * - User: Use the provided User object and $wgLang for the language,
1922 * so use an IContextSource object if possible.
1923 * - 'canonical': Canonical options (anonymous user with default
1924 * preferences and content language).
1925 * @return ParserOptions
1926 */
1927 public function makeParserOptions( $context ) {
1928 $options = $this->getContentHandler()->makeParserOptions( $context );
1929
1930 if ( $this->getTitle()->isConversionTable() ) {
1931 // @todo ConversionTable should become a separate content model, so
1932 // we don't need special cases like this one.
1933 $options->disableContentConversion();
1934 }
1935
1936 return $options;
1937 }
1938
1939 /**
1940 * Prepare content which is about to be saved.
1941 *
1942 * Prior to 1.30, this returned a stdClass object with the same class
1943 * members.
1944 *
1945 * @param Content $content
1946 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1947 * revision ID is also accepted, but this is deprecated.
1948 * @param User|null $user
1949 * @param string|null $serialFormat
1950 * @param bool $useCache Check shared prepared edit cache
1951 *
1952 * @return PreparedEdit
1953 *
1954 * @since 1.21
1955 */
1956 public function prepareContentForEdit(
1957 Content $content, $revision = null, User $user = null,
1958 $serialFormat = null, $useCache = true
1959 ) {
1960 global $wgContLang, $wgUser, $wgAjaxEditStash;
1961
1962 if ( is_object( $revision ) ) {
1963 $revid = $revision->getId();
1964 } else {
1965 $revid = $revision;
1966 // This code path is deprecated, and nothing is known to
1967 // use it, so performance here shouldn't be a worry.
1968 if ( $revid !== null ) {
1969 wfDeprecated( __METHOD__ . ' with $revision = revision ID', '1.25' );
1970 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
1971 } else {
1972 $revision = null;
1973 }
1974 }
1975
1976 $user = is_null( $user ) ? $wgUser : $user;
1977 // XXX: check $user->getId() here???
1978
1979 // Use a sane default for $serialFormat, see T59026
1980 if ( $serialFormat === null ) {
1981 $serialFormat = $content->getContentHandler()->getDefaultFormat();
1982 }
1983
1984 if ( $this->mPreparedEdit
1985 && isset( $this->mPreparedEdit->newContent )
1986 && $this->mPreparedEdit->newContent->equals( $content )
1987 && $this->mPreparedEdit->revid == $revid
1988 && $this->mPreparedEdit->format == $serialFormat
1989 // XXX: also check $user here?
1990 ) {
1991 // Already prepared
1992 return $this->mPreparedEdit;
1993 }
1994
1995 // The edit may have already been prepared via api.php?action=stashedit
1996 $cachedEdit = $useCache && $wgAjaxEditStash
1997 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
1998 : false;
1999
2000 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2001 Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2002
2003 $edit = new PreparedEdit();
2004 if ( $cachedEdit ) {
2005 $edit->timestamp = $cachedEdit->timestamp;
2006 } else {
2007 $edit->timestamp = wfTimestampNow();
2008 }
2009 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2010 $edit->revid = $revid;
2011
2012 if ( $cachedEdit ) {
2013 $edit->pstContent = $cachedEdit->pstContent;
2014 } else {
2015 $edit->pstContent = $content
2016 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2017 : null;
2018 }
2019
2020 $edit->format = $serialFormat;
2021 $edit->popts = $this->makeParserOptions( 'canonical' );
2022 if ( $cachedEdit ) {
2023 $edit->output = $cachedEdit->output;
2024 } else {
2025 if ( $revision ) {
2026 // We get here if vary-revision is set. This means that this page references
2027 // itself (such as via self-transclusion). In this case, we need to make sure
2028 // that any such self-references refer to the newly-saved revision, and not
2029 // to the previous one, which could otherwise happen due to replica DB lag.
2030 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2031 $edit->popts->setCurrentRevisionCallback(
2032 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2033 if ( $title->equals( $revision->getTitle() ) ) {
2034 return $revision;
2035 } else {
2036 return call_user_func( $oldCallback, $title, $parser );
2037 }
2038 }
2039 );
2040 } else {
2041 // Try to avoid a second parse if {{REVISIONID}} is used
2042 $dbIndex = ( $this->mDataLoadedFrom & self::READ_LATEST ) === self::READ_LATEST
2043 ? DB_MASTER // use the best possible guess
2044 : DB_REPLICA; // T154554
2045
2046 $edit->popts->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2047 return 1 + (int)wfGetDB( $dbIndex )->selectField(
2048 'revision',
2049 'MAX(rev_id)',
2050 [],
2051 __METHOD__
2052 );
2053 } );
2054 }
2055 $edit->output = $edit->pstContent
2056 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2057 : null;
2058 }
2059
2060 $edit->newContent = $content;
2061 $edit->oldContent = $this->getContent( Revision::RAW );
2062
2063 // NOTE: B/C for hooks! don't use these fields!
2064 $edit->newText = $edit->newContent
2065 ? ContentHandler::getContentText( $edit->newContent )
2066 : '';
2067 $edit->oldText = $edit->oldContent
2068 ? ContentHandler::getContentText( $edit->oldContent )
2069 : '';
2070 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2071
2072 if ( $edit->output ) {
2073 $edit->output->setCacheTime( wfTimestampNow() );
2074 }
2075
2076 // Process cache the result
2077 $this->mPreparedEdit = $edit;
2078
2079 return $edit;
2080 }
2081
2082 /**
2083 * Do standard deferred updates after page edit.
2084 * Update links tables, site stats, search index and message cache.
2085 * Purges pages that include this page if the text was changed here.
2086 * Every 100th edit, prune the recent changes table.
2087 *
2088 * @param Revision $revision
2089 * @param User $user User object that did the revision
2090 * @param array $options Array of options, following indexes are used:
2091 * - changed: bool, whether the revision changed the content (default true)
2092 * - created: bool, whether the revision created the page (default false)
2093 * - moved: bool, whether the page was moved (default false)
2094 * - restored: bool, whether the page was undeleted (default false)
2095 * - oldrevision: Revision object for the pre-update revision (default null)
2096 * - oldcountable: bool, null, or string 'no-change' (default null):
2097 * - bool: whether the page was counted as an article before that
2098 * revision, only used in changed is true and created is false
2099 * - null: if created is false, don't update the article count; if created
2100 * is true, do update the article count
2101 * - 'no-change': don't update the article count, ever
2102 */
2103 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2104 global $wgRCWatchCategoryMembership;
2105
2106 $options += [
2107 'changed' => true,
2108 'created' => false,
2109 'moved' => false,
2110 'restored' => false,
2111 'oldrevision' => null,
2112 'oldcountable' => null
2113 ];
2114 $content = $revision->getContent();
2115
2116 $logger = LoggerFactory::getInstance( 'SaveParse' );
2117
2118 // See if the parser output before $revision was inserted is still valid
2119 $editInfo = false;
2120 if ( !$this->mPreparedEdit ) {
2121 $logger->debug( __METHOD__ . ": No prepared edit...\n" );
2122 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2123 $logger->info( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2124 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision-id' )
2125 && $this->mPreparedEdit->output->getSpeculativeRevIdUsed() !== $revision->getId()
2126 ) {
2127 $logger->info( __METHOD__ . ": Prepared edit has vary-revision-id with wrong ID...\n" );
2128 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2129 $logger->info( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2130 } else {
2131 wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2132 $editInfo = $this->mPreparedEdit;
2133 }
2134
2135 if ( !$editInfo ) {
2136 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2137 // $text is usually already pre-save transformed once. Avoid using the edit stash
2138 // as any prepared content from there or in doEditContent() was already rejected.
2139 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2140 }
2141
2142 // Save it to the parser cache.
2143 // Make sure the cache time matches page_touched to avoid double parsing.
2144 MediaWikiServices::getInstance()->getParserCache()->save(
2145 $editInfo->output, $this, $editInfo->popts,
2146 $revision->getTimestamp(), $editInfo->revid
2147 );
2148
2149 // Update the links tables and other secondary data
2150 if ( $content ) {
2151 $recursive = $options['changed']; // T52785
2152 $updates = $content->getSecondaryDataUpdates(
2153 $this->getTitle(), null, $recursive, $editInfo->output
2154 );
2155 foreach ( $updates as $update ) {
2156 $update->setCause( 'edit-page', $user->getName() );
2157 if ( $update instanceof LinksUpdate ) {
2158 $update->setRevision( $revision );
2159 $update->setTriggeringUser( $user );
2160 }
2161 DeferredUpdates::addUpdate( $update );
2162 }
2163 if ( $wgRCWatchCategoryMembership
2164 && $this->getContentHandler()->supportsCategories() === true
2165 && ( $options['changed'] || $options['created'] )
2166 && !$options['restored']
2167 ) {
2168 // Note: jobs are pushed after deferred updates, so the job should be able to see
2169 // the recent change entry (also done via deferred updates) and carry over any
2170 // bot/deletion/IP flags, ect.
2171 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2172 $this->getTitle(),
2173 [
2174 'pageId' => $this->getId(),
2175 'revTimestamp' => $revision->getTimestamp()
2176 ]
2177 ) );
2178 }
2179 }
2180
2181 // Avoid PHP 7.1 warning of passing $this by reference
2182 $wikiPage = $this;
2183
2184 Hooks::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2185
2186 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2187 // Flush old entries from the `recentchanges` table
2188 if ( mt_rand( 0, 9 ) == 0 ) {
2189 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2190 }
2191 }
2192
2193 if ( !$this->exists() ) {
2194 return;
2195 }
2196
2197 $id = $this->getId();
2198 $title = $this->mTitle->getPrefixedDBkey();
2199 $shortTitle = $this->mTitle->getDBkey();
2200
2201 if ( $options['oldcountable'] === 'no-change' ||
2202 ( !$options['changed'] && !$options['moved'] )
2203 ) {
2204 $good = 0;
2205 } elseif ( $options['created'] ) {
2206 $good = (int)$this->isCountable( $editInfo );
2207 } elseif ( $options['oldcountable'] !== null ) {
2208 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2209 } else {
2210 $good = 0;
2211 }
2212 $edits = $options['changed'] ? 1 : 0;
2213 $total = $options['created'] ? 1 : 0;
2214
2215 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2216 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2217
2218 // If this is another user's talk page, update newtalk.
2219 // Don't do this if $options['changed'] = false (null-edits) nor if
2220 // it's a minor edit and the user doesn't want notifications for those.
2221 if ( $options['changed']
2222 && $this->mTitle->getNamespace() == NS_USER_TALK
2223 && $shortTitle != $user->getTitleKey()
2224 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2225 ) {
2226 $recipient = User::newFromName( $shortTitle, false );
2227 if ( !$recipient ) {
2228 wfDebug( __METHOD__ . ": invalid username\n" );
2229 } else {
2230 // Avoid PHP 7.1 warning of passing $this by reference
2231 $wikiPage = $this;
2232
2233 // Allow extensions to prevent user notification
2234 // when a new message is added to their talk page
2235 if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2236 if ( User::isIP( $shortTitle ) ) {
2237 // An anonymous user
2238 $recipient->setNewtalk( true, $revision );
2239 } elseif ( $recipient->isLoggedIn() ) {
2240 $recipient->setNewtalk( true, $revision );
2241 } else {
2242 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2243 }
2244 }
2245 }
2246 }
2247
2248 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2249 MessageCache::singleton()->updateMessageOverride( $this->mTitle, $content );
2250 }
2251
2252 if ( $options['created'] ) {
2253 self::onArticleCreate( $this->mTitle );
2254 } elseif ( $options['changed'] ) { // T52785
2255 self::onArticleEdit( $this->mTitle, $revision );
2256 }
2257
2258 ResourceLoaderWikiModule::invalidateModuleCache(
2259 $this->mTitle, $options['oldrevision'], $revision, wfWikiID()
2260 );
2261 }
2262
2263 /**
2264 * Update the article's restriction field, and leave a log entry.
2265 * This works for protection both existing and non-existing pages.
2266 *
2267 * @param array $limit Set of restriction keys
2268 * @param array $expiry Per restriction type expiration
2269 * @param int &$cascade Set to false if cascading protection isn't allowed.
2270 * @param string $reason
2271 * @param User $user The user updating the restrictions
2272 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2273 * ($user should be able to add the specified tags before this is called)
2274 * @return Status Status object; if action is taken, $status->value is the log_id of the
2275 * protection log entry.
2276 */
2277 public function doUpdateRestrictions( array $limit, array $expiry,
2278 &$cascade, $reason, User $user, $tags = null
2279 ) {
2280 global $wgCascadingRestrictionLevels;
2281
2282 if ( wfReadOnly() ) {
2283 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2284 }
2285
2286 $this->loadPageData( 'fromdbmaster' );
2287 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2288 $id = $this->getId();
2289
2290 if ( !$cascade ) {
2291 $cascade = false;
2292 }
2293
2294 // Take this opportunity to purge out expired restrictions
2295 Title::purgeExpiredRestrictions();
2296
2297 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2298 // we expect a single selection, but the schema allows otherwise.
2299 $isProtected = false;
2300 $protect = false;
2301 $changed = false;
2302
2303 $dbw = wfGetDB( DB_MASTER );
2304
2305 foreach ( $restrictionTypes as $action ) {
2306 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2307 $expiry[$action] = 'infinity';
2308 }
2309 if ( !isset( $limit[$action] ) ) {
2310 $limit[$action] = '';
2311 } elseif ( $limit[$action] != '' ) {
2312 $protect = true;
2313 }
2314
2315 // Get current restrictions on $action
2316 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2317 if ( $current != '' ) {
2318 $isProtected = true;
2319 }
2320
2321 if ( $limit[$action] != $current ) {
2322 $changed = true;
2323 } elseif ( $limit[$action] != '' ) {
2324 // Only check expiry change if the action is actually being
2325 // protected, since expiry does nothing on an not-protected
2326 // action.
2327 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2328 $changed = true;
2329 }
2330 }
2331 }
2332
2333 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2334 $changed = true;
2335 }
2336
2337 // If nothing has changed, do nothing
2338 if ( !$changed ) {
2339 return Status::newGood();
2340 }
2341
2342 if ( !$protect ) { // No protection at all means unprotection
2343 $revCommentMsg = 'unprotectedarticle-comment';
2344 $logAction = 'unprotect';
2345 } elseif ( $isProtected ) {
2346 $revCommentMsg = 'modifiedarticleprotection-comment';
2347 $logAction = 'modify';
2348 } else {
2349 $revCommentMsg = 'protectedarticle-comment';
2350 $logAction = 'protect';
2351 }
2352
2353 $logRelationsValues = [];
2354 $logRelationsField = null;
2355 $logParamsDetails = [];
2356
2357 // Null revision (used for change tag insertion)
2358 $nullRevision = null;
2359
2360 if ( $id ) { // Protection of existing page
2361 // Avoid PHP 7.1 warning of passing $this by reference
2362 $wikiPage = $this;
2363
2364 if ( !Hooks::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2365 return Status::newGood();
2366 }
2367
2368 // Only certain restrictions can cascade...
2369 $editrestriction = isset( $limit['edit'] )
2370 ? [ $limit['edit'] ]
2371 : $this->mTitle->getRestrictions( 'edit' );
2372 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2373 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2374 }
2375 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2376 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2377 }
2378
2379 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2380 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2381 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2382 }
2383 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2384 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2385 }
2386
2387 // The schema allows multiple restrictions
2388 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2389 $cascade = false;
2390 }
2391
2392 // insert null revision to identify the page protection change as edit summary
2393 $latest = $this->getLatest();
2394 $nullRevision = $this->insertProtectNullRevision(
2395 $revCommentMsg,
2396 $limit,
2397 $expiry,
2398 $cascade,
2399 $reason,
2400 $user
2401 );
2402
2403 if ( $nullRevision === null ) {
2404 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2405 }
2406
2407 $logRelationsField = 'pr_id';
2408
2409 // Update restrictions table
2410 foreach ( $limit as $action => $restrictions ) {
2411 $dbw->delete(
2412 'page_restrictions',
2413 [
2414 'pr_page' => $id,
2415 'pr_type' => $action
2416 ],
2417 __METHOD__
2418 );
2419 if ( $restrictions != '' ) {
2420 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2421 $dbw->insert(
2422 'page_restrictions',
2423 [
2424 'pr_page' => $id,
2425 'pr_type' => $action,
2426 'pr_level' => $restrictions,
2427 'pr_cascade' => $cascadeValue,
2428 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2429 ],
2430 __METHOD__
2431 );
2432 $logRelationsValues[] = $dbw->insertId();
2433 $logParamsDetails[] = [
2434 'type' => $action,
2435 'level' => $restrictions,
2436 'expiry' => $expiry[$action],
2437 'cascade' => (bool)$cascadeValue,
2438 ];
2439 }
2440 }
2441
2442 // Clear out legacy restriction fields
2443 $dbw->update(
2444 'page',
2445 [ 'page_restrictions' => '' ],
2446 [ 'page_id' => $id ],
2447 __METHOD__
2448 );
2449
2450 // Avoid PHP 7.1 warning of passing $this by reference
2451 $wikiPage = $this;
2452
2453 Hooks::run( 'NewRevisionFromEditComplete',
2454 [ $this, $nullRevision, $latest, $user ] );
2455 Hooks::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2456 } else { // Protection of non-existing page (also known as "title protection")
2457 // Cascade protection is meaningless in this case
2458 $cascade = false;
2459
2460 if ( $limit['create'] != '' ) {
2461 $commentFields = CommentStore::newKey( 'pt_reason' )->insert( $dbw, $reason );
2462 $dbw->replace( 'protected_titles',
2463 [ [ 'pt_namespace', 'pt_title' ] ],
2464 [
2465 'pt_namespace' => $this->mTitle->getNamespace(),
2466 'pt_title' => $this->mTitle->getDBkey(),
2467 'pt_create_perm' => $limit['create'],
2468 'pt_timestamp' => $dbw->timestamp(),
2469 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2470 'pt_user' => $user->getId(),
2471 ] + $commentFields, __METHOD__
2472 );
2473 $logParamsDetails[] = [
2474 'type' => 'create',
2475 'level' => $limit['create'],
2476 'expiry' => $expiry['create'],
2477 ];
2478 } else {
2479 $dbw->delete( 'protected_titles',
2480 [
2481 'pt_namespace' => $this->mTitle->getNamespace(),
2482 'pt_title' => $this->mTitle->getDBkey()
2483 ], __METHOD__
2484 );
2485 }
2486 }
2487
2488 $this->mTitle->flushRestrictions();
2489 InfoAction::invalidateCache( $this->mTitle );
2490
2491 if ( $logAction == 'unprotect' ) {
2492 $params = [];
2493 } else {
2494 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2495 $params = [
2496 '4::description' => $protectDescriptionLog, // parameter for IRC
2497 '5:bool:cascade' => $cascade,
2498 'details' => $logParamsDetails, // parameter for localize and api
2499 ];
2500 }
2501
2502 // Update the protection log
2503 $logEntry = new ManualLogEntry( 'protect', $logAction );
2504 $logEntry->setTarget( $this->mTitle );
2505 $logEntry->setComment( $reason );
2506 $logEntry->setPerformer( $user );
2507 $logEntry->setParameters( $params );
2508 if ( !is_null( $nullRevision ) ) {
2509 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2510 }
2511 $logEntry->setTags( $tags );
2512 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2513 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2514 }
2515 $logId = $logEntry->insert();
2516 $logEntry->publish( $logId );
2517
2518 return Status::newGood( $logId );
2519 }
2520
2521 /**
2522 * Insert a new null revision for this page.
2523 *
2524 * @param string $revCommentMsg Comment message key for the revision
2525 * @param array $limit Set of restriction keys
2526 * @param array $expiry Per restriction type expiration
2527 * @param int $cascade Set to false if cascading protection isn't allowed.
2528 * @param string $reason
2529 * @param User|null $user
2530 * @return Revision|null Null on error
2531 */
2532 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2533 array $expiry, $cascade, $reason, $user = null
2534 ) {
2535 $dbw = wfGetDB( DB_MASTER );
2536
2537 // Prepare a null revision to be added to the history
2538 $editComment = wfMessage(
2539 $revCommentMsg,
2540 $this->mTitle->getPrefixedText(),
2541 $user ? $user->getName() : ''
2542 )->inContentLanguage()->text();
2543 if ( $reason ) {
2544 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2545 }
2546 $protectDescription = $this->protectDescription( $limit, $expiry );
2547 if ( $protectDescription ) {
2548 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2549 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2550 ->inContentLanguage()->text();
2551 }
2552 if ( $cascade ) {
2553 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2554 $editComment .= wfMessage( 'brackets' )->params(
2555 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2556 )->inContentLanguage()->text();
2557 }
2558
2559 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2560 if ( $nullRev ) {
2561 $nullRev->insertOn( $dbw );
2562
2563 // Update page record and touch page
2564 $oldLatest = $nullRev->getParentId();
2565 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2566 }
2567
2568 return $nullRev;
2569 }
2570
2571 /**
2572 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2573 * @return string
2574 */
2575 protected function formatExpiry( $expiry ) {
2576 global $wgContLang;
2577
2578 if ( $expiry != 'infinity' ) {
2579 return wfMessage(
2580 'protect-expiring',
2581 $wgContLang->timeanddate( $expiry, false, false ),
2582 $wgContLang->date( $expiry, false, false ),
2583 $wgContLang->time( $expiry, false, false )
2584 )->inContentLanguage()->text();
2585 } else {
2586 return wfMessage( 'protect-expiry-indefinite' )
2587 ->inContentLanguage()->text();
2588 }
2589 }
2590
2591 /**
2592 * Builds the description to serve as comment for the edit.
2593 *
2594 * @param array $limit Set of restriction keys
2595 * @param array $expiry Per restriction type expiration
2596 * @return string
2597 */
2598 public function protectDescription( array $limit, array $expiry ) {
2599 $protectDescription = '';
2600
2601 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2602 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2603 # All possible message keys are listed here for easier grepping:
2604 # * restriction-create
2605 # * restriction-edit
2606 # * restriction-move
2607 # * restriction-upload
2608 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2609 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2610 # with '' filtered out. All possible message keys are listed below:
2611 # * protect-level-autoconfirmed
2612 # * protect-level-sysop
2613 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2614 ->inContentLanguage()->text();
2615
2616 $expiryText = $this->formatExpiry( $expiry[$action] );
2617
2618 if ( $protectDescription !== '' ) {
2619 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2620 }
2621 $protectDescription .= wfMessage( 'protect-summary-desc' )
2622 ->params( $actionText, $restrictionsText, $expiryText )
2623 ->inContentLanguage()->text();
2624 }
2625
2626 return $protectDescription;
2627 }
2628
2629 /**
2630 * Builds the description to serve as comment for the log entry.
2631 *
2632 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2633 * protect description text. Keep them in old format to avoid breaking compatibility.
2634 * TODO: Fix protection log to store structured description and format it on-the-fly.
2635 *
2636 * @param array $limit Set of restriction keys
2637 * @param array $expiry Per restriction type expiration
2638 * @return string
2639 */
2640 public function protectDescriptionLog( array $limit, array $expiry ) {
2641 global $wgContLang;
2642
2643 $protectDescriptionLog = '';
2644
2645 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2646 $expiryText = $this->formatExpiry( $expiry[$action] );
2647 $protectDescriptionLog .= $wgContLang->getDirMark() .
2648 "[$action=$restrictions] ($expiryText)";
2649 }
2650
2651 return trim( $protectDescriptionLog );
2652 }
2653
2654 /**
2655 * Take an array of page restrictions and flatten it to a string
2656 * suitable for insertion into the page_restrictions field.
2657 *
2658 * @param string[] $limit
2659 *
2660 * @throws MWException
2661 * @return string
2662 */
2663 protected static function flattenRestrictions( $limit ) {
2664 if ( !is_array( $limit ) ) {
2665 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2666 }
2667
2668 $bits = [];
2669 ksort( $limit );
2670
2671 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2672 $bits[] = "$action=$restrictions";
2673 }
2674
2675 return implode( ':', $bits );
2676 }
2677
2678 /**
2679 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2680 * backwards compatibility, if you care about error reporting you should use
2681 * doDeleteArticleReal() instead.
2682 *
2683 * Deletes the article with database consistency, writes logs, purges caches
2684 *
2685 * @param string $reason Delete reason for deletion log
2686 * @param bool $suppress Suppress all revisions and log the deletion in
2687 * the suppression log instead of the deletion log
2688 * @param int $u1 Unused
2689 * @param bool $u2 Unused
2690 * @param array|string &$error Array of errors to append to
2691 * @param User $user The deleting user
2692 * @return bool True if successful
2693 */
2694 public function doDeleteArticle(
2695 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2696 ) {
2697 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2698 return $status->isGood();
2699 }
2700
2701 /**
2702 * Back-end article deletion
2703 * Deletes the article with database consistency, writes logs, purges caches
2704 *
2705 * @since 1.19
2706 *
2707 * @param string $reason Delete reason for deletion log
2708 * @param bool $suppress Suppress all revisions and log the deletion in
2709 * the suppression log instead of the deletion log
2710 * @param int $u1 Unused
2711 * @param bool $u2 Unused
2712 * @param array|string &$error Array of errors to append to
2713 * @param User $user The deleting user
2714 * @param array $tags Tags to apply to the deletion action
2715 * @param string $logsubtype
2716 * @return Status Status object; if successful, $status->value is the log_id of the
2717 * deletion log entry. If the page couldn't be deleted because it wasn't
2718 * found, $status is a non-fatal 'cannotdelete' error
2719 */
2720 public function doDeleteArticleReal(
2721 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2722 $tags = [], $logsubtype = 'delete'
2723 ) {
2724 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2725
2726 wfDebug( __METHOD__ . "\n" );
2727
2728 $status = Status::newGood();
2729
2730 if ( $this->mTitle->getDBkey() === '' ) {
2731 $status->error( 'cannotdelete',
2732 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2733 return $status;
2734 }
2735
2736 // Avoid PHP 7.1 warning of passing $this by reference
2737 $wikiPage = $this;
2738
2739 $user = is_null( $user ) ? $wgUser : $user;
2740 if ( !Hooks::run( 'ArticleDelete',
2741 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2742 ) ) {
2743 if ( $status->isOK() ) {
2744 // Hook aborted but didn't set a fatal status
2745 $status->fatal( 'delete-hook-aborted' );
2746 }
2747 return $status;
2748 }
2749
2750 $dbw = wfGetDB( DB_MASTER );
2751 $dbw->startAtomic( __METHOD__ );
2752
2753 $this->loadPageData( self::READ_LATEST );
2754 $id = $this->getId();
2755 // T98706: lock the page from various other updates but avoid using
2756 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2757 // the revisions queries (which also JOIN on user). Only lock the page
2758 // row and CAS check on page_latest to see if the trx snapshot matches.
2759 $lockedLatest = $this->lockAndGetLatest();
2760 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2761 $dbw->endAtomic( __METHOD__ );
2762 // Page not there or trx snapshot is stale
2763 $status->error( 'cannotdelete',
2764 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2765 return $status;
2766 }
2767
2768 // Given the lock above, we can be confident in the title and page ID values
2769 $namespace = $this->getTitle()->getNamespace();
2770 $dbKey = $this->getTitle()->getDBkey();
2771
2772 // At this point we are now comitted to returning an OK
2773 // status unless some DB query error or other exception comes up.
2774 // This way callers don't have to call rollback() if $status is bad
2775 // unless they actually try to catch exceptions (which is rare).
2776
2777 // we need to remember the old content so we can use it to generate all deletion updates.
2778 $revision = $this->getRevision();
2779 try {
2780 $content = $this->getContent( Revision::RAW );
2781 } catch ( Exception $ex ) {
2782 wfLogWarning( __METHOD__ . ': failed to load content during deletion! '
2783 . $ex->getMessage() );
2784
2785 $content = null;
2786 }
2787
2788 $revCommentStore = new CommentStore( 'rev_comment' );
2789 $arCommentStore = new CommentStore( 'ar_comment' );
2790
2791 $fields = Revision::selectFields();
2792 $bitfield = false;
2793
2794 // Bitfields to further suppress the content
2795 if ( $suppress ) {
2796 $bitfield = Revision::SUPPRESSED_ALL;
2797 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2798 }
2799
2800 // For now, shunt the revision data into the archive table.
2801 // Text is *not* removed from the text table; bulk storage
2802 // is left intact to avoid breaking block-compression or
2803 // immutable storage schemes.
2804 // In the future, we may keep revisions and mark them with
2805 // the rev_deleted field, which is reserved for this purpose.
2806
2807 // Get all of the page revisions
2808 $commentQuery = $revCommentStore->getJoin();
2809 $res = $dbw->select(
2810 [ 'revision' ] + $commentQuery['tables'],
2811 $fields + $commentQuery['fields'],
2812 [ 'rev_page' => $id ],
2813 __METHOD__,
2814 'FOR UPDATE',
2815 $commentQuery['joins']
2816 );
2817
2818 // Build their equivalent archive rows
2819 $rowsInsert = [];
2820 $revids = [];
2821
2822 /** @var int[] Revision IDs of edits that were made by IPs */
2823 $ipRevIds = [];
2824
2825 foreach ( $res as $row ) {
2826 $comment = $revCommentStore->getComment( $row );
2827 $rowInsert = [
2828 'ar_namespace' => $namespace,
2829 'ar_title' => $dbKey,
2830 'ar_user' => $row->rev_user,
2831 'ar_user_text' => $row->rev_user_text,
2832 'ar_timestamp' => $row->rev_timestamp,
2833 'ar_minor_edit' => $row->rev_minor_edit,
2834 'ar_rev_id' => $row->rev_id,
2835 'ar_parent_id' => $row->rev_parent_id,
2836 'ar_text_id' => $row->rev_text_id,
2837 'ar_text' => '',
2838 'ar_flags' => '',
2839 'ar_len' => $row->rev_len,
2840 'ar_page_id' => $id,
2841 'ar_deleted' => $suppress ? $bitfield : $row->rev_deleted,
2842 'ar_sha1' => $row->rev_sha1,
2843 ] + $arCommentStore->insert( $dbw, $comment );
2844 if ( $wgContentHandlerUseDB ) {
2845 $rowInsert['ar_content_model'] = $row->rev_content_model;
2846 $rowInsert['ar_content_format'] = $row->rev_content_format;
2847 }
2848 $rowsInsert[] = $rowInsert;
2849 $revids[] = $row->rev_id;
2850
2851 // Keep track of IP edits, so that the corresponding rows can
2852 // be deleted in the ip_changes table.
2853 if ( (int)$row->rev_user === 0 && IP::isValid( $row->rev_user_text ) ) {
2854 $ipRevIds[] = $row->rev_id;
2855 }
2856 }
2857 // Copy them into the archive table
2858 $dbw->insert( 'archive', $rowsInsert, __METHOD__ );
2859 // Save this so we can pass it to the ArticleDeleteComplete hook.
2860 $archivedRevisionCount = $dbw->affectedRows();
2861
2862 // Clone the title and wikiPage, so we have the information we need when
2863 // we log and run the ArticleDeleteComplete hook.
2864 $logTitle = clone $this->mTitle;
2865 $wikiPageBeforeDelete = clone $this;
2866
2867 // Now that it's safely backed up, delete it
2868 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2869 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2870 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD ) {
2871 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__ );
2872 }
2873
2874 // Also delete records from ip_changes as applicable.
2875 if ( count( $ipRevIds ) > 0 ) {
2876 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__ );
2877 }
2878
2879 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2880 $logtype = $suppress ? 'suppress' : 'delete';
2881
2882 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2883 $logEntry->setPerformer( $user );
2884 $logEntry->setTarget( $logTitle );
2885 $logEntry->setComment( $reason );
2886 $logEntry->setTags( $tags );
2887 $logid = $logEntry->insert();
2888
2889 $dbw->onTransactionPreCommitOrIdle(
2890 function () use ( $dbw, $logEntry, $logid ) {
2891 // T58776: avoid deadlocks (especially from FileDeleteForm)
2892 $logEntry->publish( $logid );
2893 },
2894 __METHOD__
2895 );
2896
2897 $dbw->endAtomic( __METHOD__ );
2898
2899 $this->doDeleteUpdates( $id, $content, $revision, $user );
2900
2901 Hooks::run( 'ArticleDeleteComplete', [
2902 &$wikiPageBeforeDelete,
2903 &$user,
2904 $reason,
2905 $id,
2906 $content,
2907 $logEntry,
2908 $archivedRevisionCount
2909 ] );
2910 $status->value = $logid;
2911
2912 // Show log excerpt on 404 pages rather than just a link
2913 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
2914 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2915 $cache->set( $key, 1, $cache::TTL_DAY );
2916
2917 return $status;
2918 }
2919
2920 /**
2921 * Lock the page row for this title+id and return page_latest (or 0)
2922 *
2923 * @return int Returns 0 if no row was found with this title+id
2924 * @since 1.27
2925 */
2926 public function lockAndGetLatest() {
2927 return (int)wfGetDB( DB_MASTER )->selectField(
2928 'page',
2929 'page_latest',
2930 [
2931 'page_id' => $this->getId(),
2932 // Typically page_id is enough, but some code might try to do
2933 // updates assuming the title is the same, so verify that
2934 'page_namespace' => $this->getTitle()->getNamespace(),
2935 'page_title' => $this->getTitle()->getDBkey()
2936 ],
2937 __METHOD__,
2938 [ 'FOR UPDATE' ]
2939 );
2940 }
2941
2942 /**
2943 * Do some database updates after deletion
2944 *
2945 * @param int $id The page_id value of the page being deleted
2946 * @param Content|null $content Optional page content to be used when determining
2947 * the required updates. This may be needed because $this->getContent()
2948 * may already return null when the page proper was deleted.
2949 * @param Revision|null $revision The latest page revision
2950 * @param User|null $user The user that caused the deletion
2951 */
2952 public function doDeleteUpdates(
2953 $id, Content $content = null, Revision $revision = null, User $user = null
2954 ) {
2955 try {
2956 $countable = $this->isCountable();
2957 } catch ( Exception $ex ) {
2958 // fallback for deleting broken pages for which we cannot load the content for
2959 // some reason. Note that doDeleteArticleReal() already logged this problem.
2960 $countable = false;
2961 }
2962
2963 // Update site status
2964 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2965
2966 // Delete pagelinks, update secondary indexes, etc
2967 $updates = $this->getDeletionUpdates( $content );
2968 foreach ( $updates as $update ) {
2969 DeferredUpdates::addUpdate( $update );
2970 }
2971
2972 $causeAgent = $user ? $user->getName() : 'unknown';
2973 // Reparse any pages transcluding this page
2974 LinksUpdate::queueRecursiveJobsForTable(
2975 $this->mTitle, 'templatelinks', 'delete-page', $causeAgent );
2976 // Reparse any pages including this image
2977 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2978 LinksUpdate::queueRecursiveJobsForTable(
2979 $this->mTitle, 'imagelinks', 'delete-page', $causeAgent );
2980 }
2981
2982 // Clear caches
2983 self::onArticleDelete( $this->mTitle );
2984 ResourceLoaderWikiModule::invalidateModuleCache(
2985 $this->mTitle, $revision, null, wfWikiID()
2986 );
2987
2988 // Reset this object and the Title object
2989 $this->loadFromRow( false, self::READ_LATEST );
2990
2991 // Search engine
2992 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2993 }
2994
2995 /**
2996 * Roll back the most recent consecutive set of edits to a page
2997 * from the same user; fails if there are no eligible edits to
2998 * roll back to, e.g. user is the sole contributor. This function
2999 * performs permissions checks on $user, then calls commitRollback()
3000 * to do the dirty work
3001 *
3002 * @todo Separate the business/permission stuff out from backend code
3003 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3004 *
3005 * @param string $fromP Name of the user whose edits to rollback.
3006 * @param string $summary Custom summary. Set to default summary if empty.
3007 * @param string $token Rollback token.
3008 * @param bool $bot If true, mark all reverted edits as bot.
3009 *
3010 * @param array &$resultDetails Array contains result-specific array of additional values
3011 * 'alreadyrolled' : 'current' (rev)
3012 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3013 *
3014 * @param User $user The user performing the rollback
3015 * @param array|null $tags Change tags to apply to the rollback
3016 * Callers are responsible for permission checks
3017 * (with ChangeTags::canAddTagsAccompanyingChange)
3018 *
3019 * @return array Array of errors, each error formatted as
3020 * array(messagekey, param1, param2, ...).
3021 * On success, the array is empty. This array can also be passed to
3022 * OutputPage::showPermissionsErrorPage().
3023 */
3024 public function doRollback(
3025 $fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3026 ) {
3027 $resultDetails = null;
3028
3029 // Check permissions
3030 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3031 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3032 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3033
3034 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3035 $errors[] = [ 'sessionfailure' ];
3036 }
3037
3038 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3039 $errors[] = [ 'actionthrottledtext' ];
3040 }
3041
3042 // If there were errors, bail out now
3043 if ( !empty( $errors ) ) {
3044 return $errors;
3045 }
3046
3047 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3048 }
3049
3050 /**
3051 * Backend implementation of doRollback(), please refer there for parameter
3052 * and return value documentation
3053 *
3054 * NOTE: This function does NOT check ANY permissions, it just commits the
3055 * rollback to the DB. Therefore, you should only call this function direct-
3056 * ly if you want to use custom permissions checks. If you don't, use
3057 * doRollback() instead.
3058 * @param string $fromP Name of the user whose edits to rollback.
3059 * @param string $summary Custom summary. Set to default summary if empty.
3060 * @param bool $bot If true, mark all reverted edits as bot.
3061 *
3062 * @param array &$resultDetails Contains result-specific array of additional values
3063 * @param User $guser The user performing the rollback
3064 * @param array|null $tags Change tags to apply to the rollback
3065 * Callers are responsible for permission checks
3066 * (with ChangeTags::canAddTagsAccompanyingChange)
3067 *
3068 * @return array
3069 */
3070 public function commitRollback( $fromP, $summary, $bot,
3071 &$resultDetails, User $guser, $tags = null
3072 ) {
3073 global $wgUseRCPatrol, $wgContLang;
3074
3075 $dbw = wfGetDB( DB_MASTER );
3076
3077 if ( wfReadOnly() ) {
3078 return [ [ 'readonlytext' ] ];
3079 }
3080
3081 // Get the last editor
3082 $current = $this->getRevision();
3083 if ( is_null( $current ) ) {
3084 // Something wrong... no page?
3085 return [ [ 'notanarticle' ] ];
3086 }
3087
3088 $from = str_replace( '_', ' ', $fromP );
3089 // User name given should match up with the top revision.
3090 // If the user was deleted then $from should be empty.
3091 if ( $from != $current->getUserText() ) {
3092 $resultDetails = [ 'current' => $current ];
3093 return [ [ 'alreadyrolled',
3094 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3095 htmlspecialchars( $fromP ),
3096 htmlspecialchars( $current->getUserText() )
3097 ] ];
3098 }
3099
3100 // Get the last edit not by this person...
3101 // Note: these may not be public values
3102 $user = intval( $current->getUser( Revision::RAW ) );
3103 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3104 $s = $dbw->selectRow( 'revision',
3105 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3106 [ 'rev_page' => $current->getPage(),
3107 "rev_user != {$user} OR rev_user_text != {$user_text}"
3108 ], __METHOD__,
3109 [ 'USE INDEX' => 'page_timestamp',
3110 'ORDER BY' => 'rev_timestamp DESC' ]
3111 );
3112 if ( $s === false ) {
3113 // No one else ever edited this page
3114 return [ [ 'cantrollback' ] ];
3115 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3116 || $s->rev_deleted & Revision::DELETED_USER
3117 ) {
3118 // Only admins can see this text
3119 return [ [ 'notvisiblerev' ] ];
3120 }
3121
3122 // Generate the edit summary if necessary
3123 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3124 if ( empty( $summary ) ) {
3125 if ( $from == '' ) { // no public user name
3126 $summary = wfMessage( 'revertpage-nouser' );
3127 } else {
3128 $summary = wfMessage( 'revertpage' );
3129 }
3130 }
3131
3132 // Allow the custom summary to use the same args as the default message
3133 $args = [
3134 $target->getUserText(), $from, $s->rev_id,
3135 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3136 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3137 ];
3138 if ( $summary instanceof Message ) {
3139 $summary = $summary->params( $args )->inContentLanguage()->text();
3140 } else {
3141 $summary = wfMsgReplaceArgs( $summary, $args );
3142 }
3143
3144 // Trim spaces on user supplied text
3145 $summary = trim( $summary );
3146
3147 // Save
3148 $flags = EDIT_UPDATE | EDIT_INTERNAL;
3149
3150 if ( $guser->isAllowed( 'minoredit' ) ) {
3151 $flags |= EDIT_MINOR;
3152 }
3153
3154 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3155 $flags |= EDIT_FORCE_BOT;
3156 }
3157
3158 $targetContent = $target->getContent();
3159 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3160
3161 // Actually store the edit
3162 $status = $this->doEditContent(
3163 $targetContent,
3164 $summary,
3165 $flags,
3166 $target->getId(),
3167 $guser,
3168 null,
3169 $tags
3170 );
3171
3172 // Set patrolling and bot flag on the edits, which gets rollbacked.
3173 // This is done even on edit failure to have patrolling in that case (T64157).
3174 $set = [];
3175 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3176 // Mark all reverted edits as bot
3177 $set['rc_bot'] = 1;
3178 }
3179
3180 if ( $wgUseRCPatrol ) {
3181 // Mark all reverted edits as patrolled
3182 $set['rc_patrolled'] = 1;
3183 }
3184
3185 if ( count( $set ) ) {
3186 $dbw->update( 'recentchanges', $set,
3187 [ /* WHERE */
3188 'rc_cur_id' => $current->getPage(),
3189 'rc_user_text' => $current->getUserText(),
3190 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3191 ],
3192 __METHOD__
3193 );
3194 }
3195
3196 if ( !$status->isOK() ) {
3197 return $status->getErrorsArray();
3198 }
3199
3200 // raise error, when the edit is an edit without a new version
3201 $statusRev = isset( $status->value['revision'] )
3202 ? $status->value['revision']
3203 : null;
3204 if ( !( $statusRev instanceof Revision ) ) {
3205 $resultDetails = [ 'current' => $current ];
3206 return [ [ 'alreadyrolled',
3207 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3208 htmlspecialchars( $fromP ),
3209 htmlspecialchars( $current->getUserText() )
3210 ] ];
3211 }
3212
3213 if ( $changingContentModel ) {
3214 // If the content model changed during the rollback,
3215 // make sure it gets logged to Special:Log/contentmodel
3216 $log = new ManualLogEntry( 'contentmodel', 'change' );
3217 $log->setPerformer( $guser );
3218 $log->setTarget( $this->mTitle );
3219 $log->setComment( $summary );
3220 $log->setParameters( [
3221 '4::oldmodel' => $current->getContentModel(),
3222 '5::newmodel' => $targetContent->getModel(),
3223 ] );
3224
3225 $logId = $log->insert( $dbw );
3226 $log->publish( $logId );
3227 }
3228
3229 $revId = $statusRev->getId();
3230
3231 Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3232
3233 $resultDetails = [
3234 'summary' => $summary,
3235 'current' => $current,
3236 'target' => $target,
3237 'newid' => $revId
3238 ];
3239
3240 return [];
3241 }
3242
3243 /**
3244 * The onArticle*() functions are supposed to be a kind of hooks
3245 * which should be called whenever any of the specified actions
3246 * are done.
3247 *
3248 * This is a good place to put code to clear caches, for instance.
3249 *
3250 * This is called on page move and undelete, as well as edit
3251 *
3252 * @param Title $title
3253 */
3254 public static function onArticleCreate( Title $title ) {
3255 // Update existence markers on article/talk tabs...
3256 $other = $title->getOtherPage();
3257
3258 $other->purgeSquid();
3259
3260 $title->touchLinks();
3261 $title->purgeSquid();
3262 $title->deleteTitleProtection();
3263
3264 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3265
3266 // Invalidate caches of articles which include this page
3267 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3268
3269 if ( $title->getNamespace() == NS_CATEGORY ) {
3270 // Load the Category object, which will schedule a job to create
3271 // the category table row if necessary. Checking a replica DB is ok
3272 // here, in the worst case it'll run an unnecessary recount job on
3273 // a category that probably doesn't have many members.
3274 Category::newFromTitle( $title )->getID();
3275 }
3276 }
3277
3278 /**
3279 * Clears caches when article is deleted
3280 *
3281 * @param Title $title
3282 */
3283 public static function onArticleDelete( Title $title ) {
3284 // Update existence markers on article/talk tabs...
3285 $other = $title->getOtherPage();
3286
3287 $other->purgeSquid();
3288
3289 $title->touchLinks();
3290 $title->purgeSquid();
3291
3292 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3293
3294 // File cache
3295 HTMLFileCache::clearFileCache( $title );
3296 InfoAction::invalidateCache( $title );
3297
3298 // Messages
3299 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3300 MessageCache::singleton()->updateMessageOverride( $title, null );
3301 }
3302
3303 // Images
3304 if ( $title->getNamespace() == NS_FILE ) {
3305 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3306 }
3307
3308 // User talk pages
3309 if ( $title->getNamespace() == NS_USER_TALK ) {
3310 $user = User::newFromName( $title->getText(), false );
3311 if ( $user ) {
3312 $user->setNewtalk( false );
3313 }
3314 }
3315
3316 // Image redirects
3317 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3318 }
3319
3320 /**
3321 * Purge caches on page update etc
3322 *
3323 * @param Title $title
3324 * @param Revision|null $revision Revision that was just saved, may be null
3325 */
3326 public static function onArticleEdit( Title $title, Revision $revision = null ) {
3327 // Invalidate caches of articles which include this page
3328 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3329
3330 // Invalidate the caches of all pages which redirect here
3331 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3332
3333 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3334
3335 // Purge CDN for this page only
3336 $title->purgeSquid();
3337 // Clear file cache for this page only
3338 HTMLFileCache::clearFileCache( $title );
3339
3340 $revid = $revision ? $revision->getId() : null;
3341 DeferredUpdates::addCallableUpdate( function () use ( $title, $revid ) {
3342 InfoAction::invalidateCache( $title, $revid );
3343 } );
3344 }
3345
3346 /**#@-*/
3347
3348 /**
3349 * Returns a list of categories this page is a member of.
3350 * Results will include hidden categories
3351 *
3352 * @return TitleArray
3353 */
3354 public function getCategories() {
3355 $id = $this->getId();
3356 if ( $id == 0 ) {
3357 return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3358 }
3359
3360 $dbr = wfGetDB( DB_REPLICA );
3361 $res = $dbr->select( 'categorylinks',
3362 [ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3363 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3364 // as not being aliases, and NS_CATEGORY is numeric
3365 [ 'cl_from' => $id ],
3366 __METHOD__ );
3367
3368 return TitleArray::newFromResult( $res );
3369 }
3370
3371 /**
3372 * Returns a list of hidden categories this page is a member of.
3373 * Uses the page_props and categorylinks tables.
3374 *
3375 * @return array Array of Title objects
3376 */
3377 public function getHiddenCategories() {
3378 $result = [];
3379 $id = $this->getId();
3380
3381 if ( $id == 0 ) {
3382 return [];
3383 }
3384
3385 $dbr = wfGetDB( DB_REPLICA );
3386 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3387 [ 'cl_to' ],
3388 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3389 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3390 __METHOD__ );
3391
3392 if ( $res !== false ) {
3393 foreach ( $res as $row ) {
3394 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3395 }
3396 }
3397
3398 return $result;
3399 }
3400
3401 /**
3402 * Auto-generates a deletion reason
3403 *
3404 * @param bool &$hasHistory Whether the page has a history
3405 * @return string|bool String containing deletion reason or empty string, or boolean false
3406 * if no revision occurred
3407 */
3408 public function getAutoDeleteReason( &$hasHistory ) {
3409 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3410 }
3411
3412 /**
3413 * Update all the appropriate counts in the category table, given that
3414 * we've added the categories $added and deleted the categories $deleted.
3415 *
3416 * This should only be called from deferred updates or jobs to avoid contention.
3417 *
3418 * @param array $added The names of categories that were added
3419 * @param array $deleted The names of categories that were deleted
3420 * @param int $id Page ID (this should be the original deleted page ID)
3421 */
3422 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3423 $id = $id ?: $this->getId();
3424 $ns = $this->getTitle()->getNamespace();
3425
3426 $addFields = [ 'cat_pages = cat_pages + 1' ];
3427 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3428 if ( $ns == NS_CATEGORY ) {
3429 $addFields[] = 'cat_subcats = cat_subcats + 1';
3430 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3431 } elseif ( $ns == NS_FILE ) {
3432 $addFields[] = 'cat_files = cat_files + 1';
3433 $removeFields[] = 'cat_files = cat_files - 1';
3434 }
3435
3436 $dbw = wfGetDB( DB_MASTER );
3437
3438 if ( count( $added ) ) {
3439 $existingAdded = $dbw->selectFieldValues(
3440 'category',
3441 'cat_title',
3442 [ 'cat_title' => $added ],
3443 __METHOD__
3444 );
3445
3446 // For category rows that already exist, do a plain
3447 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3448 // to avoid creating gaps in the cat_id sequence.
3449 if ( count( $existingAdded ) ) {
3450 $dbw->update(
3451 'category',
3452 $addFields,
3453 [ 'cat_title' => $existingAdded ],
3454 __METHOD__
3455 );
3456 }
3457
3458 $missingAdded = array_diff( $added, $existingAdded );
3459 if ( count( $missingAdded ) ) {
3460 $insertRows = [];
3461 foreach ( $missingAdded as $cat ) {
3462 $insertRows[] = [
3463 'cat_title' => $cat,
3464 'cat_pages' => 1,
3465 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3466 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3467 ];
3468 }
3469 $dbw->upsert(
3470 'category',
3471 $insertRows,
3472 [ 'cat_title' ],
3473 $addFields,
3474 __METHOD__
3475 );
3476 }
3477 }
3478
3479 if ( count( $deleted ) ) {
3480 $dbw->update(
3481 'category',
3482 $removeFields,
3483 [ 'cat_title' => $deleted ],
3484 __METHOD__
3485 );
3486 }
3487
3488 foreach ( $added as $catName ) {
3489 $cat = Category::newFromName( $catName );
3490 Hooks::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3491 }
3492
3493 foreach ( $deleted as $catName ) {
3494 $cat = Category::newFromName( $catName );
3495 Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3496 }
3497
3498 // Refresh counts on categories that should be empty now, to
3499 // trigger possible deletion. Check master for the most
3500 // up-to-date cat_pages.
3501 if ( count( $deleted ) ) {
3502 $rows = $dbw->select(
3503 'category',
3504 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3505 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3506 __METHOD__
3507 );
3508 foreach ( $rows as $row ) {
3509 $cat = Category::newFromRow( $row );
3510 // T166757: do the update after this DB commit
3511 DeferredUpdates::addCallableUpdate( function () use ( $cat ) {
3512 $cat->refreshCounts();
3513 } );
3514 }
3515 }
3516 }
3517
3518 /**
3519 * Opportunistically enqueue link update jobs given fresh parser output if useful
3520 *
3521 * @param ParserOutput $parserOutput Current version page output
3522 * @since 1.25
3523 */
3524 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3525 if ( wfReadOnly() ) {
3526 return;
3527 }
3528
3529 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3530 [ $this, $this->mTitle, $parserOutput ]
3531 ) ) {
3532 return;
3533 }
3534
3535 $config = RequestContext::getMain()->getConfig();
3536
3537 $params = [
3538 'isOpportunistic' => true,
3539 'rootJobTimestamp' => $parserOutput->getCacheTime()
3540 ];
3541
3542 if ( $this->mTitle->areRestrictionsCascading() ) {
3543 // If the page is cascade protecting, the links should really be up-to-date
3544 JobQueueGroup::singleton()->lazyPush(
3545 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3546 );
3547 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3548 // Assume the output contains "dynamic" time/random based magic words.
3549 // Only update pages that expired due to dynamic content and NOT due to edits
3550 // to referenced templates/files. When the cache expires due to dynamic content,
3551 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3552 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3553 // template/file edit already triggered recursive RefreshLinksJob jobs.
3554 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3555 // If a page is uncacheable, do not keep spamming a job for it.
3556 // Although it would be de-duplicated, it would still waste I/O.
3557 $cache = ObjectCache::getLocalClusterInstance();
3558 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3559 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3560 if ( $cache->add( $key, time(), $ttl ) ) {
3561 JobQueueGroup::singleton()->lazyPush(
3562 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3563 );
3564 }
3565 }
3566 }
3567 }
3568
3569 /**
3570 * Returns a list of updates to be performed when this page is deleted. The
3571 * updates should remove any information about this page from secondary data
3572 * stores such as links tables.
3573 *
3574 * @param Content|null $content Optional Content object for determining the
3575 * necessary updates.
3576 * @return DeferrableUpdate[]
3577 */
3578 public function getDeletionUpdates( Content $content = null ) {
3579 if ( !$content ) {
3580 // load content object, which may be used to determine the necessary updates.
3581 // XXX: the content may not be needed to determine the updates.
3582 try {
3583 $content = $this->getContent( Revision::RAW );
3584 } catch ( Exception $ex ) {
3585 // If we can't load the content, something is wrong. Perhaps that's why
3586 // the user is trying to delete the page, so let's not fail in that case.
3587 // Note that doDeleteArticleReal() will already have logged an issue with
3588 // loading the content.
3589 }
3590 }
3591
3592 if ( !$content ) {
3593 $updates = [];
3594 } else {
3595 $updates = $content->getDeletionUpdates( $this );
3596 }
3597
3598 Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3599 return $updates;
3600 }
3601
3602 /**
3603 * Whether this content displayed on this page
3604 * comes from the local database
3605 *
3606 * @since 1.28
3607 * @return bool
3608 */
3609 public function isLocal() {
3610 return true;
3611 }
3612
3613 /**
3614 * The display name for the site this content
3615 * come from. If a subclass overrides isLocal(),
3616 * this could return something other than the
3617 * current site name
3618 *
3619 * @since 1.28
3620 * @return string
3621 */
3622 public function getWikiDisplayName() {
3623 global $wgSitename;
3624 return $wgSitename;
3625 }
3626
3627 /**
3628 * Get the source URL for the content on this page,
3629 * typically the canonical URL, but may be a remote
3630 * link if the content comes from another site
3631 *
3632 * @since 1.28
3633 * @return string
3634 */
3635 public function getSourceURL() {
3636 return $this->getTitle()->getCanonicalURL();
3637 }
3638
3639 /**
3640 * @param WANObjectCache $cache
3641 * @return string[]
3642 * @since 1.28
3643 */
3644 public function getMutableCacheKeys( WANObjectCache $cache ) {
3645 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3646
3647 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );
3648 }
3649 }