Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / page / WikiPage.php
blobf760cd1601c65776f7283c31876e4bc625b5e721
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
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.
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.
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
20 * @file
23 use \MediaWiki\Logger\LoggerFactory;
24 use \MediaWiki\MediaWikiServices;
26 /**
27 * Class representing a MediaWiki article and history.
29 * Some fields are public only for backwards-compatibility. Use accessors.
30 * In the past, this class was part of Article.php and everything was public.
32 class WikiPage implements Page, IDBAccessObject {
33 // Constants for $mDataLoadedFrom and related
35 /**
36 * @var Title
38 public $mTitle = null;
40 /**@{{
41 * @protected
43 public $mDataLoaded = false; // !< Boolean
44 public $mIsRedirect = false; // !< Boolean
45 public $mLatest = false; // !< Integer (false means "not loaded")
46 /**@}}*/
48 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
49 public $mPreparedEdit = false;
51 /**
52 * @var int
54 protected $mId = null;
56 /**
57 * @var int One of the READ_* constants
59 protected $mDataLoadedFrom = self::READ_NONE;
61 /**
62 * @var Title
64 protected $mRedirectTarget = null;
66 /**
67 * @var Revision
69 protected $mLastRevision = null;
71 /**
72 * @var string Timestamp of the current revision or empty string if not loaded
74 protected $mTimestamp = '';
76 /**
77 * @var string
79 protected $mTouched = '19700101000000';
81 /**
82 * @var string
84 protected $mLinksUpdated = '19700101000000';
86 const PURGE_CDN_CACHE = 1; // purge CDN cache for page variant URLs
87 const PURGE_CLUSTER_PCACHE = 2; // purge parser cache in the local datacenter
88 const PURGE_GLOBAL_PCACHE = 4; // set page_touched to clear parser cache in all datacenters
89 const PURGE_ALL = 7;
91 /**
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title $title ) {
96 $this->mTitle = $title;
99 /**
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
103 public function __clone() {
104 $this->mTitle = clone $this->mTitle;
108 * Create a WikiPage object of the appropriate class for the given title.
110 * @param Title $title
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
115 public static function factory( Title $title ) {
116 $ns = $title->getNamespace();
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." );
124 $page = null;
125 if ( !Hooks::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
126 return $page;
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 );
140 return $page;
144 * Constructor from a page id
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
151 * @return WikiPage|null
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 // page id's are never 0 or negative, see bug 61166
155 if ( $id < 1 ) {
156 return null;
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;
166 return self::newFromRow( $row, $from );
170 * Constructor from a database row
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
180 public static function newFromRow( $row, $from = 'fromdb' ) {
181 $page = self::factory( Title::newFromRow( $row ) );
182 $page->loadFromRow( $row, $from );
183 return $page;
187 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
189 * @param object|string|int $type
190 * @return mixed
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;
207 * @todo Move this UI stuff somewhere else
209 * @see ContentHandler::getActionOverrides
211 public function getActionOverrides() {
212 return $this->getContentHandler()->getActionOverrides();
216 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
218 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
220 * @return ContentHandler
222 * @since 1.21
224 public function getContentHandler() {
225 return ContentHandler::getForModelID( $this->getContentModel() );
229 * Get the title object of the article
230 * @return Title Title object of this page
232 public function getTitle() {
233 return $this->mTitle;
237 * Clear the object
238 * @return void
240 public function clear() {
241 $this->mDataLoaded = false;
242 $this->mDataLoadedFrom = self::READ_NONE;
244 $this->clearCacheFields();
248 * Clear the object cache fields
249 * @return void
251 protected function clearCacheFields() {
252 $this->mId = null;
253 $this->mRedirectTarget = null; // Title object if set
254 $this->mLastRevision = null; // Latest revision
255 $this->mTouched = '19700101000000';
256 $this->mLinksUpdated = '19700101000000';
257 $this->mTimestamp = '';
258 $this->mIsRedirect = false;
259 $this->mLatest = false;
260 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
261 // the requested rev ID and content against the cached one for equality. For most
262 // content types, the output should not change during the lifetime of this cache.
263 // Clearing it can cause extra parses on edit for no reason.
267 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
268 * @return void
269 * @since 1.23
271 public function clearPreparedEdit() {
272 $this->mPreparedEdit = false;
276 * Return the list of revision fields that should be selected to create
277 * a new page.
279 * @return array
281 public static function selectFields() {
282 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
284 $fields = [
285 'page_id',
286 'page_namespace',
287 'page_title',
288 'page_restrictions',
289 'page_is_redirect',
290 'page_is_new',
291 'page_random',
292 'page_touched',
293 'page_links_updated',
294 'page_latest',
295 'page_len',
298 if ( $wgContentHandlerUseDB ) {
299 $fields[] = 'page_content_model';
302 if ( $wgPageLanguageUseDB ) {
303 $fields[] = 'page_lang';
306 return $fields;
310 * Fetch a page record with the given conditions
311 * @param IDatabase $dbr
312 * @param array $conditions
313 * @param array $options
314 * @return object|bool Database result resource, or false on failure
316 protected function pageData( $dbr, $conditions, $options = [] ) {
317 $fields = self::selectFields();
319 // Avoid PHP 7.1 warning of passing $this by reference
320 $wikiPage = $this;
322 Hooks::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
324 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
326 Hooks::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
328 return $row;
332 * Fetch a page record matching the Title object's namespace and title
333 * using a sanitized title string
335 * @param IDatabase $dbr
336 * @param Title $title
337 * @param array $options
338 * @return object|bool Database result resource, or false on failure
340 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
341 return $this->pageData( $dbr, [
342 'page_namespace' => $title->getNamespace(),
343 'page_title' => $title->getDBkey() ], $options );
347 * Fetch a page record matching the requested ID
349 * @param IDatabase $dbr
350 * @param int $id
351 * @param array $options
352 * @return object|bool Database result resource, or false on failure
354 public function pageDataFromId( $dbr, $id, $options = [] ) {
355 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
359 * Load the object from a given source by title
361 * @param object|string|int $from One of the following:
362 * - A DB query result object.
363 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
364 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
365 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
366 * using SELECT FOR UPDATE.
368 * @return void
370 public function loadPageData( $from = 'fromdb' ) {
371 $from = self::convertSelectType( $from );
372 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
373 // We already have the data from the correct location, no need to load it twice.
374 return;
377 if ( is_int( $from ) ) {
378 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
379 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
381 if ( !$data
382 && $index == DB_REPLICA
383 && wfGetLB()->getServerCount() > 1
384 && wfGetLB()->hasOrMadeRecentMasterChanges()
386 $from = self::READ_LATEST;
387 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
388 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
390 } else {
391 // No idea from where the caller got this data, assume replica DB.
392 $data = $from;
393 $from = self::READ_NORMAL;
396 $this->loadFromRow( $data, $from );
400 * Load the object from a database row
402 * @since 1.20
403 * @param object|bool $data DB row containing fields returned by selectFields() or false
404 * @param string|int $from One of the following:
405 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
406 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
407 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
408 * the master DB using SELECT FOR UPDATE
410 public function loadFromRow( $data, $from ) {
411 $lc = LinkCache::singleton();
412 $lc->clearLink( $this->mTitle );
414 if ( $data ) {
415 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
417 $this->mTitle->loadFromRow( $data );
419 // Old-fashioned restrictions
420 $this->mTitle->loadRestrictions( $data->page_restrictions );
422 $this->mId = intval( $data->page_id );
423 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
424 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
425 $this->mIsRedirect = intval( $data->page_is_redirect );
426 $this->mLatest = intval( $data->page_latest );
427 // Bug 37225: $latest may no longer match the cached latest Revision object.
428 // Double-check the ID of any cached latest Revision object for consistency.
429 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
430 $this->mLastRevision = null;
431 $this->mTimestamp = '';
433 } else {
434 $lc->addBadLinkObj( $this->mTitle );
436 $this->mTitle->loadFromRow( false );
438 $this->clearCacheFields();
440 $this->mId = 0;
443 $this->mDataLoaded = true;
444 $this->mDataLoadedFrom = self::convertSelectType( $from );
448 * @return int Page ID
450 public function getId() {
451 if ( !$this->mDataLoaded ) {
452 $this->loadPageData();
454 return $this->mId;
458 * @return bool Whether or not the page exists in the database
460 public function exists() {
461 if ( !$this->mDataLoaded ) {
462 $this->loadPageData();
464 return $this->mId > 0;
468 * Check if this page is something we're going to be showing
469 * some sort of sensible content for. If we return false, page
470 * views (plain action=view) will return an HTTP 404 response,
471 * so spiders and robots can know they're following a bad link.
473 * @return bool
475 public function hasViewableContent() {
476 return $this->mTitle->isKnown();
480 * Tests if the article content represents a redirect
482 * @return bool
484 public function isRedirect() {
485 if ( !$this->mDataLoaded ) {
486 $this->loadPageData();
489 return (bool)$this->mIsRedirect;
493 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
495 * Will use the revisions actual content model if the page exists,
496 * and the page's default if the page doesn't exist yet.
498 * @return string
500 * @since 1.21
502 public function getContentModel() {
503 if ( $this->exists() ) {
504 $cache = ObjectCache::getMainWANInstance();
506 return $cache->getWithSetCallback(
507 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
508 $cache::TTL_MONTH,
509 function () {
510 $rev = $this->getRevision();
511 if ( $rev ) {
512 // Look at the revision's actual content model
513 return $rev->getContentModel();
514 } else {
515 $title = $this->mTitle->getPrefixedDBkey();
516 wfWarn( "Page $title exists but has no (visible) revisions!" );
517 return $this->mTitle->getContentModel();
523 // use the default model for this page
524 return $this->mTitle->getContentModel();
528 * Loads page_touched and returns a value indicating if it should be used
529 * @return bool True if this page exists and is not a redirect
531 public function checkTouched() {
532 if ( !$this->mDataLoaded ) {
533 $this->loadPageData();
535 return ( $this->mId && !$this->mIsRedirect );
539 * Get the page_touched field
540 * @return string Containing GMT timestamp
542 public function getTouched() {
543 if ( !$this->mDataLoaded ) {
544 $this->loadPageData();
546 return $this->mTouched;
550 * Get the page_links_updated field
551 * @return string|null Containing GMT timestamp
553 public function getLinksTimestamp() {
554 if ( !$this->mDataLoaded ) {
555 $this->loadPageData();
557 return $this->mLinksUpdated;
561 * Get the page_latest field
562 * @return int The rev_id of current revision
564 public function getLatest() {
565 if ( !$this->mDataLoaded ) {
566 $this->loadPageData();
568 return (int)$this->mLatest;
572 * Get the Revision object of the oldest revision
573 * @return Revision|null
575 public function getOldestRevision() {
577 // Try using the replica DB first, then try the master
578 $continue = 2;
579 $db = wfGetDB( DB_REPLICA );
580 $revSelectFields = Revision::selectFields();
582 $row = null;
583 while ( $continue ) {
584 $row = $db->selectRow(
585 [ 'page', 'revision' ],
586 $revSelectFields,
588 'page_namespace' => $this->mTitle->getNamespace(),
589 'page_title' => $this->mTitle->getDBkey(),
590 'rev_page = page_id'
592 __METHOD__,
594 'ORDER BY' => 'rev_timestamp ASC'
598 if ( $row ) {
599 $continue = 0;
600 } else {
601 $db = wfGetDB( DB_MASTER );
602 $continue--;
606 return $row ? Revision::newFromRow( $row ) : null;
610 * Loads everything except the text
611 * This isn't necessary for all uses, so it's only done if needed.
613 protected function loadLastEdit() {
614 if ( $this->mLastRevision !== null ) {
615 return; // already loaded
618 $latest = $this->getLatest();
619 if ( !$latest ) {
620 return; // page doesn't exist or is missing page_latest info
623 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
624 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
625 // includes the latest changes committed. This is true even within REPEATABLE-READ
626 // transactions, where S1 normally only sees changes committed before the first S1
627 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
628 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
629 // happened after the first S1 SELECT.
630 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
631 $flags = Revision::READ_LOCKING;
632 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
633 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
634 // Bug T93976: if page_latest was loaded from the master, fetch the
635 // revision from there as well, as it may not exist yet on a replica DB.
636 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
637 $flags = Revision::READ_LATEST;
638 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
639 } else {
640 $dbr = wfGetDB( DB_REPLICA );
641 $revision = Revision::newKnownCurrent( $dbr, $this->getId(), $latest );
644 if ( $revision ) { // sanity
645 $this->setLastEdit( $revision );
650 * Set the latest revision
651 * @param Revision $revision
653 protected function setLastEdit( Revision $revision ) {
654 $this->mLastRevision = $revision;
655 $this->mTimestamp = $revision->getTimestamp();
659 * Get the latest revision
660 * @return Revision|null
662 public function getRevision() {
663 $this->loadLastEdit();
664 if ( $this->mLastRevision ) {
665 return $this->mLastRevision;
667 return null;
671 * Get the content of the current revision. No side-effects...
673 * @param int $audience One of:
674 * Revision::FOR_PUBLIC to be displayed to all users
675 * Revision::FOR_THIS_USER to be displayed to $wgUser
676 * Revision::RAW get the text regardless of permissions
677 * @param User $user User object to check for, only if FOR_THIS_USER is passed
678 * to the $audience parameter
679 * @return Content|null The content of the current revision
681 * @since 1.21
683 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
684 $this->loadLastEdit();
685 if ( $this->mLastRevision ) {
686 return $this->mLastRevision->getContent( $audience, $user );
688 return null;
692 * @return string MW timestamp of last article revision
694 public function getTimestamp() {
695 // Check if the field has been filled by WikiPage::setTimestamp()
696 if ( !$this->mTimestamp ) {
697 $this->loadLastEdit();
700 return wfTimestamp( TS_MW, $this->mTimestamp );
704 * Set the page timestamp (use only to avoid DB queries)
705 * @param string $ts MW timestamp of last article revision
706 * @return void
708 public function setTimestamp( $ts ) {
709 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
713 * @param int $audience One of:
714 * Revision::FOR_PUBLIC to be displayed to all users
715 * Revision::FOR_THIS_USER to be displayed to the given user
716 * Revision::RAW get the text regardless of permissions
717 * @param User $user User object to check for, only if FOR_THIS_USER is passed
718 * to the $audience parameter
719 * @return int User ID for the user that made the last article revision
721 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
722 $this->loadLastEdit();
723 if ( $this->mLastRevision ) {
724 return $this->mLastRevision->getUser( $audience, $user );
725 } else {
726 return -1;
731 * Get the User object of the user who created the page
732 * @param int $audience One of:
733 * Revision::FOR_PUBLIC to be displayed to all users
734 * Revision::FOR_THIS_USER to be displayed to the given user
735 * Revision::RAW get the text regardless of permissions
736 * @param User $user User object to check for, only if FOR_THIS_USER is passed
737 * to the $audience parameter
738 * @return User|null
740 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
741 $revision = $this->getOldestRevision();
742 if ( $revision ) {
743 $userName = $revision->getUserText( $audience, $user );
744 return User::newFromName( $userName, false );
745 } else {
746 return null;
751 * @param int $audience One of:
752 * Revision::FOR_PUBLIC to be displayed to all users
753 * Revision::FOR_THIS_USER to be displayed to the given user
754 * Revision::RAW get the text regardless of permissions
755 * @param User $user User object to check for, only if FOR_THIS_USER is passed
756 * to the $audience parameter
757 * @return string Username of the user that made the last article revision
759 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
760 $this->loadLastEdit();
761 if ( $this->mLastRevision ) {
762 return $this->mLastRevision->getUserText( $audience, $user );
763 } else {
764 return '';
769 * @param int $audience One of:
770 * Revision::FOR_PUBLIC to be displayed to all users
771 * Revision::FOR_THIS_USER to be displayed to the given user
772 * Revision::RAW get the text regardless of permissions
773 * @param User $user User object to check for, only if FOR_THIS_USER is passed
774 * to the $audience parameter
775 * @return string Comment stored for the last article revision
777 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
778 $this->loadLastEdit();
779 if ( $this->mLastRevision ) {
780 return $this->mLastRevision->getComment( $audience, $user );
781 } else {
782 return '';
787 * Returns true if last revision was marked as "minor edit"
789 * @return bool Minor edit indicator for the last article revision.
791 public function getMinorEdit() {
792 $this->loadLastEdit();
793 if ( $this->mLastRevision ) {
794 return $this->mLastRevision->isMinor();
795 } else {
796 return false;
801 * Determine whether a page would be suitable for being counted as an
802 * article in the site_stats table based on the title & its content
804 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
805 * if false, the current database state will be used
806 * @return bool
808 public function isCountable( $editInfo = false ) {
809 global $wgArticleCountMethod;
811 if ( !$this->mTitle->isContentPage() ) {
812 return false;
815 if ( $editInfo ) {
816 $content = $editInfo->pstContent;
817 } else {
818 $content = $this->getContent();
821 if ( !$content || $content->isRedirect() ) {
822 return false;
825 $hasLinks = null;
827 if ( $wgArticleCountMethod === 'link' ) {
828 // nasty special case to avoid re-parsing to detect links
830 if ( $editInfo ) {
831 // ParserOutput::getLinks() is a 2D array of page links, so
832 // to be really correct we would need to recurse in the array
833 // but the main array should only have items in it if there are
834 // links.
835 $hasLinks = (bool)count( $editInfo->output->getLinks() );
836 } else {
837 $hasLinks = (bool)wfGetDB( DB_REPLICA )->selectField( 'pagelinks', 1,
838 [ 'pl_from' => $this->getId() ], __METHOD__ );
842 return $content->isCountable( $hasLinks );
846 * If this page is a redirect, get its target
848 * The target will be fetched from the redirect table if possible.
849 * If this page doesn't have an entry there, call insertRedirect()
850 * @return Title|null Title object, or null if this page is not a redirect
852 public function getRedirectTarget() {
853 if ( !$this->mTitle->isRedirect() ) {
854 return null;
857 if ( $this->mRedirectTarget !== null ) {
858 return $this->mRedirectTarget;
861 // Query the redirect table
862 $dbr = wfGetDB( DB_REPLICA );
863 $row = $dbr->selectRow( 'redirect',
864 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
865 [ 'rd_from' => $this->getId() ],
866 __METHOD__
869 // rd_fragment and rd_interwiki were added later, populate them if empty
870 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
871 $this->mRedirectTarget = Title::makeTitle(
872 $row->rd_namespace, $row->rd_title,
873 $row->rd_fragment, $row->rd_interwiki
875 return $this->mRedirectTarget;
878 // This page doesn't have an entry in the redirect table
879 $this->mRedirectTarget = $this->insertRedirect();
880 return $this->mRedirectTarget;
884 * Insert an entry for this page into the redirect table if the content is a redirect
886 * The database update will be deferred via DeferredUpdates
888 * Don't call this function directly unless you know what you're doing.
889 * @return Title|null Title object or null if not a redirect
891 public function insertRedirect() {
892 $content = $this->getContent();
893 $retval = $content ? $content->getUltimateRedirectTarget() : null;
894 if ( !$retval ) {
895 return null;
898 // Update the DB post-send if the page has not cached since now
899 $that = $this;
900 $latest = $this->getLatest();
901 DeferredUpdates::addCallableUpdate(
902 function () use ( $that, $retval, $latest ) {
903 $that->insertRedirectEntry( $retval, $latest );
905 DeferredUpdates::POSTSEND,
906 wfGetDB( DB_MASTER )
909 return $retval;
913 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
914 * @param Title $rt Redirect target
915 * @param int|null $oldLatest Prior page_latest for check and set
917 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
918 $dbw = wfGetDB( DB_MASTER );
919 $dbw->startAtomic( __METHOD__ );
921 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
922 $dbw->upsert(
923 'redirect',
925 'rd_from' => $this->getId(),
926 'rd_namespace' => $rt->getNamespace(),
927 'rd_title' => $rt->getDBkey(),
928 'rd_fragment' => $rt->getFragment(),
929 'rd_interwiki' => $rt->getInterwiki(),
931 [ 'rd_from' ],
933 'rd_namespace' => $rt->getNamespace(),
934 'rd_title' => $rt->getDBkey(),
935 'rd_fragment' => $rt->getFragment(),
936 'rd_interwiki' => $rt->getInterwiki(),
938 __METHOD__
942 $dbw->endAtomic( __METHOD__ );
946 * Get the Title object or URL this page redirects to
948 * @return bool|Title|string False, Title of in-wiki target, or string with URL
950 public function followRedirect() {
951 return $this->getRedirectURL( $this->getRedirectTarget() );
955 * Get the Title object or URL to use for a redirect. We use Title
956 * objects for same-wiki, non-special redirects and URLs for everything
957 * else.
958 * @param Title $rt Redirect target
959 * @return bool|Title|string False, Title object of local target, or string with URL
961 public function getRedirectURL( $rt ) {
962 if ( !$rt ) {
963 return false;
966 if ( $rt->isExternal() ) {
967 if ( $rt->isLocal() ) {
968 // Offsite wikis need an HTTP redirect.
969 // This can be hard to reverse and may produce loops,
970 // so they may be disabled in the site configuration.
971 $source = $this->mTitle->getFullURL( 'redirect=no' );
972 return $rt->getFullURL( [ 'rdfrom' => $source ] );
973 } else {
974 // External pages without "local" bit set are not valid
975 // redirect targets
976 return false;
980 if ( $rt->isSpecialPage() ) {
981 // Gotta handle redirects to special pages differently:
982 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
983 // Some pages are not valid targets.
984 if ( $rt->isValidRedirectTarget() ) {
985 return $rt->getFullURL();
986 } else {
987 return false;
991 return $rt;
995 * Get a list of users who have edited this article, not including the user who made
996 * the most recent revision, which you can get from $article->getUser() if you want it
997 * @return UserArrayFromResult
999 public function getContributors() {
1000 // @todo FIXME: This is expensive; cache this info somewhere.
1002 $dbr = wfGetDB( DB_REPLICA );
1004 if ( $dbr->implicitGroupby() ) {
1005 $realNameField = 'user_real_name';
1006 } else {
1007 $realNameField = 'MIN(user_real_name) AS user_real_name';
1010 $tables = [ 'revision', 'user' ];
1012 $fields = [
1013 'user_id' => 'rev_user',
1014 'user_name' => 'rev_user_text',
1015 $realNameField,
1016 'timestamp' => 'MAX(rev_timestamp)',
1019 $conds = [ 'rev_page' => $this->getId() ];
1021 // The user who made the top revision gets credited as "this page was last edited by
1022 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1023 $user = $this->getUser();
1024 if ( $user ) {
1025 $conds[] = "rev_user != $user";
1026 } else {
1027 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1030 // Username hidden?
1031 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1033 $jconds = [
1034 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1037 $options = [
1038 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1039 'ORDER BY' => 'timestamp DESC',
1042 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1043 return new UserArrayFromResult( $res );
1047 * Should the parser cache be used?
1049 * @param ParserOptions $parserOptions ParserOptions to check
1050 * @param int $oldId
1051 * @return bool
1053 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1054 return $parserOptions->getStubThreshold() == 0
1055 && $this->exists()
1056 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1057 && $this->getContentHandler()->isParserCacheSupported();
1061 * Get a ParserOutput for the given ParserOptions and revision ID.
1063 * The parser cache will be used if possible. Cache misses that result
1064 * in parser runs are debounced with PoolCounter.
1066 * @since 1.19
1067 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1068 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1069 * get the current revision (default value)
1070 * @param bool $forceParse Force reindexing, regardless of cache settings
1071 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1073 public function getParserOutput(
1074 ParserOptions $parserOptions, $oldid = null, $forceParse = false
1076 $useParserCache =
1077 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1078 wfDebug( __METHOD__ .
1079 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1080 if ( $parserOptions->getStubThreshold() ) {
1081 wfIncrStats( 'pcache.miss.stub' );
1084 if ( $useParserCache ) {
1085 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1086 if ( $parserOutput !== false ) {
1087 return $parserOutput;
1091 if ( $oldid === null || $oldid === 0 ) {
1092 $oldid = $this->getLatest();
1095 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1096 $pool->execute();
1098 return $pool->getParserOutput();
1102 * Do standard deferred updates after page view (existing or missing page)
1103 * @param User $user The relevant user
1104 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1106 public function doViewUpdates( User $user, $oldid = 0 ) {
1107 if ( wfReadOnly() ) {
1108 return;
1111 Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1112 // Update newtalk / watchlist notification status
1113 try {
1114 $user->clearNotification( $this->mTitle, $oldid );
1115 } catch ( DBError $e ) {
1116 // Avoid outage if the master is not reachable
1117 MWExceptionHandler::logException( $e );
1122 * Perform the actions of a page purging
1123 * @param integer $flags Bitfield of WikiPage::PURGE_* constants
1124 * @return bool
1126 public function doPurge( $flags = self::PURGE_ALL ) {
1127 // Avoid PHP 7.1 warning of passing $this by reference
1128 $wikiPage = $this;
1130 if ( !Hooks::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1131 return false;
1134 if ( ( $flags & self::PURGE_GLOBAL_PCACHE ) == self::PURGE_GLOBAL_PCACHE ) {
1135 // Set page_touched in the database to invalidate all DC caches
1136 $this->mTitle->invalidateCache();
1137 } elseif ( ( $flags & self::PURGE_CLUSTER_PCACHE ) == self::PURGE_CLUSTER_PCACHE ) {
1138 // Delete the parser options key in the local cluster to invalidate the DC cache
1139 ParserCache::singleton()->deleteOptionsKey( $this );
1140 // Avoid sending HTTP 304s in ViewAction to the client who just issued the purge
1141 $cache = ObjectCache::getLocalClusterInstance();
1142 $cache->set(
1143 $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ),
1144 wfTimestamp( TS_MW ),
1145 $cache::TTL_HOUR
1149 if ( ( $flags & self::PURGE_CDN_CACHE ) == self::PURGE_CDN_CACHE ) {
1150 // Clear any HTML file cache
1151 HTMLFileCache::clearFileCache( $this->getTitle() );
1152 // Send purge after any page_touched above update was committed
1153 DeferredUpdates::addUpdate(
1154 new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1155 DeferredUpdates::PRESEND
1159 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1160 $messageCache = MessageCache::singleton();
1161 $messageCache->updateMessageOverride( $this->mTitle, $this->getContent() );
1164 return true;
1168 * Get the last time a user explicitly purged the page via action=purge
1170 * @return string|bool TS_MW timestamp or false
1171 * @since 1.28
1173 public function getLastPurgeTimestamp() {
1174 $cache = ObjectCache::getLocalClusterInstance();
1176 return $cache->get( $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ) );
1180 * Insert a new empty page record for this article.
1181 * This *must* be followed up by creating a revision
1182 * and running $this->updateRevisionOn( ... );
1183 * or else the record will be left in a funky state.
1184 * Best if all done inside a transaction.
1186 * @param IDatabase $dbw
1187 * @param int|null $pageId Custom page ID that will be used for the insert statement
1189 * @return bool|int The newly created page_id key; false if the row was not
1190 * inserted, e.g. because the title already existed or because the specified
1191 * page ID is already in use.
1193 public function insertOn( $dbw, $pageId = null ) {
1194 $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1195 $dbw->insert(
1196 'page',
1198 'page_id' => $pageIdForInsert,
1199 'page_namespace' => $this->mTitle->getNamespace(),
1200 'page_title' => $this->mTitle->getDBkey(),
1201 'page_restrictions' => '',
1202 'page_is_redirect' => 0, // Will set this shortly...
1203 'page_is_new' => 1,
1204 'page_random' => wfRandom(),
1205 'page_touched' => $dbw->timestamp(),
1206 'page_latest' => 0, // Fill this in shortly...
1207 'page_len' => 0, // Fill this in shortly...
1209 __METHOD__,
1210 'IGNORE'
1213 if ( $dbw->affectedRows() > 0 ) {
1214 $newid = $pageId ?: $dbw->insertId();
1215 $this->mId = $newid;
1216 $this->mTitle->resetArticleID( $newid );
1218 return $newid;
1219 } else {
1220 return false; // nothing changed
1225 * Update the page record to point to a newly saved revision.
1227 * @param IDatabase $dbw
1228 * @param Revision $revision For ID number, and text used to set
1229 * length and redirect status fields
1230 * @param int $lastRevision If given, will not overwrite the page field
1231 * when different from the currently set value.
1232 * Giving 0 indicates the new page flag should be set on.
1233 * @param bool $lastRevIsRedirect If given, will optimize adding and
1234 * removing rows in redirect table.
1235 * @return bool Success; false if the page row was missing or page_latest changed
1237 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1238 $lastRevIsRedirect = null
1240 global $wgContentHandlerUseDB;
1242 // Assertion to try to catch T92046
1243 if ( (int)$revision->getId() === 0 ) {
1244 throw new InvalidArgumentException(
1245 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1249 $content = $revision->getContent();
1250 $len = $content ? $content->getSize() : 0;
1251 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1253 $conditions = [ 'page_id' => $this->getId() ];
1255 if ( !is_null( $lastRevision ) ) {
1256 // An extra check against threads stepping on each other
1257 $conditions['page_latest'] = $lastRevision;
1260 $row = [ /* SET */
1261 'page_latest' => $revision->getId(),
1262 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1263 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1264 'page_is_redirect' => $rt !== null ? 1 : 0,
1265 'page_len' => $len,
1268 if ( $wgContentHandlerUseDB ) {
1269 $row['page_content_model'] = $revision->getContentModel();
1272 $dbw->update( 'page',
1273 $row,
1274 $conditions,
1275 __METHOD__ );
1277 $result = $dbw->affectedRows() > 0;
1278 if ( $result ) {
1279 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1280 $this->setLastEdit( $revision );
1281 $this->mLatest = $revision->getId();
1282 $this->mIsRedirect = (bool)$rt;
1283 // Update the LinkCache.
1284 LinkCache::singleton()->addGoodLinkObj(
1285 $this->getId(),
1286 $this->mTitle,
1287 $len,
1288 $this->mIsRedirect,
1289 $this->mLatest,
1290 $revision->getContentModel()
1294 return $result;
1298 * Add row to the redirect table if this is a redirect, remove otherwise.
1300 * @param IDatabase $dbw
1301 * @param Title $redirectTitle Title object pointing to the redirect target,
1302 * or NULL if this is not a redirect
1303 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1304 * removing rows in redirect table.
1305 * @return bool True on success, false on failure
1306 * @private
1308 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1309 // Always update redirects (target link might have changed)
1310 // Update/Insert if we don't know if the last revision was a redirect or not
1311 // Delete if changing from redirect to non-redirect
1312 $isRedirect = !is_null( $redirectTitle );
1314 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1315 return true;
1318 if ( $isRedirect ) {
1319 $this->insertRedirectEntry( $redirectTitle );
1320 } else {
1321 // This is not a redirect, remove row from redirect table
1322 $where = [ 'rd_from' => $this->getId() ];
1323 $dbw->delete( 'redirect', $where, __METHOD__ );
1326 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1327 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1330 return ( $dbw->affectedRows() != 0 );
1334 * If the given revision is newer than the currently set page_latest,
1335 * update the page record. Otherwise, do nothing.
1337 * @deprecated since 1.24, use updateRevisionOn instead
1339 * @param IDatabase $dbw
1340 * @param Revision $revision
1341 * @return bool
1343 public function updateIfNewerOn( $dbw, $revision ) {
1345 $row = $dbw->selectRow(
1346 [ 'revision', 'page' ],
1347 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1349 'page_id' => $this->getId(),
1350 'page_latest=rev_id' ],
1351 __METHOD__ );
1353 if ( $row ) {
1354 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1355 return false;
1357 $prev = $row->rev_id;
1358 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1359 } else {
1360 // No or missing previous revision; mark the page as new
1361 $prev = 0;
1362 $lastRevIsRedirect = null;
1365 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1367 return $ret;
1371 * Get the content that needs to be saved in order to undo all revisions
1372 * between $undo and $undoafter. Revisions must belong to the same page,
1373 * must exist and must not be deleted
1374 * @param Revision $undo
1375 * @param Revision $undoafter Must be an earlier revision than $undo
1376 * @return Content|bool Content on success, false on failure
1377 * @since 1.21
1378 * Before we had the Content object, this was done in getUndoText
1380 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1381 $handler = $undo->getContentHandler();
1382 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1386 * Returns true if this page's content model supports sections.
1388 * @return bool
1390 * @todo The skin should check this and not offer section functionality if
1391 * sections are not supported.
1392 * @todo The EditPage should check this and not offer section functionality
1393 * if sections are not supported.
1395 public function supportsSections() {
1396 return $this->getContentHandler()->supportsSections();
1400 * @param string|int|null|bool $sectionId Section identifier as a number or string
1401 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1402 * or 'new' for a new section.
1403 * @param Content $sectionContent New content of the section.
1404 * @param string $sectionTitle New section's subject, only if $section is "new".
1405 * @param string $edittime Revision timestamp or null to use the current revision.
1407 * @throws MWException
1408 * @return Content|null New complete article content, or null if error.
1410 * @since 1.21
1411 * @deprecated since 1.24, use replaceSectionAtRev instead
1413 public function replaceSectionContent(
1414 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1417 $baseRevId = null;
1418 if ( $edittime && $sectionId !== 'new' ) {
1419 $dbr = wfGetDB( DB_REPLICA );
1420 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1421 // Try the master if this thread may have just added it.
1422 // This could be abstracted into a Revision method, but we don't want
1423 // to encourage loading of revisions by timestamp.
1424 if ( !$rev
1425 && wfGetLB()->getServerCount() > 1
1426 && wfGetLB()->hasOrMadeRecentMasterChanges()
1428 $dbw = wfGetDB( DB_MASTER );
1429 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1431 if ( $rev ) {
1432 $baseRevId = $rev->getId();
1436 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1440 * @param string|int|null|bool $sectionId Section identifier as a number or string
1441 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1442 * or 'new' for a new section.
1443 * @param Content $sectionContent New content of the section.
1444 * @param string $sectionTitle New section's subject, only if $section is "new".
1445 * @param int|null $baseRevId
1447 * @throws MWException
1448 * @return Content|null New complete article content, or null if error.
1450 * @since 1.24
1452 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1453 $sectionTitle = '', $baseRevId = null
1456 if ( strval( $sectionId ) === '' ) {
1457 // Whole-page edit; let the whole text through
1458 $newContent = $sectionContent;
1459 } else {
1460 if ( !$this->supportsSections() ) {
1461 throw new MWException( "sections not supported for content model " .
1462 $this->getContentHandler()->getModelID() );
1465 // Bug 30711: always use current version when adding a new section
1466 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1467 $oldContent = $this->getContent();
1468 } else {
1469 $rev = Revision::newFromId( $baseRevId );
1470 if ( !$rev ) {
1471 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1472 $this->getId() . "; section: $sectionId)\n" );
1473 return null;
1476 $oldContent = $rev->getContent();
1479 if ( !$oldContent ) {
1480 wfDebug( __METHOD__ . ": no page text\n" );
1481 return null;
1484 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1487 return $newContent;
1491 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1492 * @param int $flags
1493 * @return int Updated $flags
1495 public function checkFlags( $flags ) {
1496 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1497 if ( $this->exists() ) {
1498 $flags |= EDIT_UPDATE;
1499 } else {
1500 $flags |= EDIT_NEW;
1504 return $flags;
1508 * Change an existing article or create a new article. Updates RC and all necessary caches,
1509 * optionally via the deferred update array.
1511 * @param Content $content New content
1512 * @param string $summary Edit summary
1513 * @param int $flags Bitfield:
1514 * EDIT_NEW
1515 * Article is known or assumed to be non-existent, create a new one
1516 * EDIT_UPDATE
1517 * Article is known or assumed to be pre-existing, update it
1518 * EDIT_MINOR
1519 * Mark this edit minor, if the user is allowed to do so
1520 * EDIT_SUPPRESS_RC
1521 * Do not log the change in recentchanges
1522 * EDIT_FORCE_BOT
1523 * Mark the edit a "bot" edit regardless of user rights
1524 * EDIT_AUTOSUMMARY
1525 * Fill in blank summaries with generated text where possible
1526 * EDIT_INTERNAL
1527 * Signal that the page retrieve/save cycle happened entirely in this request.
1529 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1530 * article will be detected. If EDIT_UPDATE is specified and the article
1531 * doesn't exist, the function will return an edit-gone-missing error. If
1532 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1533 * error will be returned. These two conditions are also possible with
1534 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1536 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1537 * This is not the parent revision ID, rather the revision ID for older
1538 * content used as the source for a rollback, for example.
1539 * @param User $user The user doing the edit
1540 * @param string $serialFormat Format for storing the content in the
1541 * database.
1542 * @param array|null $tags Change tags to apply to this edit
1543 * Callers are responsible for permission checks
1544 * (with ChangeTags::canAddTagsAccompanyingChange)
1545 * @param Int $undidRevId Id of revision that was undone or 0
1547 * @throws MWException
1548 * @return Status Possible errors:
1549 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1550 * set the fatal flag of $status.
1551 * edit-gone-missing: In update mode, but the article didn't exist.
1552 * edit-conflict: In update mode, the article changed unexpectedly.
1553 * edit-no-change: Warning that the text was the same as before.
1554 * edit-already-exists: In creation mode, but the article already exists.
1556 * Extensions may define additional errors.
1558 * $return->value will contain an associative array with members as follows:
1559 * new: Boolean indicating if the function attempted to create a new article.
1560 * revision: The revision object for the inserted revision, or null.
1562 * @since 1.21
1563 * @throws MWException
1565 public function doEditContent(
1566 Content $content, $summary, $flags = 0, $baseRevId = false,
1567 User $user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1569 global $wgUser, $wgUseAutomaticEditSummaries;
1571 // Old default parameter for $tags was null
1572 if ( $tags === null ) {
1573 $tags = [];
1576 // Low-level sanity check
1577 if ( $this->mTitle->getText() === '' ) {
1578 throw new MWException( 'Something is trying to edit an article with an empty title' );
1580 // Make sure the given content type is allowed for this page
1581 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1582 return Status::newFatal( 'content-not-allowed-here',
1583 ContentHandler::getLocalizedName( $content->getModel() ),
1584 $this->mTitle->getPrefixedText()
1588 // Load the data from the master database if needed.
1589 // The caller may already loaded it from the master or even loaded it using
1590 // SELECT FOR UPDATE, so do not override that using clear().
1591 $this->loadPageData( 'fromdbmaster' );
1593 $user = $user ?: $wgUser;
1594 $flags = $this->checkFlags( $flags );
1596 // Avoid PHP 7.1 warning of passing $this by reference
1597 $wikiPage = $this;
1599 // Trigger pre-save hook (using provided edit summary)
1600 $hookStatus = Status::newGood( [] );
1601 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1602 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1603 // Check if the hook rejected the attempted save
1604 if ( !Hooks::run( 'PageContentSave', $hook_args ) ) {
1605 if ( $hookStatus->isOK() ) {
1606 // Hook returned false but didn't call fatal(); use generic message
1607 $hookStatus->fatal( 'edit-hook-aborted' );
1610 return $hookStatus;
1613 $old_revision = $this->getRevision(); // current revision
1614 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1616 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1617 $tags[] = 'mw-contentmodelchange';
1620 // Provide autosummaries if one is not provided and autosummaries are enabled
1621 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1622 $handler = $content->getContentHandler();
1623 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1626 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1627 if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1628 $useCache = false;
1629 } else {
1630 $useCache = true;
1633 // Get the pre-save transform content and final parser output
1634 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1635 $pstContent = $editInfo->pstContent; // Content object
1636 $meta = [
1637 'bot' => ( $flags & EDIT_FORCE_BOT ),
1638 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1639 'serialized' => $editInfo->pst,
1640 'serialFormat' => $serialFormat,
1641 'baseRevId' => $baseRevId,
1642 'oldRevision' => $old_revision,
1643 'oldContent' => $old_content,
1644 'oldId' => $this->getLatest(),
1645 'oldIsRedirect' => $this->isRedirect(),
1646 'oldCountable' => $this->isCountable(),
1647 'tags' => ( $tags !== null ) ? (array)$tags : [],
1648 'undidRevId' => $undidRevId
1651 // Actually create the revision and create/update the page
1652 if ( $flags & EDIT_UPDATE ) {
1653 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1654 } else {
1655 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1658 // Promote user to any groups they meet the criteria for
1659 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1660 $user->addAutopromoteOnceGroups( 'onEdit' );
1661 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1662 } );
1664 return $status;
1668 * @param Content $content Pre-save transform content
1669 * @param integer $flags
1670 * @param User $user
1671 * @param string $summary
1672 * @param array $meta
1673 * @return Status
1674 * @throws DBUnexpectedError
1675 * @throws Exception
1676 * @throws FatalError
1677 * @throws MWException
1679 private function doModify(
1680 Content $content, $flags, User $user, $summary, array $meta
1682 global $wgUseRCPatrol;
1684 // Update article, but only if changed.
1685 $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1687 // Convenience variables
1688 $now = wfTimestampNow();
1689 $oldid = $meta['oldId'];
1690 /** @var $oldContent Content|null */
1691 $oldContent = $meta['oldContent'];
1692 $newsize = $content->getSize();
1694 if ( !$oldid ) {
1695 // Article gone missing
1696 $status->fatal( 'edit-gone-missing' );
1698 return $status;
1699 } elseif ( !$oldContent ) {
1700 // Sanity check for bug 37225
1701 throw new MWException( "Could not find text for current revision {$oldid}." );
1704 // @TODO: pass content object?!
1705 $revision = new Revision( [
1706 'page' => $this->getId(),
1707 'title' => $this->mTitle, // for determining the default content model
1708 'comment' => $summary,
1709 'minor_edit' => $meta['minor'],
1710 'text' => $meta['serialized'],
1711 'len' => $newsize,
1712 'parent_id' => $oldid,
1713 'user' => $user->getId(),
1714 'user_text' => $user->getName(),
1715 'timestamp' => $now,
1716 'content_model' => $content->getModel(),
1717 'content_format' => $meta['serialFormat'],
1718 ] );
1720 $changed = !$content->equals( $oldContent );
1722 $dbw = wfGetDB( DB_MASTER );
1724 if ( $changed ) {
1725 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1726 $status->merge( $prepStatus );
1727 if ( !$status->isOK() ) {
1728 return $status;
1731 $dbw->startAtomic( __METHOD__ );
1732 // Get the latest page_latest value while locking it.
1733 // Do a CAS style check to see if it's the same as when this method
1734 // started. If it changed then bail out before touching the DB.
1735 $latestNow = $this->lockAndGetLatest();
1736 if ( $latestNow != $oldid ) {
1737 $dbw->endAtomic( __METHOD__ );
1738 // Page updated or deleted in the mean time
1739 $status->fatal( 'edit-conflict' );
1741 return $status;
1744 // At this point we are now comitted to returning an OK
1745 // status unless some DB query error or other exception comes up.
1746 // This way callers don't have to call rollback() if $status is bad
1747 // unless they actually try to catch exceptions (which is rare).
1749 // Save the revision text
1750 $revisionId = $revision->insertOn( $dbw );
1751 // Update page_latest and friends to reflect the new revision
1752 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1753 throw new MWException( "Failed to update page row to use new revision." );
1756 Hooks::run( 'NewRevisionFromEditComplete',
1757 [ $this, $revision, $meta['baseRevId'], $user ] );
1759 // Update recentchanges
1760 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1761 // Mark as patrolled if the user can do so
1762 $patrolled = $wgUseRCPatrol && !count(
1763 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1764 // Add RC row to the DB
1765 RecentChange::notifyEdit(
1766 $now,
1767 $this->mTitle,
1768 $revision->isMinor(),
1769 $user,
1770 $summary,
1771 $oldid,
1772 $this->getTimestamp(),
1773 $meta['bot'],
1775 $oldContent ? $oldContent->getSize() : 0,
1776 $newsize,
1777 $revisionId,
1778 $patrolled,
1779 $meta['tags']
1783 $user->incEditCount();
1785 $dbw->endAtomic( __METHOD__ );
1786 $this->mTimestamp = $now;
1787 } else {
1788 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1789 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1790 $revision->setId( $this->getLatest() );
1791 $revision->setUserIdAndName(
1792 $this->getUser( Revision::RAW ),
1793 $this->getUserText( Revision::RAW )
1797 if ( $changed ) {
1798 // Return the new revision to the caller
1799 $status->value['revision'] = $revision;
1800 } else {
1801 $status->warning( 'edit-no-change' );
1802 // Update page_touched as updateRevisionOn() was not called.
1803 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1804 $this->mTitle->invalidateCache( $now );
1807 // Do secondary updates once the main changes have been committed...
1808 DeferredUpdates::addUpdate(
1809 new AtomicSectionUpdate(
1810 $dbw,
1811 __METHOD__,
1812 function () use (
1813 $revision, &$user, $content, $summary, &$flags,
1814 $changed, $meta, &$status
1816 // Update links tables, site stats, etc.
1817 $this->doEditUpdates(
1818 $revision,
1819 $user,
1821 'changed' => $changed,
1822 'oldcountable' => $meta['oldCountable'],
1823 'oldrevision' => $meta['oldRevision']
1826 // Avoid PHP 7.1 warning of passing $this by reference
1827 $wikiPage = $this;
1828 // Trigger post-save hook
1829 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR,
1830 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1831 $meta['undidRevId'] ];
1832 Hooks::run( 'PageContentSaveComplete', $params );
1835 DeferredUpdates::PRESEND
1838 return $status;
1842 * @param Content $content Pre-save transform content
1843 * @param integer $flags
1844 * @param User $user
1845 * @param string $summary
1846 * @param array $meta
1847 * @return Status
1848 * @throws DBUnexpectedError
1849 * @throws Exception
1850 * @throws FatalError
1851 * @throws MWException
1853 private function doCreate(
1854 Content $content, $flags, User $user, $summary, array $meta
1856 global $wgUseRCPatrol, $wgUseNPPatrol;
1858 $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1860 $now = wfTimestampNow();
1861 $newsize = $content->getSize();
1862 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1863 $status->merge( $prepStatus );
1864 if ( !$status->isOK() ) {
1865 return $status;
1868 $dbw = wfGetDB( DB_MASTER );
1869 $dbw->startAtomic( __METHOD__ );
1871 // Add the page record unless one already exists for the title
1872 $newid = $this->insertOn( $dbw );
1873 if ( $newid === false ) {
1874 $dbw->endAtomic( __METHOD__ ); // nothing inserted
1875 $status->fatal( 'edit-already-exists' );
1877 return $status; // nothing done
1880 // At this point we are now comitted to returning an OK
1881 // status unless some DB query error or other exception comes up.
1882 // This way callers don't have to call rollback() if $status is bad
1883 // unless they actually try to catch exceptions (which is rare).
1885 // @TODO: pass content object?!
1886 $revision = new Revision( [
1887 'page' => $newid,
1888 'title' => $this->mTitle, // for determining the default content model
1889 'comment' => $summary,
1890 'minor_edit' => $meta['minor'],
1891 'text' => $meta['serialized'],
1892 'len' => $newsize,
1893 'user' => $user->getId(),
1894 'user_text' => $user->getName(),
1895 'timestamp' => $now,
1896 'content_model' => $content->getModel(),
1897 'content_format' => $meta['serialFormat'],
1898 ] );
1900 // Save the revision text...
1901 $revisionId = $revision->insertOn( $dbw );
1902 // Update the page record with revision data
1903 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1904 throw new MWException( "Failed to update page row to use new revision." );
1907 Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1909 // Update recentchanges
1910 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1911 // Mark as patrolled if the user can do so
1912 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1913 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1914 // Add RC row to the DB
1915 RecentChange::notifyNew(
1916 $now,
1917 $this->mTitle,
1918 $revision->isMinor(),
1919 $user,
1920 $summary,
1921 $meta['bot'],
1923 $newsize,
1924 $revisionId,
1925 $patrolled,
1926 $meta['tags']
1930 $user->incEditCount();
1932 $dbw->endAtomic( __METHOD__ );
1933 $this->mTimestamp = $now;
1935 // Return the new revision to the caller
1936 $status->value['revision'] = $revision;
1938 // Do secondary updates once the main changes have been committed...
1939 DeferredUpdates::addUpdate(
1940 new AtomicSectionUpdate(
1941 $dbw,
1942 __METHOD__,
1943 function () use (
1944 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1946 // Update links, etc.
1947 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1948 // Avoid PHP 7.1 warning of passing $this by reference
1949 $wikiPage = $this;
1950 // Trigger post-create hook
1951 $params = [ &$wikiPage, &$user, $content, $summary,
1952 $flags & EDIT_MINOR, null, null, &$flags, $revision ];
1953 Hooks::run( 'PageContentInsertComplete', $params );
1954 // Trigger post-save hook
1955 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1956 Hooks::run( 'PageContentSaveComplete', $params );
1959 DeferredUpdates::PRESEND
1962 return $status;
1966 * Get parser options suitable for rendering the primary article wikitext
1968 * @see ContentHandler::makeParserOptions
1970 * @param IContextSource|User|string $context One of the following:
1971 * - IContextSource: Use the User and the Language of the provided
1972 * context
1973 * - User: Use the provided User object and $wgLang for the language,
1974 * so use an IContextSource object if possible.
1975 * - 'canonical': Canonical options (anonymous user with default
1976 * preferences and content language).
1977 * @return ParserOptions
1979 public function makeParserOptions( $context ) {
1980 $options = $this->getContentHandler()->makeParserOptions( $context );
1982 if ( $this->getTitle()->isConversionTable() ) {
1983 // @todo ConversionTable should become a separate content model, so
1984 // we don't need special cases like this one.
1985 $options->disableContentConversion();
1988 return $options;
1992 * Prepare content which is about to be saved.
1993 * Returns a stdClass with source, pst and output members
1995 * @param Content $content
1996 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1997 * revision ID is also accepted, but this is deprecated.
1998 * @param User|null $user
1999 * @param string|null $serialFormat
2000 * @param bool $useCache Check shared prepared edit cache
2002 * @return object
2004 * @since 1.21
2006 public function prepareContentForEdit(
2007 Content $content, $revision = null, User $user = null,
2008 $serialFormat = null, $useCache = true
2010 global $wgContLang, $wgUser, $wgAjaxEditStash;
2012 if ( is_object( $revision ) ) {
2013 $revid = $revision->getId();
2014 } else {
2015 $revid = $revision;
2016 // This code path is deprecated, and nothing is known to
2017 // use it, so performance here shouldn't be a worry.
2018 if ( $revid !== null ) {
2019 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2020 } else {
2021 $revision = null;
2025 $user = is_null( $user ) ? $wgUser : $user;
2026 // XXX: check $user->getId() here???
2028 // Use a sane default for $serialFormat, see bug 57026
2029 if ( $serialFormat === null ) {
2030 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2033 if ( $this->mPreparedEdit
2034 && isset( $this->mPreparedEdit->newContent )
2035 && $this->mPreparedEdit->newContent->equals( $content )
2036 && $this->mPreparedEdit->revid == $revid
2037 && $this->mPreparedEdit->format == $serialFormat
2038 // XXX: also check $user here?
2040 // Already prepared
2041 return $this->mPreparedEdit;
2044 // The edit may have already been prepared via api.php?action=stashedit
2045 $cachedEdit = $useCache && $wgAjaxEditStash
2046 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2047 : false;
2049 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2050 Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2052 $edit = (object)[];
2053 if ( $cachedEdit ) {
2054 $edit->timestamp = $cachedEdit->timestamp;
2055 } else {
2056 $edit->timestamp = wfTimestampNow();
2058 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2059 $edit->revid = $revid;
2061 if ( $cachedEdit ) {
2062 $edit->pstContent = $cachedEdit->pstContent;
2063 } else {
2064 $edit->pstContent = $content
2065 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2066 : null;
2069 $edit->format = $serialFormat;
2070 $edit->popts = $this->makeParserOptions( 'canonical' );
2071 if ( $cachedEdit ) {
2072 $edit->output = $cachedEdit->output;
2073 } else {
2074 if ( $revision ) {
2075 // We get here if vary-revision is set. This means that this page references
2076 // itself (such as via self-transclusion). In this case, we need to make sure
2077 // that any such self-references refer to the newly-saved revision, and not
2078 // to the previous one, which could otherwise happen due to replica DB lag.
2079 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2080 $edit->popts->setCurrentRevisionCallback(
2081 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2082 if ( $title->equals( $revision->getTitle() ) ) {
2083 return $revision;
2084 } else {
2085 return call_user_func( $oldCallback, $title, $parser );
2089 } else {
2090 // Try to avoid a second parse if {{REVISIONID}} is used
2091 $edit->popts->setSpeculativeRevIdCallback( function () {
2092 return 1 + (int)wfGetDB( DB_MASTER )->selectField(
2093 'revision',
2094 'MAX(rev_id)',
2096 __METHOD__
2098 } );
2100 $edit->output = $edit->pstContent
2101 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2102 : null;
2105 $edit->newContent = $content;
2106 $edit->oldContent = $this->getContent( Revision::RAW );
2108 // NOTE: B/C for hooks! don't use these fields!
2109 $edit->newText = $edit->newContent
2110 ? ContentHandler::getContentText( $edit->newContent )
2111 : '';
2112 $edit->oldText = $edit->oldContent
2113 ? ContentHandler::getContentText( $edit->oldContent )
2114 : '';
2115 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2117 if ( $edit->output ) {
2118 $edit->output->setCacheTime( wfTimestampNow() );
2121 // Process cache the result
2122 $this->mPreparedEdit = $edit;
2124 return $edit;
2128 * Do standard deferred updates after page edit.
2129 * Update links tables, site stats, search index and message cache.
2130 * Purges pages that include this page if the text was changed here.
2131 * Every 100th edit, prune the recent changes table.
2133 * @param Revision $revision
2134 * @param User $user User object that did the revision
2135 * @param array $options Array of options, following indexes are used:
2136 * - changed: boolean, whether the revision changed the content (default true)
2137 * - created: boolean, whether the revision created the page (default false)
2138 * - moved: boolean, whether the page was moved (default false)
2139 * - restored: boolean, whether the page was undeleted (default false)
2140 * - oldrevision: Revision object for the pre-update revision (default null)
2141 * - oldcountable: boolean, null, or string 'no-change' (default null):
2142 * - boolean: whether the page was counted as an article before that
2143 * revision, only used in changed is true and created is false
2144 * - null: if created is false, don't update the article count; if created
2145 * is true, do update the article count
2146 * - 'no-change': don't update the article count, ever
2148 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2149 global $wgRCWatchCategoryMembership;
2151 $options += [
2152 'changed' => true,
2153 'created' => false,
2154 'moved' => false,
2155 'restored' => false,
2156 'oldrevision' => null,
2157 'oldcountable' => null
2159 $content = $revision->getContent();
2161 $logger = LoggerFactory::getInstance( 'SaveParse' );
2163 // See if the parser output before $revision was inserted is still valid
2164 $editInfo = false;
2165 if ( !$this->mPreparedEdit ) {
2166 $logger->debug( __METHOD__ . ": No prepared edit...\n" );
2167 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2168 $logger->info( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2169 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision-id' )
2170 && $this->mPreparedEdit->output->getSpeculativeRevIdUsed() !== $revision->getId()
2172 $logger->info( __METHOD__ . ": Prepared edit has vary-revision-id with wrong ID...\n" );
2173 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2174 $logger->info( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2175 } else {
2176 wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2177 $editInfo = $this->mPreparedEdit;
2180 if ( !$editInfo ) {
2181 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2182 // $text is usually already pre-save transformed once. Avoid using the edit stash
2183 // as any prepared content from there or in doEditContent() was already rejected.
2184 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2187 // Save it to the parser cache.
2188 // Make sure the cache time matches page_touched to avoid double parsing.
2189 ParserCache::singleton()->save(
2190 $editInfo->output, $this, $editInfo->popts,
2191 $revision->getTimestamp(), $editInfo->revid
2194 // Update the links tables and other secondary data
2195 if ( $content ) {
2196 $recursive = $options['changed']; // bug 50785
2197 $updates = $content->getSecondaryDataUpdates(
2198 $this->getTitle(), null, $recursive, $editInfo->output
2200 foreach ( $updates as $update ) {
2201 if ( $update instanceof LinksUpdate ) {
2202 $update->setRevision( $revision );
2203 $update->setTriggeringUser( $user );
2205 DeferredUpdates::addUpdate( $update );
2207 if ( $wgRCWatchCategoryMembership
2208 && $this->getContentHandler()->supportsCategories() === true
2209 && ( $options['changed'] || $options['created'] )
2210 && !$options['restored']
2212 // Note: jobs are pushed after deferred updates, so the job should be able to see
2213 // the recent change entry (also done via deferred updates) and carry over any
2214 // bot/deletion/IP flags, ect.
2215 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2216 $this->getTitle(),
2218 'pageId' => $this->getId(),
2219 'revTimestamp' => $revision->getTimestamp()
2221 ) );
2225 // Avoid PHP 7.1 warning of passing $this by reference
2226 $wikiPage = $this;
2228 Hooks::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2230 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2231 // Flush old entries from the `recentchanges` table
2232 if ( mt_rand( 0, 9 ) == 0 ) {
2233 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2237 if ( !$this->exists() ) {
2238 return;
2241 $id = $this->getId();
2242 $title = $this->mTitle->getPrefixedDBkey();
2243 $shortTitle = $this->mTitle->getDBkey();
2245 if ( $options['oldcountable'] === 'no-change' ||
2246 ( !$options['changed'] && !$options['moved'] )
2248 $good = 0;
2249 } elseif ( $options['created'] ) {
2250 $good = (int)$this->isCountable( $editInfo );
2251 } elseif ( $options['oldcountable'] !== null ) {
2252 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2253 } else {
2254 $good = 0;
2256 $edits = $options['changed'] ? 1 : 0;
2257 $total = $options['created'] ? 1 : 0;
2259 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2260 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2262 // If this is another user's talk page, update newtalk.
2263 // Don't do this if $options['changed'] = false (null-edits) nor if
2264 // it's a minor edit and the user doesn't want notifications for those.
2265 if ( $options['changed']
2266 && $this->mTitle->getNamespace() == NS_USER_TALK
2267 && $shortTitle != $user->getTitleKey()
2268 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2270 $recipient = User::newFromName( $shortTitle, false );
2271 if ( !$recipient ) {
2272 wfDebug( __METHOD__ . ": invalid username\n" );
2273 } else {
2274 // Avoid PHP 7.1 warning of passing $this by reference
2275 $wikiPage = $this;
2277 // Allow extensions to prevent user notification
2278 // when a new message is added to their talk page
2279 if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2280 if ( User::isIP( $shortTitle ) ) {
2281 // An anonymous user
2282 $recipient->setNewtalk( true, $revision );
2283 } elseif ( $recipient->isLoggedIn() ) {
2284 $recipient->setNewtalk( true, $revision );
2285 } else {
2286 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2292 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2293 MessageCache::singleton()->updateMessageOverride( $this->mTitle, $content );
2296 if ( $options['created'] ) {
2297 self::onArticleCreate( $this->mTitle );
2298 } elseif ( $options['changed'] ) { // bug 50785
2299 self::onArticleEdit( $this->mTitle, $revision );
2302 ResourceLoaderWikiModule::invalidateModuleCache(
2303 $this->mTitle, $options['oldrevision'], $revision, wfWikiID()
2308 * Update the article's restriction field, and leave a log entry.
2309 * This works for protection both existing and non-existing pages.
2311 * @param array $limit Set of restriction keys
2312 * @param array $expiry Per restriction type expiration
2313 * @param int &$cascade Set to false if cascading protection isn't allowed.
2314 * @param string $reason
2315 * @param User $user The user updating the restrictions
2316 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2317 * ($user should be able to add the specified tags before this is called)
2318 * @return Status Status object; if action is taken, $status->value is the log_id of the
2319 * protection log entry.
2321 public function doUpdateRestrictions( array $limit, array $expiry,
2322 &$cascade, $reason, User $user, $tags = null
2324 global $wgCascadingRestrictionLevels, $wgContLang;
2326 if ( wfReadOnly() ) {
2327 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2330 $this->loadPageData( 'fromdbmaster' );
2331 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2332 $id = $this->getId();
2334 if ( !$cascade ) {
2335 $cascade = false;
2338 // Take this opportunity to purge out expired restrictions
2339 Title::purgeExpiredRestrictions();
2341 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2342 // we expect a single selection, but the schema allows otherwise.
2343 $isProtected = false;
2344 $protect = false;
2345 $changed = false;
2347 $dbw = wfGetDB( DB_MASTER );
2349 foreach ( $restrictionTypes as $action ) {
2350 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2351 $expiry[$action] = 'infinity';
2353 if ( !isset( $limit[$action] ) ) {
2354 $limit[$action] = '';
2355 } elseif ( $limit[$action] != '' ) {
2356 $protect = true;
2359 // Get current restrictions on $action
2360 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2361 if ( $current != '' ) {
2362 $isProtected = true;
2365 if ( $limit[$action] != $current ) {
2366 $changed = true;
2367 } elseif ( $limit[$action] != '' ) {
2368 // Only check expiry change if the action is actually being
2369 // protected, since expiry does nothing on an not-protected
2370 // action.
2371 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2372 $changed = true;
2377 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2378 $changed = true;
2381 // If nothing has changed, do nothing
2382 if ( !$changed ) {
2383 return Status::newGood();
2386 if ( !$protect ) { // No protection at all means unprotection
2387 $revCommentMsg = 'unprotectedarticle-comment';
2388 $logAction = 'unprotect';
2389 } elseif ( $isProtected ) {
2390 $revCommentMsg = 'modifiedarticleprotection-comment';
2391 $logAction = 'modify';
2392 } else {
2393 $revCommentMsg = 'protectedarticle-comment';
2394 $logAction = 'protect';
2397 // Truncate for whole multibyte characters
2398 $reason = $wgContLang->truncate( $reason, 255 );
2400 $logRelationsValues = [];
2401 $logRelationsField = null;
2402 $logParamsDetails = [];
2404 // Null revision (used for change tag insertion)
2405 $nullRevision = null;
2407 if ( $id ) { // Protection of existing page
2408 // Avoid PHP 7.1 warning of passing $this by reference
2409 $wikiPage = $this;
2411 if ( !Hooks::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2412 return Status::newGood();
2415 // Only certain restrictions can cascade...
2416 $editrestriction = isset( $limit['edit'] )
2417 ? [ $limit['edit'] ]
2418 : $this->mTitle->getRestrictions( 'edit' );
2419 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2420 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2422 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2423 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2426 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2427 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2428 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2430 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2431 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2434 // The schema allows multiple restrictions
2435 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2436 $cascade = false;
2439 // insert null revision to identify the page protection change as edit summary
2440 $latest = $this->getLatest();
2441 $nullRevision = $this->insertProtectNullRevision(
2442 $revCommentMsg,
2443 $limit,
2444 $expiry,
2445 $cascade,
2446 $reason,
2447 $user
2450 if ( $nullRevision === null ) {
2451 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2454 $logRelationsField = 'pr_id';
2456 // Update restrictions table
2457 foreach ( $limit as $action => $restrictions ) {
2458 $dbw->delete(
2459 'page_restrictions',
2461 'pr_page' => $id,
2462 'pr_type' => $action
2464 __METHOD__
2466 if ( $restrictions != '' ) {
2467 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2468 $dbw->insert(
2469 'page_restrictions',
2471 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2472 'pr_page' => $id,
2473 'pr_type' => $action,
2474 'pr_level' => $restrictions,
2475 'pr_cascade' => $cascadeValue,
2476 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2478 __METHOD__
2480 $logRelationsValues[] = $dbw->insertId();
2481 $logParamsDetails[] = [
2482 'type' => $action,
2483 'level' => $restrictions,
2484 'expiry' => $expiry[$action],
2485 'cascade' => (bool)$cascadeValue,
2490 // Clear out legacy restriction fields
2491 $dbw->update(
2492 'page',
2493 [ 'page_restrictions' => '' ],
2494 [ 'page_id' => $id ],
2495 __METHOD__
2498 // Avoid PHP 7.1 warning of passing $this by reference
2499 $wikiPage = $this;
2501 Hooks::run( 'NewRevisionFromEditComplete',
2502 [ $this, $nullRevision, $latest, $user ] );
2503 Hooks::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2504 } else { // Protection of non-existing page (also known as "title protection")
2505 // Cascade protection is meaningless in this case
2506 $cascade = false;
2508 if ( $limit['create'] != '' ) {
2509 $dbw->replace( 'protected_titles',
2510 [ [ 'pt_namespace', 'pt_title' ] ],
2512 'pt_namespace' => $this->mTitle->getNamespace(),
2513 'pt_title' => $this->mTitle->getDBkey(),
2514 'pt_create_perm' => $limit['create'],
2515 'pt_timestamp' => $dbw->timestamp(),
2516 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2517 'pt_user' => $user->getId(),
2518 'pt_reason' => $reason,
2519 ], __METHOD__
2521 $logParamsDetails[] = [
2522 'type' => 'create',
2523 'level' => $limit['create'],
2524 'expiry' => $expiry['create'],
2526 } else {
2527 $dbw->delete( 'protected_titles',
2529 'pt_namespace' => $this->mTitle->getNamespace(),
2530 'pt_title' => $this->mTitle->getDBkey()
2531 ], __METHOD__
2536 $this->mTitle->flushRestrictions();
2537 InfoAction::invalidateCache( $this->mTitle );
2539 if ( $logAction == 'unprotect' ) {
2540 $params = [];
2541 } else {
2542 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2543 $params = [
2544 '4::description' => $protectDescriptionLog, // parameter for IRC
2545 '5:bool:cascade' => $cascade,
2546 'details' => $logParamsDetails, // parameter for localize and api
2550 // Update the protection log
2551 $logEntry = new ManualLogEntry( 'protect', $logAction );
2552 $logEntry->setTarget( $this->mTitle );
2553 $logEntry->setComment( $reason );
2554 $logEntry->setPerformer( $user );
2555 $logEntry->setParameters( $params );
2556 if ( !is_null( $nullRevision ) ) {
2557 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2559 $logEntry->setTags( $tags );
2560 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2561 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2563 $logId = $logEntry->insert();
2564 $logEntry->publish( $logId );
2566 return Status::newGood( $logId );
2570 * Insert a new null revision for this page.
2572 * @param string $revCommentMsg Comment message key for the revision
2573 * @param array $limit Set of restriction keys
2574 * @param array $expiry Per restriction type expiration
2575 * @param int $cascade Set to false if cascading protection isn't allowed.
2576 * @param string $reason
2577 * @param User|null $user
2578 * @return Revision|null Null on error
2580 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2581 array $expiry, $cascade, $reason, $user = null
2583 $dbw = wfGetDB( DB_MASTER );
2585 // Prepare a null revision to be added to the history
2586 $editComment = wfMessage(
2587 $revCommentMsg,
2588 $this->mTitle->getPrefixedText(),
2589 $user ? $user->getName() : ''
2590 )->inContentLanguage()->text();
2591 if ( $reason ) {
2592 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2594 $protectDescription = $this->protectDescription( $limit, $expiry );
2595 if ( $protectDescription ) {
2596 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2597 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2598 ->inContentLanguage()->text();
2600 if ( $cascade ) {
2601 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2602 $editComment .= wfMessage( 'brackets' )->params(
2603 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2604 )->inContentLanguage()->text();
2607 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2608 if ( $nullRev ) {
2609 $nullRev->insertOn( $dbw );
2611 // Update page record and touch page
2612 $oldLatest = $nullRev->getParentId();
2613 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2616 return $nullRev;
2620 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2621 * @return string
2623 protected function formatExpiry( $expiry ) {
2624 global $wgContLang;
2626 if ( $expiry != 'infinity' ) {
2627 return wfMessage(
2628 'protect-expiring',
2629 $wgContLang->timeanddate( $expiry, false, false ),
2630 $wgContLang->date( $expiry, false, false ),
2631 $wgContLang->time( $expiry, false, false )
2632 )->inContentLanguage()->text();
2633 } else {
2634 return wfMessage( 'protect-expiry-indefinite' )
2635 ->inContentLanguage()->text();
2640 * Builds the description to serve as comment for the edit.
2642 * @param array $limit Set of restriction keys
2643 * @param array $expiry Per restriction type expiration
2644 * @return string
2646 public function protectDescription( array $limit, array $expiry ) {
2647 $protectDescription = '';
2649 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2650 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2651 # All possible message keys are listed here for easier grepping:
2652 # * restriction-create
2653 # * restriction-edit
2654 # * restriction-move
2655 # * restriction-upload
2656 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2657 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2658 # with '' filtered out. All possible message keys are listed below:
2659 # * protect-level-autoconfirmed
2660 # * protect-level-sysop
2661 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2662 ->inContentLanguage()->text();
2664 $expiryText = $this->formatExpiry( $expiry[$action] );
2666 if ( $protectDescription !== '' ) {
2667 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2669 $protectDescription .= wfMessage( 'protect-summary-desc' )
2670 ->params( $actionText, $restrictionsText, $expiryText )
2671 ->inContentLanguage()->text();
2674 return $protectDescription;
2678 * Builds the description to serve as comment for the log entry.
2680 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2681 * protect description text. Keep them in old format to avoid breaking compatibility.
2682 * TODO: Fix protection log to store structured description and format it on-the-fly.
2684 * @param array $limit Set of restriction keys
2685 * @param array $expiry Per restriction type expiration
2686 * @return string
2688 public function protectDescriptionLog( array $limit, array $expiry ) {
2689 global $wgContLang;
2691 $protectDescriptionLog = '';
2693 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2694 $expiryText = $this->formatExpiry( $expiry[$action] );
2695 $protectDescriptionLog .= $wgContLang->getDirMark() .
2696 "[$action=$restrictions] ($expiryText)";
2699 return trim( $protectDescriptionLog );
2703 * Take an array of page restrictions and flatten it to a string
2704 * suitable for insertion into the page_restrictions field.
2706 * @param string[] $limit
2708 * @throws MWException
2709 * @return string
2711 protected static function flattenRestrictions( $limit ) {
2712 if ( !is_array( $limit ) ) {
2713 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2716 $bits = [];
2717 ksort( $limit );
2719 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2720 $bits[] = "$action=$restrictions";
2723 return implode( ':', $bits );
2727 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2728 * backwards compatibility, if you care about error reporting you should use
2729 * doDeleteArticleReal() instead.
2731 * Deletes the article with database consistency, writes logs, purges caches
2733 * @param string $reason Delete reason for deletion log
2734 * @param bool $suppress Suppress all revisions and log the deletion in
2735 * the suppression log instead of the deletion log
2736 * @param int $u1 Unused
2737 * @param bool $u2 Unused
2738 * @param array|string &$error Array of errors to append to
2739 * @param User $user The deleting user
2740 * @return bool True if successful
2742 public function doDeleteArticle(
2743 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2745 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2746 return $status->isGood();
2750 * Back-end article deletion
2751 * Deletes the article with database consistency, writes logs, purges caches
2753 * @since 1.19
2755 * @param string $reason Delete reason for deletion log
2756 * @param bool $suppress Suppress all revisions and log the deletion in
2757 * the suppression log instead of the deletion log
2758 * @param int $u1 Unused
2759 * @param bool $u2 Unused
2760 * @param array|string &$error Array of errors to append to
2761 * @param User $user The deleting user
2762 * @param array $tags Tags to apply to the deletion action
2763 * @return Status Status object; if successful, $status->value is the log_id of the
2764 * deletion log entry. If the page couldn't be deleted because it wasn't
2765 * found, $status is a non-fatal 'cannotdelete' error
2767 public function doDeleteArticleReal(
2768 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2769 $tags = [], $logsubtype = 'delete'
2771 global $wgUser, $wgContentHandlerUseDB;
2773 wfDebug( __METHOD__ . "\n" );
2775 $status = Status::newGood();
2777 if ( $this->mTitle->getDBkey() === '' ) {
2778 $status->error( 'cannotdelete',
2779 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2780 return $status;
2783 // Avoid PHP 7.1 warning of passing $this by reference
2784 $wikiPage = $this;
2786 $user = is_null( $user ) ? $wgUser : $user;
2787 if ( !Hooks::run( 'ArticleDelete',
2788 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2789 ) ) {
2790 if ( $status->isOK() ) {
2791 // Hook aborted but didn't set a fatal status
2792 $status->fatal( 'delete-hook-aborted' );
2794 return $status;
2797 $dbw = wfGetDB( DB_MASTER );
2798 $dbw->startAtomic( __METHOD__ );
2800 $this->loadPageData( self::READ_LATEST );
2801 $id = $this->getId();
2802 // T98706: lock the page from various other updates but avoid using
2803 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2804 // the revisions queries (which also JOIN on user). Only lock the page
2805 // row and CAS check on page_latest to see if the trx snapshot matches.
2806 $lockedLatest = $this->lockAndGetLatest();
2807 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2808 $dbw->endAtomic( __METHOD__ );
2809 // Page not there or trx snapshot is stale
2810 $status->error( 'cannotdelete',
2811 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2812 return $status;
2815 // Given the lock above, we can be confident in the title and page ID values
2816 $namespace = $this->getTitle()->getNamespace();
2817 $dbKey = $this->getTitle()->getDBkey();
2819 // At this point we are now comitted to returning an OK
2820 // status unless some DB query error or other exception comes up.
2821 // This way callers don't have to call rollback() if $status is bad
2822 // unless they actually try to catch exceptions (which is rare).
2824 // we need to remember the old content so we can use it to generate all deletion updates.
2825 $revision = $this->getRevision();
2826 try {
2827 $content = $this->getContent( Revision::RAW );
2828 } catch ( Exception $ex ) {
2829 wfLogWarning( __METHOD__ . ': failed to load content during deletion! '
2830 . $ex->getMessage() );
2832 $content = null;
2835 $fields = Revision::selectFields();
2836 $bitfield = false;
2838 // Bitfields to further suppress the content
2839 if ( $suppress ) {
2840 $bitfield = Revision::SUPPRESSED_ALL;
2841 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2844 // For now, shunt the revision data into the archive table.
2845 // Text is *not* removed from the text table; bulk storage
2846 // is left intact to avoid breaking block-compression or
2847 // immutable storage schemes.
2848 // In the future, we may keep revisions and mark them with
2849 // the rev_deleted field, which is reserved for this purpose.
2851 // Get all of the page revisions
2852 $res = $dbw->select(
2853 'revision',
2854 $fields,
2855 [ 'rev_page' => $id ],
2856 __METHOD__,
2857 'FOR UPDATE'
2859 // Build their equivalent archive rows
2860 $rowsInsert = [];
2861 foreach ( $res as $row ) {
2862 $rowInsert = [
2863 'ar_namespace' => $namespace,
2864 'ar_title' => $dbKey,
2865 'ar_comment' => $row->rev_comment,
2866 'ar_user' => $row->rev_user,
2867 'ar_user_text' => $row->rev_user_text,
2868 'ar_timestamp' => $row->rev_timestamp,
2869 'ar_minor_edit' => $row->rev_minor_edit,
2870 'ar_rev_id' => $row->rev_id,
2871 'ar_parent_id' => $row->rev_parent_id,
2872 'ar_text_id' => $row->rev_text_id,
2873 'ar_text' => '',
2874 'ar_flags' => '',
2875 'ar_len' => $row->rev_len,
2876 'ar_page_id' => $id,
2877 'ar_deleted' => $suppress ? $bitfield : $row->rev_deleted,
2878 'ar_sha1' => $row->rev_sha1,
2880 if ( $wgContentHandlerUseDB ) {
2881 $rowInsert['ar_content_model'] = $row->rev_content_model;
2882 $rowInsert['ar_content_format'] = $row->rev_content_format;
2884 $rowsInsert[] = $rowInsert;
2886 // Copy them into the archive table
2887 $dbw->insert( 'archive', $rowsInsert, __METHOD__ );
2888 // Save this so we can pass it to the ArticleDeleteComplete hook.
2889 $archivedRevisionCount = $dbw->affectedRows();
2891 // Clone the title and wikiPage, so we have the information we need when
2892 // we log and run the ArticleDeleteComplete hook.
2893 $logTitle = clone $this->mTitle;
2894 $wikiPageBeforeDelete = clone $this;
2896 // Now that it's safely backed up, delete it
2897 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2898 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2900 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2901 $logtype = $suppress ? 'suppress' : 'delete';
2903 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2904 $logEntry->setPerformer( $user );
2905 $logEntry->setTarget( $logTitle );
2906 $logEntry->setComment( $reason );
2907 $logEntry->setTags( $tags );
2908 $logid = $logEntry->insert();
2910 $dbw->onTransactionPreCommitOrIdle(
2911 function () use ( $dbw, $logEntry, $logid ) {
2912 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2913 $logEntry->publish( $logid );
2915 __METHOD__
2918 $dbw->endAtomic( __METHOD__ );
2920 $this->doDeleteUpdates( $id, $content, $revision );
2922 Hooks::run( 'ArticleDeleteComplete', [
2923 &$wikiPageBeforeDelete,
2924 &$user,
2925 $reason,
2926 $id,
2927 $content,
2928 $logEntry,
2929 $archivedRevisionCount
2930 ] );
2931 $status->value = $logid;
2933 // Show log excerpt on 404 pages rather than just a link
2934 $cache = ObjectCache::getMainStashInstance();
2935 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2936 $cache->set( $key, 1, $cache::TTL_DAY );
2938 return $status;
2942 * Lock the page row for this title+id and return page_latest (or 0)
2944 * @return integer Returns 0 if no row was found with this title+id
2945 * @since 1.27
2947 public function lockAndGetLatest() {
2948 return (int)wfGetDB( DB_MASTER )->selectField(
2949 'page',
2950 'page_latest',
2952 'page_id' => $this->getId(),
2953 // Typically page_id is enough, but some code might try to do
2954 // updates assuming the title is the same, so verify that
2955 'page_namespace' => $this->getTitle()->getNamespace(),
2956 'page_title' => $this->getTitle()->getDBkey()
2958 __METHOD__,
2959 [ 'FOR UPDATE' ]
2964 * Do some database updates after deletion
2966 * @param int $id The page_id value of the page being deleted
2967 * @param Content|null $content Optional page content to be used when determining
2968 * the required updates. This may be needed because $this->getContent()
2969 * may already return null when the page proper was deleted.
2970 * @param Revision|null $revision The latest page revision
2972 public function doDeleteUpdates( $id, Content $content = null, Revision $revision = null ) {
2973 try {
2974 $countable = $this->isCountable();
2975 } catch ( Exception $ex ) {
2976 // fallback for deleting broken pages for which we cannot load the content for
2977 // some reason. Note that doDeleteArticleReal() already logged this problem.
2978 $countable = false;
2981 // Update site status
2982 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2984 // Delete pagelinks, update secondary indexes, etc
2985 $updates = $this->getDeletionUpdates( $content );
2986 foreach ( $updates as $update ) {
2987 DeferredUpdates::addUpdate( $update );
2990 // Reparse any pages transcluding this page
2991 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2993 // Reparse any pages including this image
2994 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2995 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2998 // Clear caches
2999 WikiPage::onArticleDelete( $this->mTitle );
3000 ResourceLoaderWikiModule::invalidateModuleCache(
3001 $this->mTitle, $revision, null, wfWikiID()
3004 // Reset this object and the Title object
3005 $this->loadFromRow( false, self::READ_LATEST );
3007 // Search engine
3008 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3012 * Roll back the most recent consecutive set of edits to a page
3013 * from the same user; fails if there are no eligible edits to
3014 * roll back to, e.g. user is the sole contributor. This function
3015 * performs permissions checks on $user, then calls commitRollback()
3016 * to do the dirty work
3018 * @todo Separate the business/permission stuff out from backend code
3019 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3021 * @param string $fromP Name of the user whose edits to rollback.
3022 * @param string $summary Custom summary. Set to default summary if empty.
3023 * @param string $token Rollback token.
3024 * @param bool $bot If true, mark all reverted edits as bot.
3026 * @param array $resultDetails Array contains result-specific array of additional values
3027 * 'alreadyrolled' : 'current' (rev)
3028 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3030 * @param User $user The user performing the rollback
3031 * @param array|null $tags Change tags to apply to the rollback
3032 * Callers are responsible for permission checks
3033 * (with ChangeTags::canAddTagsAccompanyingChange)
3035 * @return array Array of errors, each error formatted as
3036 * array(messagekey, param1, param2, ...).
3037 * On success, the array is empty. This array can also be passed to
3038 * OutputPage::showPermissionsErrorPage().
3040 public function doRollback(
3041 $fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3043 $resultDetails = null;
3045 // Check permissions
3046 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3047 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3048 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3050 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3051 $errors[] = [ 'sessionfailure' ];
3054 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3055 $errors[] = [ 'actionthrottledtext' ];
3058 // If there were errors, bail out now
3059 if ( !empty( $errors ) ) {
3060 return $errors;
3063 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3067 * Backend implementation of doRollback(), please refer there for parameter
3068 * and return value documentation
3070 * NOTE: This function does NOT check ANY permissions, it just commits the
3071 * rollback to the DB. Therefore, you should only call this function direct-
3072 * ly if you want to use custom permissions checks. If you don't, use
3073 * doRollback() instead.
3074 * @param string $fromP Name of the user whose edits to rollback.
3075 * @param string $summary Custom summary. Set to default summary if empty.
3076 * @param bool $bot If true, mark all reverted edits as bot.
3078 * @param array $resultDetails Contains result-specific array of additional values
3079 * @param User $guser The user performing the rollback
3080 * @param array|null $tags Change tags to apply to the rollback
3081 * Callers are responsible for permission checks
3082 * (with ChangeTags::canAddTagsAccompanyingChange)
3084 * @return array
3086 public function commitRollback( $fromP, $summary, $bot,
3087 &$resultDetails, User $guser, $tags = null
3089 global $wgUseRCPatrol, $wgContLang;
3091 $dbw = wfGetDB( DB_MASTER );
3093 if ( wfReadOnly() ) {
3094 return [ [ 'readonlytext' ] ];
3097 // Get the last editor
3098 $current = $this->getRevision();
3099 if ( is_null( $current ) ) {
3100 // Something wrong... no page?
3101 return [ [ 'notanarticle' ] ];
3104 $from = str_replace( '_', ' ', $fromP );
3105 // User name given should match up with the top revision.
3106 // If the user was deleted then $from should be empty.
3107 if ( $from != $current->getUserText() ) {
3108 $resultDetails = [ 'current' => $current ];
3109 return [ [ 'alreadyrolled',
3110 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3111 htmlspecialchars( $fromP ),
3112 htmlspecialchars( $current->getUserText() )
3113 ] ];
3116 // Get the last edit not by this person...
3117 // Note: these may not be public values
3118 $user = intval( $current->getUser( Revision::RAW ) );
3119 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3120 $s = $dbw->selectRow( 'revision',
3121 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3122 [ 'rev_page' => $current->getPage(),
3123 "rev_user != {$user} OR rev_user_text != {$user_text}"
3124 ], __METHOD__,
3125 [ 'USE INDEX' => 'page_timestamp',
3126 'ORDER BY' => 'rev_timestamp DESC' ]
3128 if ( $s === false ) {
3129 // No one else ever edited this page
3130 return [ [ 'cantrollback' ] ];
3131 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3132 || $s->rev_deleted & Revision::DELETED_USER
3134 // Only admins can see this text
3135 return [ [ 'notvisiblerev' ] ];
3138 // Generate the edit summary if necessary
3139 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3140 if ( empty( $summary ) ) {
3141 if ( $from == '' ) { // no public user name
3142 $summary = wfMessage( 'revertpage-nouser' );
3143 } else {
3144 $summary = wfMessage( 'revertpage' );
3148 // Allow the custom summary to use the same args as the default message
3149 $args = [
3150 $target->getUserText(), $from, $s->rev_id,
3151 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3152 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3154 if ( $summary instanceof Message ) {
3155 $summary = $summary->params( $args )->inContentLanguage()->text();
3156 } else {
3157 $summary = wfMsgReplaceArgs( $summary, $args );
3160 // Trim spaces on user supplied text
3161 $summary = trim( $summary );
3163 // Truncate for whole multibyte characters.
3164 $summary = $wgContLang->truncate( $summary, 255 );
3166 // Save
3167 $flags = EDIT_UPDATE | EDIT_INTERNAL;
3169 if ( $guser->isAllowed( 'minoredit' ) ) {
3170 $flags |= EDIT_MINOR;
3173 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3174 $flags |= EDIT_FORCE_BOT;
3177 $targetContent = $target->getContent();
3178 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3180 // Actually store the edit
3181 $status = $this->doEditContent(
3182 $targetContent,
3183 $summary,
3184 $flags,
3185 $target->getId(),
3186 $guser,
3187 null,
3188 $tags
3191 // Set patrolling and bot flag on the edits, which gets rollbacked.
3192 // This is done even on edit failure to have patrolling in that case (bug 62157).
3193 $set = [];
3194 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3195 // Mark all reverted edits as bot
3196 $set['rc_bot'] = 1;
3199 if ( $wgUseRCPatrol ) {
3200 // Mark all reverted edits as patrolled
3201 $set['rc_patrolled'] = 1;
3204 if ( count( $set ) ) {
3205 $dbw->update( 'recentchanges', $set,
3206 [ /* WHERE */
3207 'rc_cur_id' => $current->getPage(),
3208 'rc_user_text' => $current->getUserText(),
3209 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3211 __METHOD__
3215 if ( !$status->isOK() ) {
3216 return $status->getErrorsArray();
3219 // raise error, when the edit is an edit without a new version
3220 $statusRev = isset( $status->value['revision'] )
3221 ? $status->value['revision']
3222 : null;
3223 if ( !( $statusRev instanceof Revision ) ) {
3224 $resultDetails = [ 'current' => $current ];
3225 return [ [ 'alreadyrolled',
3226 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3227 htmlspecialchars( $fromP ),
3228 htmlspecialchars( $current->getUserText() )
3229 ] ];
3232 if ( $changingContentModel ) {
3233 // If the content model changed during the rollback,
3234 // make sure it gets logged to Special:Log/contentmodel
3235 $log = new ManualLogEntry( 'contentmodel', 'change' );
3236 $log->setPerformer( $guser );
3237 $log->setTarget( $this->mTitle );
3238 $log->setComment( $summary );
3239 $log->setParameters( [
3240 '4::oldmodel' => $current->getContentModel(),
3241 '5::newmodel' => $targetContent->getModel(),
3242 ] );
3244 $logId = $log->insert( $dbw );
3245 $log->publish( $logId );
3248 $revId = $statusRev->getId();
3250 Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3252 $resultDetails = [
3253 'summary' => $summary,
3254 'current' => $current,
3255 'target' => $target,
3256 'newid' => $revId
3259 return [];
3263 * The onArticle*() functions are supposed to be a kind of hooks
3264 * which should be called whenever any of the specified actions
3265 * are done.
3267 * This is a good place to put code to clear caches, for instance.
3269 * This is called on page move and undelete, as well as edit
3271 * @param Title $title
3273 public static function onArticleCreate( Title $title ) {
3274 // Update existence markers on article/talk tabs...
3275 $other = $title->getOtherPage();
3277 $other->purgeSquid();
3279 $title->touchLinks();
3280 $title->purgeSquid();
3281 $title->deleteTitleProtection();
3283 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3285 if ( $title->getNamespace() == NS_CATEGORY ) {
3286 // Load the Category object, which will schedule a job to create
3287 // the category table row if necessary. Checking a replica DB is ok
3288 // here, in the worst case it'll run an unnecessary recount job on
3289 // a category that probably doesn't have many members.
3290 Category::newFromTitle( $title )->getID();
3295 * Clears caches when article is deleted
3297 * @param Title $title
3299 public static function onArticleDelete( Title $title ) {
3300 // Update existence markers on article/talk tabs...
3301 $other = $title->getOtherPage();
3303 $other->purgeSquid();
3305 $title->touchLinks();
3306 $title->purgeSquid();
3308 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3310 // File cache
3311 HTMLFileCache::clearFileCache( $title );
3312 InfoAction::invalidateCache( $title );
3314 // Messages
3315 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3316 MessageCache::singleton()->updateMessageOverride( $title, null );
3319 // Images
3320 if ( $title->getNamespace() == NS_FILE ) {
3321 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3324 // User talk pages
3325 if ( $title->getNamespace() == NS_USER_TALK ) {
3326 $user = User::newFromName( $title->getText(), false );
3327 if ( $user ) {
3328 $user->setNewtalk( false );
3332 // Image redirects
3333 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3337 * Purge caches on page update etc
3339 * @param Title $title
3340 * @param Revision|null $revision Revision that was just saved, may be null
3342 public static function onArticleEdit( Title $title, Revision $revision = null ) {
3343 // Invalidate caches of articles which include this page
3344 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3346 // Invalidate the caches of all pages which redirect here
3347 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3349 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3351 // Purge CDN for this page only
3352 $title->purgeSquid();
3353 // Clear file cache for this page only
3354 HTMLFileCache::clearFileCache( $title );
3356 $revid = $revision ? $revision->getId() : null;
3357 DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3358 InfoAction::invalidateCache( $title, $revid );
3359 } );
3362 /**#@-*/
3365 * Returns a list of categories this page is a member of.
3366 * Results will include hidden categories
3368 * @return TitleArray
3370 public function getCategories() {
3371 $id = $this->getId();
3372 if ( $id == 0 ) {
3373 return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3376 $dbr = wfGetDB( DB_REPLICA );
3377 $res = $dbr->select( 'categorylinks',
3378 [ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3379 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3380 // as not being aliases, and NS_CATEGORY is numeric
3381 [ 'cl_from' => $id ],
3382 __METHOD__ );
3384 return TitleArray::newFromResult( $res );
3388 * Returns a list of hidden categories this page is a member of.
3389 * Uses the page_props and categorylinks tables.
3391 * @return array Array of Title objects
3393 public function getHiddenCategories() {
3394 $result = [];
3395 $id = $this->getId();
3397 if ( $id == 0 ) {
3398 return [];
3401 $dbr = wfGetDB( DB_REPLICA );
3402 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3403 [ 'cl_to' ],
3404 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3405 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3406 __METHOD__ );
3408 if ( $res !== false ) {
3409 foreach ( $res as $row ) {
3410 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3414 return $result;
3418 * Auto-generates a deletion reason
3420 * @param bool &$hasHistory Whether the page has a history
3421 * @return string|bool String containing deletion reason or empty string, or boolean false
3422 * if no revision occurred
3424 public function getAutoDeleteReason( &$hasHistory ) {
3425 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3429 * Update all the appropriate counts in the category table, given that
3430 * we've added the categories $added and deleted the categories $deleted.
3432 * This should only be called from deferred updates or jobs to avoid contention.
3434 * @param array $added The names of categories that were added
3435 * @param array $deleted The names of categories that were deleted
3436 * @param integer $id Page ID (this should be the original deleted page ID)
3438 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3439 $id = $id ?: $this->getId();
3440 $ns = $this->getTitle()->getNamespace();
3442 $addFields = [ 'cat_pages = cat_pages + 1' ];
3443 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3444 if ( $ns == NS_CATEGORY ) {
3445 $addFields[] = 'cat_subcats = cat_subcats + 1';
3446 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3447 } elseif ( $ns == NS_FILE ) {
3448 $addFields[] = 'cat_files = cat_files + 1';
3449 $removeFields[] = 'cat_files = cat_files - 1';
3452 $dbw = wfGetDB( DB_MASTER );
3454 if ( count( $added ) ) {
3455 $existingAdded = $dbw->selectFieldValues(
3456 'category',
3457 'cat_title',
3458 [ 'cat_title' => $added ],
3459 __METHOD__
3462 // For category rows that already exist, do a plain
3463 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3464 // to avoid creating gaps in the cat_id sequence.
3465 if ( count( $existingAdded ) ) {
3466 $dbw->update(
3467 'category',
3468 $addFields,
3469 [ 'cat_title' => $existingAdded ],
3470 __METHOD__
3474 $missingAdded = array_diff( $added, $existingAdded );
3475 if ( count( $missingAdded ) ) {
3476 $insertRows = [];
3477 foreach ( $missingAdded as $cat ) {
3478 $insertRows[] = [
3479 'cat_title' => $cat,
3480 'cat_pages' => 1,
3481 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3482 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3485 $dbw->upsert(
3486 'category',
3487 $insertRows,
3488 [ 'cat_title' ],
3489 $addFields,
3490 __METHOD__
3495 if ( count( $deleted ) ) {
3496 $dbw->update(
3497 'category',
3498 $removeFields,
3499 [ 'cat_title' => $deleted ],
3500 __METHOD__
3504 foreach ( $added as $catName ) {
3505 $cat = Category::newFromName( $catName );
3506 Hooks::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3509 foreach ( $deleted as $catName ) {
3510 $cat = Category::newFromName( $catName );
3511 Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3514 // Refresh counts on categories that should be empty now, to
3515 // trigger possible deletion. Check master for the most
3516 // up-to-date cat_pages.
3517 if ( count( $deleted ) ) {
3518 $rows = $dbw->select(
3519 'category',
3520 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3521 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3522 __METHOD__
3524 foreach ( $rows as $row ) {
3525 $cat = Category::newFromRow( $row );
3526 $cat->refreshCounts();
3532 * Opportunistically enqueue link update jobs given fresh parser output if useful
3534 * @param ParserOutput $parserOutput Current version page output
3535 * @since 1.25
3537 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3538 if ( wfReadOnly() ) {
3539 return;
3542 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3543 [ $this, $this->mTitle, $parserOutput ]
3544 ) ) {
3545 return;
3548 $config = RequestContext::getMain()->getConfig();
3550 $params = [
3551 'isOpportunistic' => true,
3552 'rootJobTimestamp' => $parserOutput->getCacheTime()
3555 if ( $this->mTitle->areRestrictionsCascading() ) {
3556 // If the page is cascade protecting, the links should really be up-to-date
3557 JobQueueGroup::singleton()->lazyPush(
3558 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3560 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3561 // Assume the output contains "dynamic" time/random based magic words.
3562 // Only update pages that expired due to dynamic content and NOT due to edits
3563 // to referenced templates/files. When the cache expires due to dynamic content,
3564 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3565 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3566 // template/file edit already triggered recursive RefreshLinksJob jobs.
3567 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3568 // If a page is uncacheable, do not keep spamming a job for it.
3569 // Although it would be de-duplicated, it would still waste I/O.
3570 $cache = ObjectCache::getLocalClusterInstance();
3571 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3572 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3573 if ( $cache->add( $key, time(), $ttl ) ) {
3574 JobQueueGroup::singleton()->lazyPush(
3575 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3583 * Returns a list of updates to be performed when this page is deleted. The
3584 * updates should remove any information about this page from secondary data
3585 * stores such as links tables.
3587 * @param Content|null $content Optional Content object for determining the
3588 * necessary updates.
3589 * @return DeferrableUpdate[]
3591 public function getDeletionUpdates( Content $content = null ) {
3592 if ( !$content ) {
3593 // load content object, which may be used to determine the necessary updates.
3594 // XXX: the content may not be needed to determine the updates.
3595 try {
3596 $content = $this->getContent( Revision::RAW );
3597 } catch ( Exception $ex ) {
3598 // If we can't load the content, something is wrong. Perhaps that's why
3599 // the user is trying to delete the page, so let's not fail in that case.
3600 // Note that doDeleteArticleReal() will already have logged an issue with
3601 // loading the content.
3605 if ( !$content ) {
3606 $updates = [];
3607 } else {
3608 $updates = $content->getDeletionUpdates( $this );
3611 Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3612 return $updates;
3616 * Whether this content displayed on this page
3617 * comes from the local database
3619 * @since 1.28
3620 * @return bool
3622 public function isLocal() {
3623 return true;
3627 * The display name for the site this content
3628 * come from. If a subclass overrides isLocal(),
3629 * this could return something other than the
3630 * current site name
3632 * @since 1.28
3633 * @return string
3635 public function getWikiDisplayName() {
3636 global $wgSitename;
3637 return $wgSitename;
3641 * Get the source URL for the content on this page,
3642 * typically the canonical URL, but may be a remote
3643 * link if the content comes from another site
3645 * @since 1.28
3646 * @return string
3648 public function getSourceURL() {
3649 return $this->getTitle()->getCanonicalURL();