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
23 use MediaWiki\Edit\PreparedEdit
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Assert\Assert
;
27 use Wikimedia\Rdbms\FakeResultWrapper
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use Wikimedia\Rdbms\DBUnexpectedError
;
32 * Class representing a MediaWiki article and history.
34 * Some fields are public only for backwards-compatibility. Use accessors.
35 * In the past, this class was part of Article.php and everything was public.
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mLinksUpdated = '19700101000000';
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;
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." );
125 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
131 $page = new WikiFilePage( $title );
134 $page = new WikiCategoryPage( $title );
137 $page = new WikiPage( $title );
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 ids are never 0 or negative, see T63166
159 $from = self
::convertSelectType( $from );
160 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
161 $pageQuery = self
::getQueryInfo();
162 $row = $db->selectRow(
163 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
164 [], $pageQuery['joins']
169 return self
::newFromRow( $row, $from );
173 * Constructor from a database row
176 * @param object $row Database row containing at least fields returned by selectFields().
177 * @param string|int $from Source of $data:
178 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
179 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
180 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
183 public static function newFromRow( $row, $from = 'fromdb' ) {
184 $page = self
::factory( Title
::newFromRow( $row ) );
185 $page->loadFromRow( $row, $from );
190 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
192 * @param object|string|int $type
195 private static function convertSelectType( $type ) {
198 return self
::READ_NORMAL
;
200 return self
::READ_LATEST
;
202 return self
::READ_LOCKING
;
204 // It may already be an integer or whatever else
210 * @todo Move this UI stuff somewhere else
212 * @see ContentHandler::getActionOverrides
215 public function getActionOverrides() {
216 return $this->getContentHandler()->getActionOverrides();
220 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
222 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
224 * @return ContentHandler
228 public function getContentHandler() {
229 return ContentHandler
::getForModelID( $this->getContentModel() );
233 * Get the title object of the article
234 * @return Title Title object of this page
236 public function getTitle() {
237 return $this->mTitle
;
244 public function clear() {
245 $this->mDataLoaded
= false;
246 $this->mDataLoadedFrom
= self
::READ_NONE
;
248 $this->clearCacheFields();
252 * Clear the object cache fields
255 protected function clearCacheFields() {
257 $this->mRedirectTarget
= null; // Title object if set
258 $this->mLastRevision
= null; // Latest revision
259 $this->mTouched
= '19700101000000';
260 $this->mLinksUpdated
= '19700101000000';
261 $this->mTimestamp
= '';
262 $this->mIsRedirect
= false;
263 $this->mLatest
= false;
264 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
265 // the requested rev ID and content against the cached one for equality. For most
266 // content types, the output should not change during the lifetime of this cache.
267 // Clearing it can cause extra parses on edit for no reason.
271 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
275 public function clearPreparedEdit() {
276 $this->mPreparedEdit
= false;
280 * Return the list of revision fields that should be selected to create
283 * @deprecated since 1.31, use self::getQueryInfo() instead.
286 public static function selectFields() {
287 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
289 wfDeprecated( __METHOD__
, '1.31' );
300 'page_links_updated',
305 if ( $wgContentHandlerUseDB ) {
306 $fields[] = 'page_content_model';
309 if ( $wgPageLanguageUseDB ) {
310 $fields[] = 'page_lang';
317 * Return the tables, fields, and join conditions to be selected to create
320 * @return array With three keys:
321 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
322 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
323 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
325 public static function getQueryInfo() {
326 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
329 'tables' => [ 'page' ],
339 'page_links_updated',
346 if ( $wgContentHandlerUseDB ) {
347 $ret['fields'][] = 'page_content_model';
350 if ( $wgPageLanguageUseDB ) {
351 $ret['fields'][] = 'page_lang';
358 * Fetch a page record with the given conditions
359 * @param IDatabase $dbr
360 * @param array $conditions
361 * @param array $options
362 * @return object|bool Database result resource, or false on failure
364 protected function pageData( $dbr, $conditions, $options = [] ) {
365 $pageQuery = self
::getQueryInfo();
367 // Avoid PHP 7.1 warning of passing $this by reference
370 Hooks
::run( 'ArticlePageDataBefore', [
371 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
374 $row = $dbr->selectRow(
375 $pageQuery['tables'],
376 $pageQuery['fields'],
383 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
389 * Fetch a page record matching the Title object's namespace and title
390 * using a sanitized title string
392 * @param IDatabase $dbr
393 * @param Title $title
394 * @param array $options
395 * @return object|bool Database result resource, or false on failure
397 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
398 return $this->pageData( $dbr, [
399 'page_namespace' => $title->getNamespace(),
400 'page_title' => $title->getDBkey() ], $options );
404 * Fetch a page record matching the requested ID
406 * @param IDatabase $dbr
408 * @param array $options
409 * @return object|bool Database result resource, or false on failure
411 public function pageDataFromId( $dbr, $id, $options = [] ) {
412 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
416 * Load the object from a given source by title
418 * @param object|string|int $from One of the following:
419 * - A DB query result object.
420 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
421 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
422 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
423 * using SELECT FOR UPDATE.
427 public function loadPageData( $from = 'fromdb' ) {
428 $from = self
::convertSelectType( $from );
429 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
430 // We already have the data from the correct location, no need to load it twice.
434 if ( is_int( $from ) ) {
435 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
436 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
437 $db = $loadBalancer->getConnection( $index );
438 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
441 && $index == DB_REPLICA
442 && $loadBalancer->getServerCount() > 1
443 && $loadBalancer->hasOrMadeRecentMasterChanges()
445 $from = self
::READ_LATEST
;
446 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
447 $db = $loadBalancer->getConnection( $index );
448 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
451 // No idea from where the caller got this data, assume replica DB.
453 $from = self
::READ_NORMAL
;
456 $this->loadFromRow( $data, $from );
460 * Load the object from a database row
463 * @param object|bool $data DB row containing fields returned by selectFields() or false
464 * @param string|int $from One of the following:
465 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
466 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
467 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
468 * the master DB using SELECT FOR UPDATE
470 public function loadFromRow( $data, $from ) {
471 $lc = LinkCache
::singleton();
472 $lc->clearLink( $this->mTitle
);
475 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
477 $this->mTitle
->loadFromRow( $data );
479 // Old-fashioned restrictions
480 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
482 $this->mId
= intval( $data->page_id
);
483 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
484 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
485 $this->mIsRedirect
= intval( $data->page_is_redirect
);
486 $this->mLatest
= intval( $data->page_latest
);
487 // T39225: $latest may no longer match the cached latest Revision object.
488 // Double-check the ID of any cached latest Revision object for consistency.
489 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
490 $this->mLastRevision
= null;
491 $this->mTimestamp
= '';
494 $lc->addBadLinkObj( $this->mTitle
);
496 $this->mTitle
->loadFromRow( false );
498 $this->clearCacheFields();
503 $this->mDataLoaded
= true;
504 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
508 * @return int Page ID
510 public function getId() {
511 if ( !$this->mDataLoaded
) {
512 $this->loadPageData();
518 * @return bool Whether or not the page exists in the database
520 public function exists() {
521 if ( !$this->mDataLoaded
) {
522 $this->loadPageData();
524 return $this->mId
> 0;
528 * Check if this page is something we're going to be showing
529 * some sort of sensible content for. If we return false, page
530 * views (plain action=view) will return an HTTP 404 response,
531 * so spiders and robots can know they're following a bad link.
535 public function hasViewableContent() {
536 return $this->mTitle
->isKnown();
540 * Tests if the article content represents a redirect
544 public function isRedirect() {
545 if ( !$this->mDataLoaded
) {
546 $this->loadPageData();
549 return (bool)$this->mIsRedirect
;
553 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
555 * Will use the revisions actual content model if the page exists,
556 * and the page's default if the page doesn't exist yet.
562 public function getContentModel() {
563 if ( $this->exists() ) {
564 $cache = ObjectCache
::getMainWANInstance();
566 return $cache->getWithSetCallback(
567 $cache->makeKey( 'page-content-model', $this->getLatest() ),
570 $rev = $this->getRevision();
572 // Look at the revision's actual content model
573 return $rev->getContentModel();
575 $title = $this->mTitle
->getPrefixedDBkey();
576 wfWarn( "Page $title exists but has no (visible) revisions!" );
577 return $this->mTitle
->getContentModel();
583 // use the default model for this page
584 return $this->mTitle
->getContentModel();
588 * Loads page_touched and returns a value indicating if it should be used
589 * @return bool True if this page exists and is not a redirect
591 public function checkTouched() {
592 if ( !$this->mDataLoaded
) {
593 $this->loadPageData();
595 return ( $this->mId
&& !$this->mIsRedirect
);
599 * Get the page_touched field
600 * @return string Containing GMT timestamp
602 public function getTouched() {
603 if ( !$this->mDataLoaded
) {
604 $this->loadPageData();
606 return $this->mTouched
;
610 * Get the page_links_updated field
611 * @return string|null Containing GMT timestamp
613 public function getLinksTimestamp() {
614 if ( !$this->mDataLoaded
) {
615 $this->loadPageData();
617 return $this->mLinksUpdated
;
621 * Get the page_latest field
622 * @return int The rev_id of current revision
624 public function getLatest() {
625 if ( !$this->mDataLoaded
) {
626 $this->loadPageData();
628 return (int)$this->mLatest
;
632 * Get the Revision object of the oldest revision
633 * @return Revision|null
635 public function getOldestRevision() {
636 // Try using the replica DB first, then try the master
637 $rev = $this->mTitle
->getFirstRevision();
639 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
645 * Loads everything except the text
646 * This isn't necessary for all uses, so it's only done if needed.
648 protected function loadLastEdit() {
649 if ( $this->mLastRevision
!== null ) {
650 return; // already loaded
653 $latest = $this->getLatest();
655 return; // page doesn't exist or is missing page_latest info
658 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
659 // T39225: if session S1 loads the page row FOR UPDATE, the result always
660 // includes the latest changes committed. This is true even within REPEATABLE-READ
661 // transactions, where S1 normally only sees changes committed before the first S1
662 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
663 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
664 // happened after the first S1 SELECT.
665 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
666 $flags = Revision
::READ_LOCKING
;
667 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
668 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
669 // Bug T93976: if page_latest was loaded from the master, fetch the
670 // revision from there as well, as it may not exist yet on a replica DB.
671 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
672 $flags = Revision
::READ_LATEST
;
673 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
675 $dbr = wfGetDB( DB_REPLICA
);
676 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
679 if ( $revision ) { // sanity
680 $this->setLastEdit( $revision );
685 * Set the latest revision
686 * @param Revision $revision
688 protected function setLastEdit( Revision
$revision ) {
689 $this->mLastRevision
= $revision;
690 $this->mTimestamp
= $revision->getTimestamp();
694 * Get the latest revision
695 * @return Revision|null
697 public function getRevision() {
698 $this->loadLastEdit();
699 if ( $this->mLastRevision
) {
700 return $this->mLastRevision
;
706 * Get the content of the current revision. No side-effects...
708 * @param int $audience One of:
709 * Revision::FOR_PUBLIC to be displayed to all users
710 * Revision::FOR_THIS_USER to be displayed to $wgUser
711 * Revision::RAW get the text regardless of permissions
712 * @param User $user User object to check for, only if FOR_THIS_USER is passed
713 * to the $audience parameter
714 * @return Content|null The content of the current revision
718 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
719 $this->loadLastEdit();
720 if ( $this->mLastRevision
) {
721 return $this->mLastRevision
->getContent( $audience, $user );
727 * @return string MW timestamp of last article revision
729 public function getTimestamp() {
730 // Check if the field has been filled by WikiPage::setTimestamp()
731 if ( !$this->mTimestamp
) {
732 $this->loadLastEdit();
735 return wfTimestamp( TS_MW
, $this->mTimestamp
);
739 * Set the page timestamp (use only to avoid DB queries)
740 * @param string $ts MW timestamp of last article revision
743 public function setTimestamp( $ts ) {
744 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
748 * @param int $audience One of:
749 * Revision::FOR_PUBLIC to be displayed to all users
750 * Revision::FOR_THIS_USER to be displayed to the given user
751 * Revision::RAW get the text regardless of permissions
752 * @param User $user User object to check for, only if FOR_THIS_USER is passed
753 * to the $audience parameter
754 * @return int User ID for the user that made the last article revision
756 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
757 $this->loadLastEdit();
758 if ( $this->mLastRevision
) {
759 return $this->mLastRevision
->getUser( $audience, $user );
766 * Get the User object of the user who created the page
767 * @param int $audience One of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to the given user
770 * Revision::RAW get the text regardless of permissions
771 * @param User $user User object to check for, only if FOR_THIS_USER is passed
772 * to the $audience parameter
775 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
776 $revision = $this->getOldestRevision();
778 $userName = $revision->getUserText( $audience, $user );
779 return User
::newFromName( $userName, false );
786 * @param int $audience One of:
787 * Revision::FOR_PUBLIC to be displayed to all users
788 * Revision::FOR_THIS_USER to be displayed to the given user
789 * Revision::RAW get the text regardless of permissions
790 * @param User $user User object to check for, only if FOR_THIS_USER is passed
791 * to the $audience parameter
792 * @return string Username of the user that made the last article revision
794 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
795 $this->loadLastEdit();
796 if ( $this->mLastRevision
) {
797 return $this->mLastRevision
->getUserText( $audience, $user );
804 * @param int $audience One of:
805 * Revision::FOR_PUBLIC to be displayed to all users
806 * Revision::FOR_THIS_USER to be displayed to the given user
807 * Revision::RAW get the text regardless of permissions
808 * @param User $user User object to check for, only if FOR_THIS_USER is passed
809 * to the $audience parameter
810 * @return string Comment stored for the last article revision
812 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
813 $this->loadLastEdit();
814 if ( $this->mLastRevision
) {
815 return $this->mLastRevision
->getComment( $audience, $user );
822 * Returns true if last revision was marked as "minor edit"
824 * @return bool Minor edit indicator for the last article revision.
826 public function getMinorEdit() {
827 $this->loadLastEdit();
828 if ( $this->mLastRevision
) {
829 return $this->mLastRevision
->isMinor();
836 * Determine whether a page would be suitable for being counted as an
837 * article in the site_stats table based on the title & its content
839 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
840 * if false, the current database state will be used
843 public function isCountable( $editInfo = false ) {
844 global $wgArticleCountMethod;
846 if ( !$this->mTitle
->isContentPage() ) {
851 $content = $editInfo->pstContent
;
853 $content = $this->getContent();
856 if ( !$content ||
$content->isRedirect() ) {
862 if ( $wgArticleCountMethod === 'link' ) {
863 // nasty special case to avoid re-parsing to detect links
866 // ParserOutput::getLinks() is a 2D array of page links, so
867 // to be really correct we would need to recurse in the array
868 // but the main array should only have items in it if there are
870 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
872 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
873 [ 'pl_from' => $this->getId() ], __METHOD__
);
877 return $content->isCountable( $hasLinks );
881 * If this page is a redirect, get its target
883 * The target will be fetched from the redirect table if possible.
884 * If this page doesn't have an entry there, call insertRedirect()
885 * @return Title|null Title object, or null if this page is not a redirect
887 public function getRedirectTarget() {
888 if ( !$this->mTitle
->isRedirect() ) {
892 if ( $this->mRedirectTarget
!== null ) {
893 return $this->mRedirectTarget
;
896 // Query the redirect table
897 $dbr = wfGetDB( DB_REPLICA
);
898 $row = $dbr->selectRow( 'redirect',
899 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
900 [ 'rd_from' => $this->getId() ],
904 // rd_fragment and rd_interwiki were added later, populate them if empty
905 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
906 $this->mRedirectTarget
= Title
::makeTitle(
907 $row->rd_namespace
, $row->rd_title
,
908 $row->rd_fragment
, $row->rd_interwiki
910 return $this->mRedirectTarget
;
913 // This page doesn't have an entry in the redirect table
914 $this->mRedirectTarget
= $this->insertRedirect();
915 return $this->mRedirectTarget
;
919 * Insert an entry for this page into the redirect table if the content is a redirect
921 * The database update will be deferred via DeferredUpdates
923 * Don't call this function directly unless you know what you're doing.
924 * @return Title|null Title object or null if not a redirect
926 public function insertRedirect() {
927 $content = $this->getContent();
928 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
933 // Update the DB post-send if the page has not cached since now
934 $latest = $this->getLatest();
935 DeferredUpdates
::addCallableUpdate(
936 function () use ( $retval, $latest ) {
937 $this->insertRedirectEntry( $retval, $latest );
939 DeferredUpdates
::POSTSEND
,
947 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
948 * @param Title $rt Redirect target
949 * @param int|null $oldLatest Prior page_latest for check and set
951 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
952 $dbw = wfGetDB( DB_MASTER
);
953 $dbw->startAtomic( __METHOD__
);
955 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
959 'rd_from' => $this->getId(),
960 'rd_namespace' => $rt->getNamespace(),
961 'rd_title' => $rt->getDBkey(),
962 'rd_fragment' => $rt->getFragment(),
963 'rd_interwiki' => $rt->getInterwiki(),
967 'rd_namespace' => $rt->getNamespace(),
968 'rd_title' => $rt->getDBkey(),
969 'rd_fragment' => $rt->getFragment(),
970 'rd_interwiki' => $rt->getInterwiki(),
976 $dbw->endAtomic( __METHOD__
);
980 * Get the Title object or URL this page redirects to
982 * @return bool|Title|string False, Title of in-wiki target, or string with URL
984 public function followRedirect() {
985 return $this->getRedirectURL( $this->getRedirectTarget() );
989 * Get the Title object or URL to use for a redirect. We use Title
990 * objects for same-wiki, non-special redirects and URLs for everything
992 * @param Title $rt Redirect target
993 * @return bool|Title|string False, Title object of local target, or string with URL
995 public function getRedirectURL( $rt ) {
1000 if ( $rt->isExternal() ) {
1001 if ( $rt->isLocal() ) {
1002 // Offsite wikis need an HTTP redirect.
1003 // This can be hard to reverse and may produce loops,
1004 // so they may be disabled in the site configuration.
1005 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1006 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1008 // External pages without "local" bit set are not valid
1014 if ( $rt->isSpecialPage() ) {
1015 // Gotta handle redirects to special pages differently:
1016 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1017 // Some pages are not valid targets.
1018 if ( $rt->isValidRedirectTarget() ) {
1019 return $rt->getFullURL();
1029 * Get a list of users who have edited this article, not including the user who made
1030 * the most recent revision, which you can get from $article->getUser() if you want it
1031 * @return UserArrayFromResult
1033 public function getContributors() {
1034 // @todo FIXME: This is expensive; cache this info somewhere.
1036 $dbr = wfGetDB( DB_REPLICA
);
1038 $actorMigration = ActorMigration
::newMigration();
1039 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1041 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1044 'user_id' => $actorQuery['fields']['rev_user'],
1045 'user_name' => $actorQuery['fields']['rev_user_text'],
1046 'actor_id' => $actorQuery['fields']['rev_actor'],
1047 'user_real_name' => 'MIN(user_real_name)',
1048 'timestamp' => 'MAX(rev_timestamp)',
1051 $conds = [ 'rev_page' => $this->getId() ];
1053 // The user who made the top revision gets credited as "this page was last edited by
1054 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1055 $user = $this->getUser()
1056 ? User
::newFromId( $this->getUser() )
1057 : User
::newFromName( $this->getUserText(), false );
1058 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1061 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1064 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1065 ] +
$actorQuery['joins'];
1068 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1069 'ORDER BY' => 'timestamp DESC',
1072 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1073 return new UserArrayFromResult( $res );
1077 * Should the parser cache be used?
1079 * @param ParserOptions $parserOptions ParserOptions to check
1083 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1084 return $parserOptions->getStubThreshold() == 0
1086 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1087 && $this->getContentHandler()->isParserCacheSupported();
1091 * Get a ParserOutput for the given ParserOptions and revision ID.
1093 * The parser cache will be used if possible. Cache misses that result
1094 * in parser runs are debounced with PoolCounter.
1097 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1098 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1099 * get the current revision (default value)
1100 * @param bool $forceParse Force reindexing, regardless of cache settings
1101 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1103 public function getParserOutput(
1104 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1107 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1109 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1110 throw new InvalidArgumentException(
1111 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1115 wfDebug( __METHOD__
.
1116 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1117 if ( $parserOptions->getStubThreshold() ) {
1118 wfIncrStats( 'pcache.miss.stub' );
1121 if ( $useParserCache ) {
1122 $parserOutput = MediaWikiServices
::getInstance()->getParserCache()
1123 ->get( $this, $parserOptions );
1124 if ( $parserOutput !== false ) {
1125 return $parserOutput;
1129 if ( $oldid === null ||
$oldid === 0 ) {
1130 $oldid = $this->getLatest();
1133 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1136 return $pool->getParserOutput();
1140 * Do standard deferred updates after page view (existing or missing page)
1141 * @param User $user The relevant user
1142 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1144 public function doViewUpdates( User
$user, $oldid = 0 ) {
1145 if ( wfReadOnly() ) {
1149 // Update newtalk / watchlist notification status;
1150 // Avoid outage if the master is not reachable by using a deferred updated
1151 DeferredUpdates
::addCallableUpdate(
1152 function () use ( $user, $oldid ) {
1153 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1155 $user->clearNotification( $this->mTitle
, $oldid );
1157 DeferredUpdates
::PRESEND
1162 * Perform the actions of a page purging
1164 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1165 * controlled how much purging was done.
1167 public function doPurge() {
1168 // Avoid PHP 7.1 warning of passing $this by reference
1171 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1175 $this->mTitle
->invalidateCache();
1178 HTMLFileCache
::clearFileCache( $this->getTitle() );
1179 // Send purge after above page_touched update was committed
1180 DeferredUpdates
::addUpdate(
1181 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1182 DeferredUpdates
::PRESEND
1185 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1186 $messageCache = MessageCache
::singleton();
1187 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1194 * Insert a new empty page record for this article.
1195 * This *must* be followed up by creating a revision
1196 * and running $this->updateRevisionOn( ... );
1197 * or else the record will be left in a funky state.
1198 * Best if all done inside a transaction.
1200 * @param IDatabase $dbw
1201 * @param int|null $pageId Custom page ID that will be used for the insert statement
1203 * @return bool|int The newly created page_id key; false if the row was not
1204 * inserted, e.g. because the title already existed or because the specified
1205 * page ID is already in use.
1207 public function insertOn( $dbw, $pageId = null ) {
1208 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1212 'page_namespace' => $this->mTitle
->getNamespace(),
1213 'page_title' => $this->mTitle
->getDBkey(),
1214 'page_restrictions' => '',
1215 'page_is_redirect' => 0, // Will set this shortly...
1217 'page_random' => wfRandom(),
1218 'page_touched' => $dbw->timestamp(),
1219 'page_latest' => 0, // Fill this in shortly...
1220 'page_len' => 0, // Fill this in shortly...
1221 ] +
$pageIdForInsert,
1226 if ( $dbw->affectedRows() > 0 ) {
1227 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1228 $this->mId
= $newid;
1229 $this->mTitle
->resetArticleID( $newid );
1233 return false; // nothing changed
1238 * Update the page record to point to a newly saved revision.
1240 * @param IDatabase $dbw
1241 * @param Revision $revision For ID number, and text used to set
1242 * length and redirect status fields
1243 * @param int $lastRevision If given, will not overwrite the page field
1244 * when different from the currently set value.
1245 * Giving 0 indicates the new page flag should be set on.
1246 * @param bool $lastRevIsRedirect If given, will optimize adding and
1247 * removing rows in redirect table.
1248 * @return bool Success; false if the page row was missing or page_latest changed
1250 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1251 $lastRevIsRedirect = null
1253 global $wgContentHandlerUseDB;
1255 // Assertion to try to catch T92046
1256 if ( (int)$revision->getId() === 0 ) {
1257 throw new InvalidArgumentException(
1258 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1262 $content = $revision->getContent();
1263 $len = $content ?
$content->getSize() : 0;
1264 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1266 $conditions = [ 'page_id' => $this->getId() ];
1268 if ( !is_null( $lastRevision ) ) {
1269 // An extra check against threads stepping on each other
1270 $conditions['page_latest'] = $lastRevision;
1273 $revId = $revision->getId();
1274 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1277 'page_latest' => $revId,
1278 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1279 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1280 'page_is_redirect' => $rt !== null ?
1 : 0,
1284 if ( $wgContentHandlerUseDB ) {
1285 $row['page_content_model'] = $revision->getContentModel();
1288 $dbw->update( 'page',
1293 $result = $dbw->affectedRows() > 0;
1295 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1296 $this->setLastEdit( $revision );
1297 $this->mLatest
= $revision->getId();
1298 $this->mIsRedirect
= (bool)$rt;
1299 // Update the LinkCache.
1300 LinkCache
::singleton()->addGoodLinkObj(
1306 $revision->getContentModel()
1314 * Add row to the redirect table if this is a redirect, remove otherwise.
1316 * @param IDatabase $dbw
1317 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1318 * or NULL if this is not a redirect
1319 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1320 * removing rows in redirect table.
1321 * @return bool True on success, false on failure
1324 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1325 // Always update redirects (target link might have changed)
1326 // Update/Insert if we don't know if the last revision was a redirect or not
1327 // Delete if changing from redirect to non-redirect
1328 $isRedirect = !is_null( $redirectTitle );
1330 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1334 if ( $isRedirect ) {
1335 $this->insertRedirectEntry( $redirectTitle );
1337 // This is not a redirect, remove row from redirect table
1338 $where = [ 'rd_from' => $this->getId() ];
1339 $dbw->delete( 'redirect', $where, __METHOD__
);
1342 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1343 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1346 return ( $dbw->affectedRows() != 0 );
1350 * If the given revision is newer than the currently set page_latest,
1351 * update the page record. Otherwise, do nothing.
1353 * @deprecated since 1.24, use updateRevisionOn instead
1355 * @param IDatabase $dbw
1356 * @param Revision $revision
1359 public function updateIfNewerOn( $dbw, $revision ) {
1360 $row = $dbw->selectRow(
1361 [ 'revision', 'page' ],
1362 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1364 'page_id' => $this->getId(),
1365 'page_latest=rev_id' ],
1369 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1372 $prev = $row->rev_id
;
1373 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1375 // No or missing previous revision; mark the page as new
1377 $lastRevIsRedirect = null;
1380 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1386 * Get the content that needs to be saved in order to undo all revisions
1387 * between $undo and $undoafter. Revisions must belong to the same page,
1388 * must exist and must not be deleted
1389 * @param Revision $undo
1390 * @param Revision $undoafter Must be an earlier revision than $undo
1391 * @return Content|bool Content on success, false on failure
1393 * Before we had the Content object, this was done in getUndoText
1395 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1396 $handler = $undo->getContentHandler();
1397 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1401 * Returns true if this page's content model supports sections.
1405 * @todo The skin should check this and not offer section functionality if
1406 * sections are not supported.
1407 * @todo The EditPage should check this and not offer section functionality
1408 * if sections are not supported.
1410 public function supportsSections() {
1411 return $this->getContentHandler()->supportsSections();
1415 * @param string|int|null|bool $sectionId Section identifier as a number or string
1416 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1417 * or 'new' for a new section.
1418 * @param Content $sectionContent New content of the section.
1419 * @param string $sectionTitle New section's subject, only if $section is "new".
1420 * @param string $edittime Revision timestamp or null to use the current revision.
1422 * @throws MWException
1423 * @return Content|null New complete article content, or null if error.
1426 * @deprecated since 1.24, use replaceSectionAtRev instead
1428 public function replaceSectionContent(
1429 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1432 if ( $edittime && $sectionId !== 'new' ) {
1433 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1434 $dbr = $lb->getConnection( DB_REPLICA
);
1435 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1436 // Try the master if this thread may have just added it.
1437 // This could be abstracted into a Revision method, but we don't want
1438 // to encourage loading of revisions by timestamp.
1440 && $lb->getServerCount() > 1
1441 && $lb->hasOrMadeRecentMasterChanges()
1443 $dbw = $lb->getConnection( DB_MASTER
);
1444 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1447 $baseRevId = $rev->getId();
1451 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1455 * @param string|int|null|bool $sectionId Section identifier as a number or string
1456 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1457 * or 'new' for a new section.
1458 * @param Content $sectionContent New content of the section.
1459 * @param string $sectionTitle New section's subject, only if $section is "new".
1460 * @param int|null $baseRevId
1462 * @throws MWException
1463 * @return Content|null New complete article content, or null if error.
1467 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1468 $sectionTitle = '', $baseRevId = null
1470 if ( strval( $sectionId ) === '' ) {
1471 // Whole-page edit; let the whole text through
1472 $newContent = $sectionContent;
1474 if ( !$this->supportsSections() ) {
1475 throw new MWException( "sections not supported for content model " .
1476 $this->getContentHandler()->getModelID() );
1479 // T32711: always use current version when adding a new section
1480 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1481 $oldContent = $this->getContent();
1483 $rev = Revision
::newFromId( $baseRevId );
1485 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1486 $this->getId() . "; section: $sectionId)\n" );
1490 $oldContent = $rev->getContent();
1493 if ( !$oldContent ) {
1494 wfDebug( __METHOD__
. ": no page text\n" );
1498 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1505 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1507 * @return int Updated $flags
1509 public function checkFlags( $flags ) {
1510 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1511 if ( $this->exists() ) {
1512 $flags |
= EDIT_UPDATE
;
1522 * Change an existing article or create a new article. Updates RC and all necessary caches,
1523 * optionally via the deferred update array.
1525 * @param Content $content New content
1526 * @param string $summary Edit summary
1527 * @param int $flags Bitfield:
1529 * Article is known or assumed to be non-existent, create a new one
1531 * Article is known or assumed to be pre-existing, update it
1533 * Mark this edit minor, if the user is allowed to do so
1535 * Do not log the change in recentchanges
1537 * Mark the edit a "bot" edit regardless of user rights
1539 * Fill in blank summaries with generated text where possible
1541 * Signal that the page retrieve/save cycle happened entirely in this request.
1543 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1544 * article will be detected. If EDIT_UPDATE is specified and the article
1545 * doesn't exist, the function will return an edit-gone-missing error. If
1546 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1547 * error will be returned. These two conditions are also possible with
1548 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1550 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1551 * This is not the parent revision ID, rather the revision ID for older
1552 * content used as the source for a rollback, for example.
1553 * @param User $user The user doing the edit
1554 * @param string $serialFormat Format for storing the content in the
1556 * @param array|null $tags Change tags to apply to this edit
1557 * Callers are responsible for permission checks
1558 * (with ChangeTags::canAddTagsAccompanyingChange)
1559 * @param Int $undidRevId Id of revision that was undone or 0
1561 * @throws MWException
1562 * @return Status Possible errors:
1563 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1564 * set the fatal flag of $status.
1565 * edit-gone-missing: In update mode, but the article didn't exist.
1566 * edit-conflict: In update mode, the article changed unexpectedly.
1567 * edit-no-change: Warning that the text was the same as before.
1568 * edit-already-exists: In creation mode, but the article already exists.
1570 * Extensions may define additional errors.
1572 * $return->value will contain an associative array with members as follows:
1573 * new: Boolean indicating if the function attempted to create a new article.
1574 * revision: The revision object for the inserted revision, or null.
1577 * @throws MWException
1579 public function doEditContent(
1580 Content
$content, $summary, $flags = 0, $baseRevId = false,
1581 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1583 global $wgUser, $wgUseAutomaticEditSummaries;
1585 // Old default parameter for $tags was null
1586 if ( $tags === null ) {
1590 // Low-level sanity check
1591 if ( $this->mTitle
->getText() === '' ) {
1592 throw new MWException( 'Something is trying to edit an article with an empty title' );
1594 // Make sure the given content type is allowed for this page
1595 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1596 return Status
::newFatal( 'content-not-allowed-here',
1597 ContentHandler
::getLocalizedName( $content->getModel() ),
1598 $this->mTitle
->getPrefixedText()
1602 // Load the data from the master database if needed.
1603 // The caller may already loaded it from the master or even loaded it using
1604 // SELECT FOR UPDATE, so do not override that using clear().
1605 $this->loadPageData( 'fromdbmaster' );
1607 $user = $user ?
: $wgUser;
1608 $flags = $this->checkFlags( $flags );
1610 // Avoid PHP 7.1 warning of passing $this by reference
1613 // Trigger pre-save hook (using provided edit summary)
1614 $hookStatus = Status
::newGood( [] );
1615 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1616 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1617 // Check if the hook rejected the attempted save
1618 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1619 if ( $hookStatus->isOK() ) {
1620 // Hook returned false but didn't call fatal(); use generic message
1621 $hookStatus->fatal( 'edit-hook-aborted' );
1627 $old_revision = $this->getRevision(); // current revision
1628 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1630 $handler = $content->getContentHandler();
1631 $tag = $handler->getChangeTag( $old_content, $content, $flags );
1632 // If there is no applicable tag, null is returned, so we need to check
1637 // Check for undo tag
1638 if ( $undidRevId !== 0 && in_array( 'mw-undo', ChangeTags
::getSoftwareTags() ) ) {
1639 $tags[] = 'mw-undo';
1642 // Provide autosummaries if summary is not provided and autosummaries are enabled
1643 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1644 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1647 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1648 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1654 // Get the pre-save transform content and final parser output
1655 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1656 $pstContent = $editInfo->pstContent
; // Content object
1658 'bot' => ( $flags & EDIT_FORCE_BOT
),
1659 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1660 'serialized' => $pstContent->serialize( $serialFormat ),
1661 'serialFormat' => $serialFormat,
1662 'baseRevId' => $baseRevId,
1663 'oldRevision' => $old_revision,
1664 'oldContent' => $old_content,
1665 'oldId' => $this->getLatest(),
1666 'oldIsRedirect' => $this->isRedirect(),
1667 'oldCountable' => $this->isCountable(),
1668 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1669 'undidRevId' => $undidRevId
1672 // Actually create the revision and create/update the page
1673 if ( $flags & EDIT_UPDATE
) {
1674 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1676 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1679 // Promote user to any groups they meet the criteria for
1680 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1681 $user->addAutopromoteOnceGroups( 'onEdit' );
1682 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1689 * @param Content $content Pre-save transform content
1692 * @param string $summary
1693 * @param array $meta
1695 * @throws DBUnexpectedError
1697 * @throws FatalError
1698 * @throws MWException
1700 private function doModify(
1701 Content
$content, $flags, User
$user, $summary, array $meta
1703 global $wgUseRCPatrol;
1705 // Update article, but only if changed.
1706 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1708 // Convenience variables
1709 $now = wfTimestampNow();
1710 $oldid = $meta['oldId'];
1711 /** @var Content|null $oldContent */
1712 $oldContent = $meta['oldContent'];
1713 $newsize = $content->getSize();
1716 // Article gone missing
1717 $status->fatal( 'edit-gone-missing' );
1720 } elseif ( !$oldContent ) {
1721 // Sanity check for T39225
1722 throw new MWException( "Could not find text for current revision {$oldid}." );
1725 $changed = !$content->equals( $oldContent );
1727 $dbw = wfGetDB( DB_MASTER
);
1730 // @TODO: pass content object?!
1731 $revision = new Revision( [
1732 'page' => $this->getId(),
1733 'title' => $this->mTitle
, // for determining the default content model
1734 'comment' => $summary,
1735 'minor_edit' => $meta['minor'],
1736 'text' => $meta['serialized'],
1738 'parent_id' => $oldid,
1739 'user' => $user->getId(),
1740 'user_text' => $user->getName(),
1741 'timestamp' => $now,
1742 'content_model' => $content->getModel(),
1743 'content_format' => $meta['serialFormat'],
1746 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1747 $status->merge( $prepStatus );
1748 if ( !$status->isOK() ) {
1752 $dbw->startAtomic( __METHOD__
);
1753 // Get the latest page_latest value while locking it.
1754 // Do a CAS style check to see if it's the same as when this method
1755 // started. If it changed then bail out before touching the DB.
1756 $latestNow = $this->lockAndGetLatest();
1757 if ( $latestNow != $oldid ) {
1758 $dbw->endAtomic( __METHOD__
);
1759 // Page updated or deleted in the mean time
1760 $status->fatal( 'edit-conflict' );
1765 // At this point we are now comitted to returning an OK
1766 // status unless some DB query error or other exception comes up.
1767 // This way callers don't have to call rollback() if $status is bad
1768 // unless they actually try to catch exceptions (which is rare).
1770 // Save the revision text
1771 $revisionId = $revision->insertOn( $dbw );
1772 // Update page_latest and friends to reflect the new revision
1773 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1774 throw new MWException( "Failed to update page row to use new revision." );
1777 $tags = $meta['tags'];
1778 Hooks
::run( 'NewRevisionFromEditComplete',
1779 [ $this, $revision, $meta['baseRevId'], $user, &$tags ] );
1781 // Update recentchanges
1782 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1783 // Mark as patrolled if the user can do so
1784 $autopatrolled = $wgUseRCPatrol && !count(
1785 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1786 // Add RC row to the DB
1787 RecentChange
::notifyEdit(
1790 $revision->isMinor(),
1794 $this->getTimestamp(),
1797 $oldContent ?
$oldContent->getSize() : 0,
1800 $autopatrolled ? RecentChange
::PRC_AUTOPATROLLED
:
1801 RecentChange
::PRC_UNPATROLLED
,
1806 $user->incEditCount();
1808 $dbw->endAtomic( __METHOD__
);
1809 $this->mTimestamp
= $now;
1811 // T34948: revision ID must be set to page {{REVISIONID}} and
1812 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1813 // Since we don't insert a new revision into the database, the least
1814 // error-prone way is to reuse given old revision.
1815 $revision = $meta['oldRevision'];
1819 // Return the new revision to the caller
1820 $status->value
['revision'] = $revision;
1822 $status->warning( 'edit-no-change' );
1823 // Update page_touched as updateRevisionOn() was not called.
1824 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1825 $this->mTitle
->invalidateCache( $now );
1828 // Do secondary updates once the main changes have been committed...
1829 DeferredUpdates
::addUpdate(
1830 new AtomicSectionUpdate(
1834 $revision, &$user, $content, $summary, &$flags,
1835 $changed, $meta, &$status
1837 // Update links tables, site stats, etc.
1838 $this->doEditUpdates(
1842 'changed' => $changed,
1843 'oldcountable' => $meta['oldCountable'],
1844 'oldrevision' => $meta['oldRevision']
1847 // Avoid PHP 7.1 warning of passing $this by reference
1849 // Trigger post-save hook
1850 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1851 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1852 $meta['undidRevId'] ];
1853 Hooks
::run( 'PageContentSaveComplete', $params );
1856 DeferredUpdates
::PRESEND
1863 * @param Content $content Pre-save transform content
1866 * @param string $summary
1867 * @param array $meta
1869 * @throws DBUnexpectedError
1871 * @throws FatalError
1872 * @throws MWException
1874 private function doCreate(
1875 Content
$content, $flags, User
$user, $summary, array $meta
1877 global $wgUseRCPatrol, $wgUseNPPatrol;
1879 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1881 $now = wfTimestampNow();
1882 $newsize = $content->getSize();
1883 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1884 $status->merge( $prepStatus );
1885 if ( !$status->isOK() ) {
1889 $dbw = wfGetDB( DB_MASTER
);
1890 $dbw->startAtomic( __METHOD__
);
1892 // Add the page record unless one already exists for the title
1893 $newid = $this->insertOn( $dbw );
1894 if ( $newid === false ) {
1895 $dbw->endAtomic( __METHOD__
); // nothing inserted
1896 $status->fatal( 'edit-already-exists' );
1898 return $status; // nothing done
1901 // At this point we are now comitted to returning an OK
1902 // status unless some DB query error or other exception comes up.
1903 // This way callers don't have to call rollback() if $status is bad
1904 // unless they actually try to catch exceptions (which is rare).
1906 // @TODO: pass content object?!
1907 $revision = new Revision( [
1909 'title' => $this->mTitle
, // for determining the default content model
1910 'comment' => $summary,
1911 'minor_edit' => $meta['minor'],
1912 'text' => $meta['serialized'],
1914 'user' => $user->getId(),
1915 'user_text' => $user->getName(),
1916 'timestamp' => $now,
1917 'content_model' => $content->getModel(),
1918 'content_format' => $meta['serialFormat'],
1921 // Save the revision text...
1922 $revisionId = $revision->insertOn( $dbw );
1923 // Update the page record with revision data
1924 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1925 throw new MWException( "Failed to update page row to use new revision." );
1928 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1930 // Update recentchanges
1931 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1932 // Mark as patrolled if the user can do so
1933 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1934 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1935 // Add RC row to the DB
1936 RecentChange
::notifyNew(
1939 $revision->isMinor(),
1951 $user->incEditCount();
1953 $dbw->endAtomic( __METHOD__
);
1954 $this->mTimestamp
= $now;
1956 // Return the new revision to the caller
1957 $status->value
['revision'] = $revision;
1959 // Do secondary updates once the main changes have been committed...
1960 DeferredUpdates
::addUpdate(
1961 new AtomicSectionUpdate(
1965 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1967 // Update links, etc.
1968 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1969 // Avoid PHP 7.1 warning of passing $this by reference
1971 // Trigger post-create hook
1972 $params = [ &$wikiPage, &$user, $content, $summary,
1973 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1974 Hooks
::run( 'PageContentInsertComplete', $params );
1975 // Trigger post-save hook
1976 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1977 Hooks
::run( 'PageContentSaveComplete', $params );
1980 DeferredUpdates
::PRESEND
1987 * Get parser options suitable for rendering the primary article wikitext
1989 * @see ContentHandler::makeParserOptions
1991 * @param IContextSource|User|string $context One of the following:
1992 * - IContextSource: Use the User and the Language of the provided
1994 * - User: Use the provided User object and $wgLang for the language,
1995 * so use an IContextSource object if possible.
1996 * - 'canonical': Canonical options (anonymous user with default
1997 * preferences and content language).
1998 * @return ParserOptions
2000 public function makeParserOptions( $context ) {
2001 $options = $this->getContentHandler()->makeParserOptions( $context );
2003 if ( $this->getTitle()->isConversionTable() ) {
2004 // @todo ConversionTable should become a separate content model, so
2005 // we don't need special cases like this one.
2006 $options->disableContentConversion();
2013 * Prepare content which is about to be saved.
2015 * Prior to 1.30, this returned a stdClass object with the same class
2018 * @param Content $content
2019 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2020 * revision ID is also accepted, but this is deprecated.
2021 * @param User|null $user
2022 * @param string|null $serialFormat
2023 * @param bool $useCache Check shared prepared edit cache
2025 * @return PreparedEdit
2029 public function prepareContentForEdit(
2030 Content
$content, $revision = null, User
$user = null,
2031 $serialFormat = null, $useCache = true
2033 global $wgContLang, $wgUser, $wgAjaxEditStash;
2035 if ( is_object( $revision ) ) {
2036 $revid = $revision->getId();
2039 // This code path is deprecated, and nothing is known to
2040 // use it, so performance here shouldn't be a worry.
2041 if ( $revid !== null ) {
2042 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
2043 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2049 $user = is_null( $user ) ?
$wgUser : $user;
2050 // XXX: check $user->getId() here???
2052 // Use a sane default for $serialFormat, see T59026
2053 if ( $serialFormat === null ) {
2054 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2057 if ( $this->mPreparedEdit
2058 && isset( $this->mPreparedEdit
->newContent
)
2059 && $this->mPreparedEdit
->newContent
->equals( $content )
2060 && $this->mPreparedEdit
->revid
== $revid
2061 && $this->mPreparedEdit
->format
== $serialFormat
2062 // XXX: also check $user here?
2065 return $this->mPreparedEdit
;
2068 // The edit may have already been prepared via api.php?action=stashedit
2069 $cachedEdit = $useCache && $wgAjaxEditStash
2070 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2073 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2074 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2076 $edit = new PreparedEdit();
2077 if ( $cachedEdit ) {
2078 $edit->timestamp
= $cachedEdit->timestamp
;
2080 $edit->timestamp
= wfTimestampNow();
2082 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2083 $edit->revid
= $revid;
2085 if ( $cachedEdit ) {
2086 $edit->pstContent
= $cachedEdit->pstContent
;
2088 $edit->pstContent
= $content
2089 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2093 $edit->format
= $serialFormat;
2094 $edit->popts
= $this->makeParserOptions( 'canonical' );
2095 if ( $cachedEdit ) {
2096 $edit->output
= $cachedEdit->output
;
2099 // We get here if vary-revision is set. This means that this page references
2100 // itself (such as via self-transclusion). In this case, we need to make sure
2101 // that any such self-references refer to the newly-saved revision, and not
2102 // to the previous one, which could otherwise happen due to replica DB lag.
2103 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2104 $edit->popts
->setCurrentRevisionCallback(
2105 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2106 if ( $title->equals( $revision->getTitle() ) ) {
2109 return call_user_func( $oldCallback, $title, $parser );
2114 // Try to avoid a second parse if {{REVISIONID}} is used
2115 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2116 ? DB_MASTER
// use the best possible guess
2117 : DB_REPLICA
; // T154554
2119 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2120 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2121 // Use a fresh connection in order to see the latest data, by avoiding
2122 // stale data from REPEATABLE-READ snapshots.
2123 $db = $lb->getConnectionRef( $dbIndex, [], false, $lb::CONN_TRX_AUTO
);
2125 return 1 +
(int)$db->selectField(
2133 $edit->output
= $edit->pstContent
2134 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2138 $edit->newContent
= $content;
2139 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2141 if ( $edit->output
) {
2142 $edit->output
->setCacheTime( wfTimestampNow() );
2145 // Process cache the result
2146 $this->mPreparedEdit
= $edit;
2152 * Do standard deferred updates after page edit.
2153 * Update links tables, site stats, search index and message cache.
2154 * Purges pages that include this page if the text was changed here.
2155 * Every 100th edit, prune the recent changes table.
2157 * @param Revision $revision
2158 * @param User $user User object that did the revision
2159 * @param array $options Array of options, following indexes are used:
2160 * - changed: bool, whether the revision changed the content (default true)
2161 * - created: bool, whether the revision created the page (default false)
2162 * - moved: bool, whether the page was moved (default false)
2163 * - restored: bool, whether the page was undeleted (default false)
2164 * - oldrevision: Revision object for the pre-update revision (default null)
2165 * - oldcountable: bool, null, or string 'no-change' (default null):
2166 * - bool: whether the page was counted as an article before that
2167 * revision, only used in changed is true and created is false
2168 * - null: if created is false, don't update the article count; if created
2169 * is true, do update the article count
2170 * - 'no-change': don't update the article count, ever
2172 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2173 global $wgRCWatchCategoryMembership;
2179 'restored' => false,
2180 'oldrevision' => null,
2181 'oldcountable' => null
2183 $content = $revision->getContent();
2185 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2187 // See if the parser output before $revision was inserted is still valid
2189 if ( !$this->mPreparedEdit
) {
2190 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2191 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2192 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2193 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2194 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2196 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2197 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2198 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2200 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2201 $editInfo = $this->mPreparedEdit
;
2205 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2206 // $text is usually already pre-save transformed once. Avoid using the edit stash
2207 // as any prepared content from there or in doEditContent() was already rejected.
2208 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2211 // Save it to the parser cache.
2212 // Make sure the cache time matches page_touched to avoid double parsing.
2213 MediaWikiServices
::getInstance()->getParserCache()->save(
2214 $editInfo->output
, $this, $editInfo->popts
,
2215 $revision->getTimestamp(), $editInfo->revid
2218 // Update the links tables and other secondary data
2220 $recursive = $options['changed']; // T52785
2221 $updates = $content->getSecondaryDataUpdates(
2222 $this->getTitle(), null, $recursive, $editInfo->output
2224 foreach ( $updates as $update ) {
2225 $update->setCause( 'edit-page', $user->getName() );
2226 if ( $update instanceof LinksUpdate
) {
2227 $update->setRevision( $revision );
2228 $update->setTriggeringUser( $user );
2230 DeferredUpdates
::addUpdate( $update );
2232 if ( $wgRCWatchCategoryMembership
2233 && $this->getContentHandler()->supportsCategories() === true
2234 && ( $options['changed'] ||
$options['created'] )
2235 && !$options['restored']
2237 // Note: jobs are pushed after deferred updates, so the job should be able to see
2238 // the recent change entry (also done via deferred updates) and carry over any
2239 // bot/deletion/IP flags, ect.
2240 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2243 'pageId' => $this->getId(),
2244 'revTimestamp' => $revision->getTimestamp()
2250 // Avoid PHP 7.1 warning of passing $this by reference
2253 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2255 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2256 // Flush old entries from the `recentchanges` table
2257 if ( mt_rand( 0, 9 ) == 0 ) {
2258 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2262 if ( !$this->exists() ) {
2266 $id = $this->getId();
2267 $title = $this->mTitle
->getPrefixedDBkey();
2268 $shortTitle = $this->mTitle
->getDBkey();
2270 if ( $options['oldcountable'] === 'no-change' ||
2271 ( !$options['changed'] && !$options['moved'] )
2274 } elseif ( $options['created'] ) {
2275 $good = (int)$this->isCountable( $editInfo );
2276 } elseif ( $options['oldcountable'] !== null ) {
2277 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2281 $edits = $options['changed'] ?
1 : 0;
2282 $pages = $options['created'] ?
1 : 0;
2284 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2285 [ 'edits' => $edits, 'articles' => $good, 'pages' => $pages ]
2287 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2289 // If this is another user's talk page, update newtalk.
2290 // Don't do this if $options['changed'] = false (null-edits) nor if
2291 // it's a minor edit and the user doesn't want notifications for those.
2292 if ( $options['changed']
2293 && $this->mTitle
->getNamespace() == NS_USER_TALK
2294 && $shortTitle != $user->getTitleKey()
2295 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2297 $recipient = User
::newFromName( $shortTitle, false );
2298 if ( !$recipient ) {
2299 wfDebug( __METHOD__
. ": invalid username\n" );
2301 // Avoid PHP 7.1 warning of passing $this by reference
2304 // Allow extensions to prevent user notification
2305 // when a new message is added to their talk page
2306 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2307 if ( User
::isIP( $shortTitle ) ) {
2308 // An anonymous user
2309 $recipient->setNewtalk( true, $revision );
2310 } elseif ( $recipient->isLoggedIn() ) {
2311 $recipient->setNewtalk( true, $revision );
2313 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2319 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2320 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2323 if ( $options['created'] ) {
2324 self
::onArticleCreate( $this->mTitle
);
2325 } elseif ( $options['changed'] ) { // T52785
2326 self
::onArticleEdit( $this->mTitle
, $revision );
2329 ResourceLoaderWikiModule
::invalidateModuleCache(
2330 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2335 * Update the article's restriction field, and leave a log entry.
2336 * This works for protection both existing and non-existing pages.
2338 * @param array $limit Set of restriction keys
2339 * @param array $expiry Per restriction type expiration
2340 * @param int &$cascade Set to false if cascading protection isn't allowed.
2341 * @param string $reason
2342 * @param User $user The user updating the restrictions
2343 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2344 * ($user should be able to add the specified tags before this is called)
2345 * @return Status Status object; if action is taken, $status->value is the log_id of the
2346 * protection log entry.
2348 public function doUpdateRestrictions( array $limit, array $expiry,
2349 &$cascade, $reason, User
$user, $tags = null
2351 global $wgCascadingRestrictionLevels;
2353 if ( wfReadOnly() ) {
2354 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2357 $this->loadPageData( 'fromdbmaster' );
2358 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2359 $id = $this->getId();
2365 // Take this opportunity to purge out expired restrictions
2366 Title
::purgeExpiredRestrictions();
2368 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2369 // we expect a single selection, but the schema allows otherwise.
2370 $isProtected = false;
2374 $dbw = wfGetDB( DB_MASTER
);
2376 foreach ( $restrictionTypes as $action ) {
2377 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2378 $expiry[$action] = 'infinity';
2380 if ( !isset( $limit[$action] ) ) {
2381 $limit[$action] = '';
2382 } elseif ( $limit[$action] != '' ) {
2386 // Get current restrictions on $action
2387 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2388 if ( $current != '' ) {
2389 $isProtected = true;
2392 if ( $limit[$action] != $current ) {
2394 } elseif ( $limit[$action] != '' ) {
2395 // Only check expiry change if the action is actually being
2396 // protected, since expiry does nothing on an not-protected
2398 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2404 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2408 // If nothing has changed, do nothing
2410 return Status
::newGood();
2413 if ( !$protect ) { // No protection at all means unprotection
2414 $revCommentMsg = 'unprotectedarticle-comment';
2415 $logAction = 'unprotect';
2416 } elseif ( $isProtected ) {
2417 $revCommentMsg = 'modifiedarticleprotection-comment';
2418 $logAction = 'modify';
2420 $revCommentMsg = 'protectedarticle-comment';
2421 $logAction = 'protect';
2424 $logRelationsValues = [];
2425 $logRelationsField = null;
2426 $logParamsDetails = [];
2428 // Null revision (used for change tag insertion)
2429 $nullRevision = null;
2431 if ( $id ) { // Protection of existing page
2432 // Avoid PHP 7.1 warning of passing $this by reference
2435 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2436 return Status
::newGood();
2439 // Only certain restrictions can cascade...
2440 $editrestriction = isset( $limit['edit'] )
2441 ?
[ $limit['edit'] ]
2442 : $this->mTitle
->getRestrictions( 'edit' );
2443 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2444 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2446 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2447 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2450 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2451 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2452 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2454 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2455 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2458 // The schema allows multiple restrictions
2459 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2463 // insert null revision to identify the page protection change as edit summary
2464 $latest = $this->getLatest();
2465 $nullRevision = $this->insertProtectNullRevision(
2474 if ( $nullRevision === null ) {
2475 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2478 $logRelationsField = 'pr_id';
2480 // Update restrictions table
2481 foreach ( $limit as $action => $restrictions ) {
2483 'page_restrictions',
2486 'pr_type' => $action
2490 if ( $restrictions != '' ) {
2491 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2493 'page_restrictions',
2496 'pr_type' => $action,
2497 'pr_level' => $restrictions,
2498 'pr_cascade' => $cascadeValue,
2499 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2503 $logRelationsValues[] = $dbw->insertId();
2504 $logParamsDetails[] = [
2506 'level' => $restrictions,
2507 'expiry' => $expiry[$action],
2508 'cascade' => (bool)$cascadeValue,
2513 // Clear out legacy restriction fields
2516 [ 'page_restrictions' => '' ],
2517 [ 'page_id' => $id ],
2521 // Avoid PHP 7.1 warning of passing $this by reference
2524 Hooks
::run( 'NewRevisionFromEditComplete',
2525 [ $this, $nullRevision, $latest, $user ] );
2526 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2527 } else { // Protection of non-existing page (also known as "title protection")
2528 // Cascade protection is meaningless in this case
2531 if ( $limit['create'] != '' ) {
2532 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2533 $dbw->replace( 'protected_titles',
2534 [ [ 'pt_namespace', 'pt_title' ] ],
2536 'pt_namespace' => $this->mTitle
->getNamespace(),
2537 'pt_title' => $this->mTitle
->getDBkey(),
2538 'pt_create_perm' => $limit['create'],
2539 'pt_timestamp' => $dbw->timestamp(),
2540 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2541 'pt_user' => $user->getId(),
2542 ] +
$commentFields, __METHOD__
2544 $logParamsDetails[] = [
2546 'level' => $limit['create'],
2547 'expiry' => $expiry['create'],
2550 $dbw->delete( 'protected_titles',
2552 'pt_namespace' => $this->mTitle
->getNamespace(),
2553 'pt_title' => $this->mTitle
->getDBkey()
2559 $this->mTitle
->flushRestrictions();
2560 InfoAction
::invalidateCache( $this->mTitle
);
2562 if ( $logAction == 'unprotect' ) {
2565 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2567 '4::description' => $protectDescriptionLog, // parameter for IRC
2568 '5:bool:cascade' => $cascade,
2569 'details' => $logParamsDetails, // parameter for localize and api
2573 // Update the protection log
2574 $logEntry = new ManualLogEntry( 'protect', $logAction );
2575 $logEntry->setTarget( $this->mTitle
);
2576 $logEntry->setComment( $reason );
2577 $logEntry->setPerformer( $user );
2578 $logEntry->setParameters( $params );
2579 if ( !is_null( $nullRevision ) ) {
2580 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2582 $logEntry->setTags( $tags );
2583 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2584 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2586 $logId = $logEntry->insert();
2587 $logEntry->publish( $logId );
2589 return Status
::newGood( $logId );
2593 * Insert a new null revision for this page.
2595 * @param string $revCommentMsg Comment message key for the revision
2596 * @param array $limit Set of restriction keys
2597 * @param array $expiry Per restriction type expiration
2598 * @param int $cascade Set to false if cascading protection isn't allowed.
2599 * @param string $reason
2600 * @param User|null $user
2601 * @return Revision|null Null on error
2603 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2604 array $expiry, $cascade, $reason, $user = null
2606 $dbw = wfGetDB( DB_MASTER
);
2608 // Prepare a null revision to be added to the history
2609 $editComment = wfMessage(
2611 $this->mTitle
->getPrefixedText(),
2612 $user ?
$user->getName() : ''
2613 )->inContentLanguage()->text();
2615 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2617 $protectDescription = $this->protectDescription( $limit, $expiry );
2618 if ( $protectDescription ) {
2619 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2620 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2621 ->inContentLanguage()->text();
2624 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2625 $editComment .= wfMessage( 'brackets' )->params(
2626 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2627 )->inContentLanguage()->text();
2630 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2632 $nullRev->insertOn( $dbw );
2634 // Update page record and touch page
2635 $oldLatest = $nullRev->getParentId();
2636 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2643 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2646 protected function formatExpiry( $expiry ) {
2649 if ( $expiry != 'infinity' ) {
2652 $wgContLang->timeanddate( $expiry, false, false ),
2653 $wgContLang->date( $expiry, false, false ),
2654 $wgContLang->time( $expiry, false, false )
2655 )->inContentLanguage()->text();
2657 return wfMessage( 'protect-expiry-indefinite' )
2658 ->inContentLanguage()->text();
2663 * Builds the description to serve as comment for the edit.
2665 * @param array $limit Set of restriction keys
2666 * @param array $expiry Per restriction type expiration
2669 public function protectDescription( array $limit, array $expiry ) {
2670 $protectDescription = '';
2672 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2673 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2674 # All possible message keys are listed here for easier grepping:
2675 # * restriction-create
2676 # * restriction-edit
2677 # * restriction-move
2678 # * restriction-upload
2679 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2680 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2681 # with '' filtered out. All possible message keys are listed below:
2682 # * protect-level-autoconfirmed
2683 # * protect-level-sysop
2684 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2685 ->inContentLanguage()->text();
2687 $expiryText = $this->formatExpiry( $expiry[$action] );
2689 if ( $protectDescription !== '' ) {
2690 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2692 $protectDescription .= wfMessage( 'protect-summary-desc' )
2693 ->params( $actionText, $restrictionsText, $expiryText )
2694 ->inContentLanguage()->text();
2697 return $protectDescription;
2701 * Builds the description to serve as comment for the log entry.
2703 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2704 * protect description text. Keep them in old format to avoid breaking compatibility.
2705 * TODO: Fix protection log to store structured description and format it on-the-fly.
2707 * @param array $limit Set of restriction keys
2708 * @param array $expiry Per restriction type expiration
2711 public function protectDescriptionLog( array $limit, array $expiry ) {
2714 $protectDescriptionLog = '';
2716 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2717 $expiryText = $this->formatExpiry( $expiry[$action] );
2718 $protectDescriptionLog .= $wgContLang->getDirMark() .
2719 "[$action=$restrictions] ($expiryText)";
2722 return trim( $protectDescriptionLog );
2726 * Take an array of page restrictions and flatten it to a string
2727 * suitable for insertion into the page_restrictions field.
2729 * @param string[] $limit
2731 * @throws MWException
2734 protected static function flattenRestrictions( $limit ) {
2735 if ( !is_array( $limit ) ) {
2736 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2742 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2743 $bits[] = "$action=$restrictions";
2746 return implode( ':', $bits );
2750 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2751 * backwards compatibility, if you care about error reporting you should use
2752 * doDeleteArticleReal() instead.
2754 * Deletes the article with database consistency, writes logs, purges caches
2756 * @param string $reason Delete reason for deletion log
2757 * @param bool $suppress Suppress all revisions and log the deletion in
2758 * the suppression log instead of the deletion log
2759 * @param int $u1 Unused
2760 * @param bool $u2 Unused
2761 * @param array|string &$error Array of errors to append to
2762 * @param User $user The deleting user
2763 * @return bool True if successful
2765 public function doDeleteArticle(
2766 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2768 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2769 return $status->isGood();
2773 * Back-end article deletion
2774 * Deletes the article with database consistency, writes logs, purges caches
2778 * @param string $reason Delete reason for deletion log
2779 * @param bool $suppress Suppress all revisions and log the deletion in
2780 * the suppression log instead of the deletion log
2781 * @param int $u1 Unused
2782 * @param bool $u2 Unused
2783 * @param array|string &$error Array of errors to append to
2784 * @param User $deleter The deleting user
2785 * @param array $tags Tags to apply to the deletion action
2786 * @param string $logsubtype
2787 * @return Status Status object; if successful, $status->value is the log_id of the
2788 * deletion log entry. If the page couldn't be deleted because it wasn't
2789 * found, $status is a non-fatal 'cannotdelete' error
2791 public function doDeleteArticleReal(
2792 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2793 $tags = [], $logsubtype = 'delete'
2795 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage,
2796 $wgActorTableSchemaMigrationStage;
2798 wfDebug( __METHOD__
. "\n" );
2800 $status = Status
::newGood();
2802 if ( $this->mTitle
->getDBkey() === '' ) {
2803 $status->error( 'cannotdelete',
2804 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2808 // Avoid PHP 7.1 warning of passing $this by reference
2811 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2812 if ( !Hooks
::run( 'ArticleDelete',
2813 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2815 if ( $status->isOK() ) {
2816 // Hook aborted but didn't set a fatal status
2817 $status->fatal( 'delete-hook-aborted' );
2822 $dbw = wfGetDB( DB_MASTER
);
2823 $dbw->startAtomic( __METHOD__
);
2825 $this->loadPageData( self
::READ_LATEST
);
2826 $id = $this->getId();
2827 // T98706: lock the page from various other updates but avoid using
2828 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2829 // the revisions queries (which also JOIN on user). Only lock the page
2830 // row and CAS check on page_latest to see if the trx snapshot matches.
2831 $lockedLatest = $this->lockAndGetLatest();
2832 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2833 $dbw->endAtomic( __METHOD__
);
2834 // Page not there or trx snapshot is stale
2835 $status->error( 'cannotdelete',
2836 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2840 // Given the lock above, we can be confident in the title and page ID values
2841 $namespace = $this->getTitle()->getNamespace();
2842 $dbKey = $this->getTitle()->getDBkey();
2844 // At this point we are now comitted to returning an OK
2845 // status unless some DB query error or other exception comes up.
2846 // This way callers don't have to call rollback() if $status is bad
2847 // unless they actually try to catch exceptions (which is rare).
2849 // we need to remember the old content so we can use it to generate all deletion updates.
2850 $revision = $this->getRevision();
2852 $content = $this->getContent( Revision
::RAW
);
2853 } catch ( Exception
$ex ) {
2854 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2855 . $ex->getMessage() );
2860 $commentStore = CommentStore
::getStore();
2861 $actorMigration = ActorMigration
::newMigration();
2863 $revQuery = Revision
::getQueryInfo();
2866 // Bitfields to further suppress the content
2868 $bitfield = Revision
::SUPPRESSED_ALL
;
2869 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2872 // For now, shunt the revision data into the archive table.
2873 // Text is *not* removed from the text table; bulk storage
2874 // is left intact to avoid breaking block-compression or
2875 // immutable storage schemes.
2876 // In the future, we may keep revisions and mark them with
2877 // the rev_deleted field, which is reserved for this purpose.
2879 // Lock rows in `revision` and its temp tables, but not any others.
2880 // Note array_intersect() preserves keys from the first arg, and we're
2881 // assuming $revQuery has `revision` primary and isn't using subtables
2882 // for anything we care about.
2883 $res = $dbw->select(
2885 $revQuery['tables'],
2886 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2889 [ 'rev_page' => $id ],
2894 foreach ( $res as $row ) {
2895 // Fetch all rows in case the DB needs that to properly lock them.
2898 // Get all of the page revisions
2899 $res = $dbw->select(
2900 $revQuery['tables'],
2901 $revQuery['fields'],
2902 [ 'rev_page' => $id ],
2908 // Build their equivalent archive rows
2912 /** @var int[] Revision IDs of edits that were made by IPs */
2915 foreach ( $res as $row ) {
2916 $comment = $commentStore->getComment( 'rev_comment', $row );
2917 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2919 'ar_namespace' => $namespace,
2920 'ar_title' => $dbKey,
2921 'ar_timestamp' => $row->rev_timestamp
,
2922 'ar_minor_edit' => $row->rev_minor_edit
,
2923 'ar_rev_id' => $row->rev_id
,
2924 'ar_parent_id' => $row->rev_parent_id
,
2925 'ar_text_id' => $row->rev_text_id
,
2926 'ar_len' => $row->rev_len
,
2927 'ar_page_id' => $id,
2928 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2929 'ar_sha1' => $row->rev_sha1
,
2930 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2931 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2932 if ( $wgContentHandlerUseDB ) {
2933 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2934 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2936 $rowsInsert[] = $rowInsert;
2937 $revids[] = $row->rev_id
;
2939 // Keep track of IP edits, so that the corresponding rows can
2940 // be deleted in the ip_changes table.
2941 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2942 $ipRevIds[] = $row->rev_id
;
2945 // Copy them into the archive table
2946 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2947 // Save this so we can pass it to the ArticleDeleteComplete hook.
2948 $archivedRevisionCount = $dbw->affectedRows();
2950 // Clone the title and wikiPage, so we have the information we need when
2951 // we log and run the ArticleDeleteComplete hook.
2952 $logTitle = clone $this->mTitle
;
2953 $wikiPageBeforeDelete = clone $this;
2955 // Now that it's safely backed up, delete it
2956 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2957 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2958 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2959 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2961 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
2962 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2965 // Also delete records from ip_changes as applicable.
2966 if ( count( $ipRevIds ) > 0 ) {
2967 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2970 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2971 $logtype = $suppress ?
'suppress' : 'delete';
2973 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2974 $logEntry->setPerformer( $deleter );
2975 $logEntry->setTarget( $logTitle );
2976 $logEntry->setComment( $reason );
2977 $logEntry->setTags( $tags );
2978 $logid = $logEntry->insert();
2980 $dbw->onTransactionPreCommitOrIdle(
2981 function () use ( $logEntry, $logid ) {
2982 // T58776: avoid deadlocks (especially from FileDeleteForm)
2983 $logEntry->publish( $logid );
2988 $dbw->endAtomic( __METHOD__
);
2990 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2992 Hooks
::run( 'ArticleDeleteComplete', [
2993 &$wikiPageBeforeDelete,
2999 $archivedRevisionCount
3001 $status->value
= $logid;
3003 // Show log excerpt on 404 pages rather than just a link
3004 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
3005 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
3006 $cache->set( $key, 1, $cache::TTL_DAY
);
3012 * Lock the page row for this title+id and return page_latest (or 0)
3014 * @return int Returns 0 if no row was found with this title+id
3017 public function lockAndGetLatest() {
3018 return (int)wfGetDB( DB_MASTER
)->selectField(
3022 'page_id' => $this->getId(),
3023 // Typically page_id is enough, but some code might try to do
3024 // updates assuming the title is the same, so verify that
3025 'page_namespace' => $this->getTitle()->getNamespace(),
3026 'page_title' => $this->getTitle()->getDBkey()
3034 * Do some database updates after deletion
3036 * @param int $id The page_id value of the page being deleted
3037 * @param Content|null $content Optional page content to be used when determining
3038 * the required updates. This may be needed because $this->getContent()
3039 * may already return null when the page proper was deleted.
3040 * @param Revision|null $revision The latest page revision
3041 * @param User|null $user The user that caused the deletion
3043 public function doDeleteUpdates(
3044 $id, Content
$content = null, Revision
$revision = null, User
$user = null
3047 $countable = $this->isCountable();
3048 } catch ( Exception
$ex ) {
3049 // fallback for deleting broken pages for which we cannot load the content for
3050 // some reason. Note that doDeleteArticleReal() already logged this problem.
3054 // Update site status
3055 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
3056 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
3059 // Delete pagelinks, update secondary indexes, etc
3060 $updates = $this->getDeletionUpdates( $content );
3061 foreach ( $updates as $update ) {
3062 DeferredUpdates
::addUpdate( $update );
3065 $causeAgent = $user ?
$user->getName() : 'unknown';
3066 // Reparse any pages transcluding this page
3067 LinksUpdate
::queueRecursiveJobsForTable(
3068 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3069 // Reparse any pages including this image
3070 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3071 LinksUpdate
::queueRecursiveJobsForTable(
3072 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3076 self
::onArticleDelete( $this->mTitle
);
3077 ResourceLoaderWikiModule
::invalidateModuleCache(
3078 $this->mTitle
, $revision, null, wfWikiID()
3081 // Reset this object and the Title object
3082 $this->loadFromRow( false, self
::READ_LATEST
);
3085 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3089 * Roll back the most recent consecutive set of edits to a page
3090 * from the same user; fails if there are no eligible edits to
3091 * roll back to, e.g. user is the sole contributor. This function
3092 * performs permissions checks on $user, then calls commitRollback()
3093 * to do the dirty work
3095 * @todo Separate the business/permission stuff out from backend code
3096 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3098 * @param string $fromP Name of the user whose edits to rollback.
3099 * @param string $summary Custom summary. Set to default summary if empty.
3100 * @param string $token Rollback token.
3101 * @param bool $bot If true, mark all reverted edits as bot.
3103 * @param array &$resultDetails Array contains result-specific array of additional values
3104 * 'alreadyrolled' : 'current' (rev)
3105 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3107 * @param User $user The user performing the rollback
3108 * @param array|null $tags Change tags to apply to the rollback
3109 * Callers are responsible for permission checks
3110 * (with ChangeTags::canAddTagsAccompanyingChange)
3112 * @return array Array of errors, each error formatted as
3113 * array(messagekey, param1, param2, ...).
3114 * On success, the array is empty. This array can also be passed to
3115 * OutputPage::showPermissionsErrorPage().
3117 public function doRollback(
3118 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3120 $resultDetails = null;
3122 // Check permissions
3123 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3124 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3125 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3127 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3128 $errors[] = [ 'sessionfailure' ];
3131 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3132 $errors[] = [ 'actionthrottledtext' ];
3135 // If there were errors, bail out now
3136 if ( !empty( $errors ) ) {
3140 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3144 * Backend implementation of doRollback(), please refer there for parameter
3145 * and return value documentation
3147 * NOTE: This function does NOT check ANY permissions, it just commits the
3148 * rollback to the DB. Therefore, you should only call this function direct-
3149 * ly if you want to use custom permissions checks. If you don't, use
3150 * doRollback() instead.
3151 * @param string $fromP Name of the user whose edits to rollback.
3152 * @param string $summary Custom summary. Set to default summary if empty.
3153 * @param bool $bot If true, mark all reverted edits as bot.
3155 * @param array &$resultDetails Contains result-specific array of additional values
3156 * @param User $guser The user performing the rollback
3157 * @param array|null $tags Change tags to apply to the rollback
3158 * Callers are responsible for permission checks
3159 * (with ChangeTags::canAddTagsAccompanyingChange)
3163 public function commitRollback( $fromP, $summary, $bot,
3164 &$resultDetails, User
$guser, $tags = null
3166 global $wgUseRCPatrol, $wgContLang;
3168 $dbw = wfGetDB( DB_MASTER
);
3170 if ( wfReadOnly() ) {
3171 return [ [ 'readonlytext' ] ];
3174 // Get the last editor
3175 $current = $this->getRevision();
3176 if ( is_null( $current ) ) {
3177 // Something wrong... no page?
3178 return [ [ 'notanarticle' ] ];
3181 $from = str_replace( '_', ' ', $fromP );
3182 // User name given should match up with the top revision.
3183 // If the user was deleted then $from should be empty.
3184 if ( $from != $current->getUserText() ) {
3185 $resultDetails = [ 'current' => $current ];
3186 return [ [ 'alreadyrolled',
3187 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3188 htmlspecialchars( $fromP ),
3189 htmlspecialchars( $current->getUserText() )
3193 // Get the last edit not by this person...
3194 // Note: these may not be public values
3195 $userId = intval( $current->getUser( Revision
::RAW
) );
3196 $userName = $current->getUserText( Revision
::RAW
);
3198 $user = User
::newFromId( $userId );
3199 $user->setName( $userName );
3201 $user = User
::newFromName( $current->getUserText( Revision
::RAW
), false );
3204 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbw, 'rev_user', $user );
3206 $s = $dbw->selectRow(
3207 [ 'revision' ] +
$actorWhere['tables'],
3208 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3210 'rev_page' => $current->getPage(),
3211 'NOT(' . $actorWhere['conds'] . ')',
3215 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3216 'ORDER BY' => 'rev_timestamp DESC'
3218 $actorWhere['joins']
3220 if ( $s === false ) {
3221 // No one else ever edited this page
3222 return [ [ 'cantrollback' ] ];
3223 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3224 ||
$s->rev_deleted
& Revision
::DELETED_USER
3226 // Only admins can see this text
3227 return [ [ 'notvisiblerev' ] ];
3230 // Generate the edit summary if necessary
3231 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3232 if ( empty( $summary ) ) {
3233 if ( $from == '' ) { // no public user name
3234 $summary = wfMessage( 'revertpage-nouser' );
3236 $summary = wfMessage( 'revertpage' );
3240 // Allow the custom summary to use the same args as the default message
3242 $target->getUserText(), $from, $s->rev_id
,
3243 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3244 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3246 if ( $summary instanceof Message
) {
3247 $summary = $summary->params( $args )->inContentLanguage()->text();
3249 $summary = wfMsgReplaceArgs( $summary, $args );
3252 // Trim spaces on user supplied text
3253 $summary = trim( $summary );
3256 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3258 if ( $guser->isAllowed( 'minoredit' ) ) {
3259 $flags |
= EDIT_MINOR
;
3262 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3263 $flags |
= EDIT_FORCE_BOT
;
3266 $targetContent = $target->getContent();
3267 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3269 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3270 $tags[] = 'mw-rollback';
3273 // Actually store the edit
3274 $status = $this->doEditContent(
3284 // Set patrolling and bot flag on the edits, which gets rollbacked.
3285 // This is done even on edit failure to have patrolling in that case (T64157).
3287 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3288 // Mark all reverted edits as bot
3292 if ( $wgUseRCPatrol ) {
3293 // Mark all reverted edits as patrolled
3294 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3297 if ( count( $set ) ) {
3298 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbw, 'rc_user', $user, false );
3299 $dbw->update( 'recentchanges', $set,
3301 'rc_cur_id' => $current->getPage(),
3302 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3303 $actorWhere['conds'], // No tables/joins are needed for rc_user
3309 if ( !$status->isOK() ) {
3310 return $status->getErrorsArray();
3313 // raise error, when the edit is an edit without a new version
3314 $statusRev = $status->value
['revision'] ??
null;
3315 if ( !( $statusRev instanceof Revision
) ) {
3316 $resultDetails = [ 'current' => $current ];
3317 return [ [ 'alreadyrolled',
3318 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3319 htmlspecialchars( $fromP ),
3320 htmlspecialchars( $current->getUserText() )
3324 if ( $changingContentModel ) {
3325 // If the content model changed during the rollback,
3326 // make sure it gets logged to Special:Log/contentmodel
3327 $log = new ManualLogEntry( 'contentmodel', 'change' );
3328 $log->setPerformer( $guser );
3329 $log->setTarget( $this->mTitle
);
3330 $log->setComment( $summary );
3331 $log->setParameters( [
3332 '4::oldmodel' => $current->getContentModel(),
3333 '5::newmodel' => $targetContent->getModel(),
3336 $logId = $log->insert( $dbw );
3337 $log->publish( $logId );
3340 $revId = $statusRev->getId();
3342 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3345 'summary' => $summary,
3346 'current' => $current,
3347 'target' => $target,
3356 * The onArticle*() functions are supposed to be a kind of hooks
3357 * which should be called whenever any of the specified actions
3360 * This is a good place to put code to clear caches, for instance.
3362 * This is called on page move and undelete, as well as edit
3364 * @param Title $title
3366 public static function onArticleCreate( Title
$title ) {
3367 // Update existence markers on article/talk tabs...
3368 $other = $title->getOtherPage();
3370 $other->purgeSquid();
3372 $title->touchLinks();
3373 $title->purgeSquid();
3374 $title->deleteTitleProtection();
3376 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3378 // Invalidate caches of articles which include this page
3379 DeferredUpdates
::addUpdate(
3380 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3383 if ( $title->getNamespace() == NS_CATEGORY
) {
3384 // Load the Category object, which will schedule a job to create
3385 // the category table row if necessary. Checking a replica DB is ok
3386 // here, in the worst case it'll run an unnecessary recount job on
3387 // a category that probably doesn't have many members.
3388 Category
::newFromTitle( $title )->getID();
3393 * Clears caches when article is deleted
3395 * @param Title $title
3397 public static function onArticleDelete( Title
$title ) {
3398 // Update existence markers on article/talk tabs...
3399 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3400 BacklinkCache
::get( $title )->clear();
3401 $other = $title->getOtherPage();
3403 $other->purgeSquid();
3405 $title->touchLinks();
3406 $title->purgeSquid();
3408 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3411 HTMLFileCache
::clearFileCache( $title );
3412 InfoAction
::invalidateCache( $title );
3415 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3416 MessageCache
::singleton()->updateMessageOverride( $title, null );
3420 if ( $title->getNamespace() == NS_FILE
) {
3421 DeferredUpdates
::addUpdate(
3422 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3427 if ( $title->getNamespace() == NS_USER_TALK
) {
3428 $user = User
::newFromName( $title->getText(), false );
3430 $user->setNewtalk( false );
3435 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3439 * Purge caches on page update etc
3441 * @param Title $title
3442 * @param Revision|null $revision Revision that was just saved, may be null
3444 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3445 // Invalidate caches of articles which include this page
3446 DeferredUpdates
::addUpdate(
3447 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3450 // Invalidate the caches of all pages which redirect here
3451 DeferredUpdates
::addUpdate(
3452 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3455 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3457 // Purge CDN for this page only
3458 $title->purgeSquid();
3459 // Clear file cache for this page only
3460 HTMLFileCache
::clearFileCache( $title );
3462 $revid = $revision ?
$revision->getId() : null;
3463 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3464 InfoAction
::invalidateCache( $title, $revid );
3471 * Returns a list of categories this page is a member of.
3472 * Results will include hidden categories
3474 * @return TitleArray
3476 public function getCategories() {
3477 $id = $this->getId();
3479 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3482 $dbr = wfGetDB( DB_REPLICA
);
3483 $res = $dbr->select( 'categorylinks',
3484 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3485 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3486 // as not being aliases, and NS_CATEGORY is numeric
3487 [ 'cl_from' => $id ],
3490 return TitleArray
::newFromResult( $res );
3494 * Returns a list of hidden categories this page is a member of.
3495 * Uses the page_props and categorylinks tables.
3497 * @return array Array of Title objects
3499 public function getHiddenCategories() {
3501 $id = $this->getId();
3507 $dbr = wfGetDB( DB_REPLICA
);
3508 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3510 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3511 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3514 if ( $res !== false ) {
3515 foreach ( $res as $row ) {
3516 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3524 * Auto-generates a deletion reason
3526 * @param bool &$hasHistory Whether the page has a history
3527 * @return string|bool String containing deletion reason or empty string, or boolean false
3528 * if no revision occurred
3530 public function getAutoDeleteReason( &$hasHistory ) {
3531 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3535 * Update all the appropriate counts in the category table, given that
3536 * we've added the categories $added and deleted the categories $deleted.
3538 * This should only be called from deferred updates or jobs to avoid contention.
3540 * @param array $added The names of categories that were added
3541 * @param array $deleted The names of categories that were deleted
3542 * @param int $id Page ID (this should be the original deleted page ID)
3544 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3545 $id = $id ?
: $this->getId();
3546 $ns = $this->getTitle()->getNamespace();
3548 $addFields = [ 'cat_pages = cat_pages + 1' ];
3549 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3550 if ( $ns == NS_CATEGORY
) {
3551 $addFields[] = 'cat_subcats = cat_subcats + 1';
3552 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3553 } elseif ( $ns == NS_FILE
) {
3554 $addFields[] = 'cat_files = cat_files + 1';
3555 $removeFields[] = 'cat_files = cat_files - 1';
3558 $dbw = wfGetDB( DB_MASTER
);
3560 if ( count( $added ) ) {
3561 $existingAdded = $dbw->selectFieldValues(
3564 [ 'cat_title' => $added ],
3568 // For category rows that already exist, do a plain
3569 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3570 // to avoid creating gaps in the cat_id sequence.
3571 if ( count( $existingAdded ) ) {
3575 [ 'cat_title' => $existingAdded ],
3580 $missingAdded = array_diff( $added, $existingAdded );
3581 if ( count( $missingAdded ) ) {
3583 foreach ( $missingAdded as $cat ) {
3585 'cat_title' => $cat,
3587 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3588 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3601 if ( count( $deleted ) ) {
3605 [ 'cat_title' => $deleted ],
3610 foreach ( $added as $catName ) {
3611 $cat = Category
::newFromName( $catName );
3612 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3615 foreach ( $deleted as $catName ) {
3616 $cat = Category
::newFromName( $catName );
3617 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3620 // Refresh counts on categories that should be empty now
3621 if ( count( $deleted ) ) {
3622 $rows = $dbw->select(
3624 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3625 [ 'cat_title' => $deleted, 'cat_pages <= 100' ],
3628 foreach ( $rows as $row ) {
3629 $cat = Category
::newFromRow( $row );
3630 // T166757: do the update after this DB commit
3631 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3632 $cat->refreshCounts();
3639 * Opportunistically enqueue link update jobs given fresh parser output if useful
3641 * @param ParserOutput $parserOutput Current version page output
3644 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3645 if ( wfReadOnly() ) {
3649 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3650 [ $this, $this->mTitle
, $parserOutput ]
3655 $config = RequestContext
::getMain()->getConfig();
3658 'isOpportunistic' => true,
3659 'rootJobTimestamp' => $parserOutput->getCacheTime()
3662 if ( $this->mTitle
->areRestrictionsCascading() ) {
3663 // If the page is cascade protecting, the links should really be up-to-date
3664 JobQueueGroup
::singleton()->lazyPush(
3665 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3667 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3668 // Assume the output contains "dynamic" time/random based magic words.
3669 // Only update pages that expired due to dynamic content and NOT due to edits
3670 // to referenced templates/files. When the cache expires due to dynamic content,
3671 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3672 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3673 // template/file edit already triggered recursive RefreshLinksJob jobs.
3674 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3675 // If a page is uncacheable, do not keep spamming a job for it.
3676 // Although it would be de-duplicated, it would still waste I/O.
3677 $cache = ObjectCache
::getLocalClusterInstance();
3678 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3679 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3680 if ( $cache->add( $key, time(), $ttl ) ) {
3681 JobQueueGroup
::singleton()->lazyPush(
3682 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3690 * Returns a list of updates to be performed when this page is deleted. The
3691 * updates should remove any information about this page from secondary data
3692 * stores such as links tables.
3694 * @param Content|null $content Optional Content object for determining the
3695 * necessary updates.
3696 * @return DeferrableUpdate[]
3698 public function getDeletionUpdates( Content
$content = null ) {
3700 // load content object, which may be used to determine the necessary updates.
3701 // XXX: the content may not be needed to determine the updates.
3703 $content = $this->getContent( Revision
::RAW
);
3704 } catch ( Exception
$ex ) {
3705 // If we can't load the content, something is wrong. Perhaps that's why
3706 // the user is trying to delete the page, so let's not fail in that case.
3707 // Note that doDeleteArticleReal() will already have logged an issue with
3708 // loading the content.
3715 $updates = $content->getDeletionUpdates( $this );
3718 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3723 * Whether this content displayed on this page
3724 * comes from the local database
3729 public function isLocal() {
3734 * The display name for the site this content
3735 * come from. If a subclass overrides isLocal(),
3736 * this could return something other than the
3742 public function getWikiDisplayName() {
3748 * Get the source URL for the content on this page,
3749 * typically the canonical URL, but may be a remote
3750 * link if the content comes from another site
3755 public function getSourceURL() {
3756 return $this->getTitle()->getCanonicalURL();
3760 * @param WANObjectCache $cache
3764 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3765 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3767 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );