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\Rdbms\FakeResultWrapper
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\DBError
;
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 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
437 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
440 && $index == DB_REPLICA
441 && $loadBalancer->getServerCount() > 1
442 && $loadBalancer->hasOrMadeRecentMasterChanges()
444 $from = self
::READ_LATEST
;
445 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
446 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
449 // No idea from where the caller got this data, assume replica DB.
451 $from = self
::READ_NORMAL
;
454 $this->loadFromRow( $data, $from );
458 * Load the object from a database row
461 * @param object|bool $data DB row containing fields returned by selectFields() or false
462 * @param string|int $from One of the following:
463 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
464 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
465 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
466 * the master DB using SELECT FOR UPDATE
468 public function loadFromRow( $data, $from ) {
469 $lc = LinkCache
::singleton();
470 $lc->clearLink( $this->mTitle
);
473 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
475 $this->mTitle
->loadFromRow( $data );
477 // Old-fashioned restrictions
478 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
480 $this->mId
= intval( $data->page_id
);
481 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
482 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
483 $this->mIsRedirect
= intval( $data->page_is_redirect
);
484 $this->mLatest
= intval( $data->page_latest
);
485 // T39225: $latest may no longer match the cached latest Revision object.
486 // Double-check the ID of any cached latest Revision object for consistency.
487 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
488 $this->mLastRevision
= null;
489 $this->mTimestamp
= '';
492 $lc->addBadLinkObj( $this->mTitle
);
494 $this->mTitle
->loadFromRow( false );
496 $this->clearCacheFields();
501 $this->mDataLoaded
= true;
502 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
506 * @return int Page ID
508 public function getId() {
509 if ( !$this->mDataLoaded
) {
510 $this->loadPageData();
516 * @return bool Whether or not the page exists in the database
518 public function exists() {
519 if ( !$this->mDataLoaded
) {
520 $this->loadPageData();
522 return $this->mId
> 0;
526 * Check if this page is something we're going to be showing
527 * some sort of sensible content for. If we return false, page
528 * views (plain action=view) will return an HTTP 404 response,
529 * so spiders and robots can know they're following a bad link.
533 public function hasViewableContent() {
534 return $this->mTitle
->isKnown();
538 * Tests if the article content represents a redirect
542 public function isRedirect() {
543 if ( !$this->mDataLoaded
) {
544 $this->loadPageData();
547 return (bool)$this->mIsRedirect
;
551 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
553 * Will use the revisions actual content model if the page exists,
554 * and the page's default if the page doesn't exist yet.
560 public function getContentModel() {
561 if ( $this->exists() ) {
562 $cache = ObjectCache
::getMainWANInstance();
564 return $cache->getWithSetCallback(
565 $cache->makeKey( 'page-content-model', $this->getLatest() ),
568 $rev = $this->getRevision();
570 // Look at the revision's actual content model
571 return $rev->getContentModel();
573 $title = $this->mTitle
->getPrefixedDBkey();
574 wfWarn( "Page $title exists but has no (visible) revisions!" );
575 return $this->mTitle
->getContentModel();
581 // use the default model for this page
582 return $this->mTitle
->getContentModel();
586 * Loads page_touched and returns a value indicating if it should be used
587 * @return bool True if this page exists and is not a redirect
589 public function checkTouched() {
590 if ( !$this->mDataLoaded
) {
591 $this->loadPageData();
593 return ( $this->mId
&& !$this->mIsRedirect
);
597 * Get the page_touched field
598 * @return string Containing GMT timestamp
600 public function getTouched() {
601 if ( !$this->mDataLoaded
) {
602 $this->loadPageData();
604 return $this->mTouched
;
608 * Get the page_links_updated field
609 * @return string|null Containing GMT timestamp
611 public function getLinksTimestamp() {
612 if ( !$this->mDataLoaded
) {
613 $this->loadPageData();
615 return $this->mLinksUpdated
;
619 * Get the page_latest field
620 * @return int The rev_id of current revision
622 public function getLatest() {
623 if ( !$this->mDataLoaded
) {
624 $this->loadPageData();
626 return (int)$this->mLatest
;
630 * Get the Revision object of the oldest revision
631 * @return Revision|null
633 public function getOldestRevision() {
634 // Try using the replica DB first, then try the master
635 $rev = $this->mTitle
->getFirstRevision();
637 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
643 * Loads everything except the text
644 * This isn't necessary for all uses, so it's only done if needed.
646 protected function loadLastEdit() {
647 if ( $this->mLastRevision
!== null ) {
648 return; // already loaded
651 $latest = $this->getLatest();
653 return; // page doesn't exist or is missing page_latest info
656 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
657 // T39225: if session S1 loads the page row FOR UPDATE, the result always
658 // includes the latest changes committed. This is true even within REPEATABLE-READ
659 // transactions, where S1 normally only sees changes committed before the first S1
660 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
661 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
662 // happened after the first S1 SELECT.
663 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
664 $flags = Revision
::READ_LOCKING
;
665 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
666 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
667 // Bug T93976: if page_latest was loaded from the master, fetch the
668 // revision from there as well, as it may not exist yet on a replica DB.
669 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
670 $flags = Revision
::READ_LATEST
;
671 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
673 $dbr = wfGetDB( DB_REPLICA
);
674 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
677 if ( $revision ) { // sanity
678 $this->setLastEdit( $revision );
683 * Set the latest revision
684 * @param Revision $revision
686 protected function setLastEdit( Revision
$revision ) {
687 $this->mLastRevision
= $revision;
688 $this->mTimestamp
= $revision->getTimestamp();
692 * Get the latest revision
693 * @return Revision|null
695 public function getRevision() {
696 $this->loadLastEdit();
697 if ( $this->mLastRevision
) {
698 return $this->mLastRevision
;
704 * Get the content of the current revision. No side-effects...
706 * @param int $audience One of:
707 * Revision::FOR_PUBLIC to be displayed to all users
708 * Revision::FOR_THIS_USER to be displayed to $wgUser
709 * Revision::RAW get the text regardless of permissions
710 * @param User $user User object to check for, only if FOR_THIS_USER is passed
711 * to the $audience parameter
712 * @return Content|null The content of the current revision
716 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
717 $this->loadLastEdit();
718 if ( $this->mLastRevision
) {
719 return $this->mLastRevision
->getContent( $audience, $user );
725 * @return string MW timestamp of last article revision
727 public function getTimestamp() {
728 // Check if the field has been filled by WikiPage::setTimestamp()
729 if ( !$this->mTimestamp
) {
730 $this->loadLastEdit();
733 return wfTimestamp( TS_MW
, $this->mTimestamp
);
737 * Set the page timestamp (use only to avoid DB queries)
738 * @param string $ts MW timestamp of last article revision
741 public function setTimestamp( $ts ) {
742 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
746 * @param int $audience One of:
747 * Revision::FOR_PUBLIC to be displayed to all users
748 * Revision::FOR_THIS_USER to be displayed to the given user
749 * Revision::RAW get the text regardless of permissions
750 * @param User $user User object to check for, only if FOR_THIS_USER is passed
751 * to the $audience parameter
752 * @return int User ID for the user that made the last article revision
754 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
755 $this->loadLastEdit();
756 if ( $this->mLastRevision
) {
757 return $this->mLastRevision
->getUser( $audience, $user );
764 * Get the User object of the user who created the page
765 * @param int $audience One of:
766 * Revision::FOR_PUBLIC to be displayed to all users
767 * Revision::FOR_THIS_USER to be displayed to the given user
768 * Revision::RAW get the text regardless of permissions
769 * @param User $user User object to check for, only if FOR_THIS_USER is passed
770 * to the $audience parameter
773 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
774 $revision = $this->getOldestRevision();
776 $userName = $revision->getUserText( $audience, $user );
777 return User
::newFromName( $userName, false );
784 * @param int $audience One of:
785 * Revision::FOR_PUBLIC to be displayed to all users
786 * Revision::FOR_THIS_USER to be displayed to the given user
787 * Revision::RAW get the text regardless of permissions
788 * @param User $user User object to check for, only if FOR_THIS_USER is passed
789 * to the $audience parameter
790 * @return string Username of the user that made the last article revision
792 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
793 $this->loadLastEdit();
794 if ( $this->mLastRevision
) {
795 return $this->mLastRevision
->getUserText( $audience, $user );
802 * @param int $audience One of:
803 * Revision::FOR_PUBLIC to be displayed to all users
804 * Revision::FOR_THIS_USER to be displayed to the given user
805 * Revision::RAW get the text regardless of permissions
806 * @param User $user User object to check for, only if FOR_THIS_USER is passed
807 * to the $audience parameter
808 * @return string Comment stored for the last article revision
810 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
811 $this->loadLastEdit();
812 if ( $this->mLastRevision
) {
813 return $this->mLastRevision
->getComment( $audience, $user );
820 * Returns true if last revision was marked as "minor edit"
822 * @return bool Minor edit indicator for the last article revision.
824 public function getMinorEdit() {
825 $this->loadLastEdit();
826 if ( $this->mLastRevision
) {
827 return $this->mLastRevision
->isMinor();
834 * Determine whether a page would be suitable for being counted as an
835 * article in the site_stats table based on the title & its content
837 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
838 * if false, the current database state will be used
841 public function isCountable( $editInfo = false ) {
842 global $wgArticleCountMethod;
844 if ( !$this->mTitle
->isContentPage() ) {
849 $content = $editInfo->pstContent
;
851 $content = $this->getContent();
854 if ( !$content ||
$content->isRedirect() ) {
860 if ( $wgArticleCountMethod === 'link' ) {
861 // nasty special case to avoid re-parsing to detect links
864 // ParserOutput::getLinks() is a 2D array of page links, so
865 // to be really correct we would need to recurse in the array
866 // but the main array should only have items in it if there are
868 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
870 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
871 [ 'pl_from' => $this->getId() ], __METHOD__
);
875 return $content->isCountable( $hasLinks );
879 * If this page is a redirect, get its target
881 * The target will be fetched from the redirect table if possible.
882 * If this page doesn't have an entry there, call insertRedirect()
883 * @return Title|null Title object, or null if this page is not a redirect
885 public function getRedirectTarget() {
886 if ( !$this->mTitle
->isRedirect() ) {
890 if ( $this->mRedirectTarget
!== null ) {
891 return $this->mRedirectTarget
;
894 // Query the redirect table
895 $dbr = wfGetDB( DB_REPLICA
);
896 $row = $dbr->selectRow( 'redirect',
897 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
898 [ 'rd_from' => $this->getId() ],
902 // rd_fragment and rd_interwiki were added later, populate them if empty
903 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
904 $this->mRedirectTarget
= Title
::makeTitle(
905 $row->rd_namespace
, $row->rd_title
,
906 $row->rd_fragment
, $row->rd_interwiki
908 return $this->mRedirectTarget
;
911 // This page doesn't have an entry in the redirect table
912 $this->mRedirectTarget
= $this->insertRedirect();
913 return $this->mRedirectTarget
;
917 * Insert an entry for this page into the redirect table if the content is a redirect
919 * The database update will be deferred via DeferredUpdates
921 * Don't call this function directly unless you know what you're doing.
922 * @return Title|null Title object or null if not a redirect
924 public function insertRedirect() {
925 $content = $this->getContent();
926 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
931 // Update the DB post-send if the page has not cached since now
932 $latest = $this->getLatest();
933 DeferredUpdates
::addCallableUpdate(
934 function () use ( $retval, $latest ) {
935 $this->insertRedirectEntry( $retval, $latest );
937 DeferredUpdates
::POSTSEND
,
945 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
946 * @param Title $rt Redirect target
947 * @param int|null $oldLatest Prior page_latest for check and set
949 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
950 $dbw = wfGetDB( DB_MASTER
);
951 $dbw->startAtomic( __METHOD__
);
953 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
957 'rd_from' => $this->getId(),
958 'rd_namespace' => $rt->getNamespace(),
959 'rd_title' => $rt->getDBkey(),
960 'rd_fragment' => $rt->getFragment(),
961 'rd_interwiki' => $rt->getInterwiki(),
965 'rd_namespace' => $rt->getNamespace(),
966 'rd_title' => $rt->getDBkey(),
967 'rd_fragment' => $rt->getFragment(),
968 'rd_interwiki' => $rt->getInterwiki(),
974 $dbw->endAtomic( __METHOD__
);
978 * Get the Title object or URL this page redirects to
980 * @return bool|Title|string False, Title of in-wiki target, or string with URL
982 public function followRedirect() {
983 return $this->getRedirectURL( $this->getRedirectTarget() );
987 * Get the Title object or URL to use for a redirect. We use Title
988 * objects for same-wiki, non-special redirects and URLs for everything
990 * @param Title $rt Redirect target
991 * @return bool|Title|string False, Title object of local target, or string with URL
993 public function getRedirectURL( $rt ) {
998 if ( $rt->isExternal() ) {
999 if ( $rt->isLocal() ) {
1000 // Offsite wikis need an HTTP redirect.
1001 // This can be hard to reverse and may produce loops,
1002 // so they may be disabled in the site configuration.
1003 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1004 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1006 // External pages without "local" bit set are not valid
1012 if ( $rt->isSpecialPage() ) {
1013 // Gotta handle redirects to special pages differently:
1014 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1015 // Some pages are not valid targets.
1016 if ( $rt->isValidRedirectTarget() ) {
1017 return $rt->getFullURL();
1027 * Get a list of users who have edited this article, not including the user who made
1028 * the most recent revision, which you can get from $article->getUser() if you want it
1029 * @return UserArrayFromResult
1031 public function getContributors() {
1032 // @todo FIXME: This is expensive; cache this info somewhere.
1034 $dbr = wfGetDB( DB_REPLICA
);
1036 $tables = [ 'revision', 'user' ];
1039 'user_id' => 'rev_user',
1040 'user_name' => 'rev_user_text',
1041 'user_real_name' => 'MIN(user_real_name)',
1042 'timestamp' => 'MAX(rev_timestamp)',
1045 $conds = [ 'rev_page' => $this->getId() ];
1047 // The user who made the top revision gets credited as "this page was last edited by
1048 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1049 $user = $this->getUser();
1051 $conds[] = "rev_user != $user";
1053 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1057 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1060 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1064 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1065 'ORDER BY' => 'timestamp DESC',
1068 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1069 return new UserArrayFromResult( $res );
1073 * Should the parser cache be used?
1075 * @param ParserOptions $parserOptions ParserOptions to check
1079 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1080 return $parserOptions->getStubThreshold() == 0
1082 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1083 && $this->getContentHandler()->isParserCacheSupported();
1087 * Get a ParserOutput for the given ParserOptions and revision ID.
1089 * The parser cache will be used if possible. Cache misses that result
1090 * in parser runs are debounced with PoolCounter.
1093 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1094 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1095 * get the current revision (default value)
1096 * @param bool $forceParse Force reindexing, regardless of cache settings
1097 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1099 public function getParserOutput(
1100 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1103 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1105 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1106 throw new InvalidArgumentException(
1107 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1111 wfDebug( __METHOD__
.
1112 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1113 if ( $parserOptions->getStubThreshold() ) {
1114 wfIncrStats( 'pcache.miss.stub' );
1117 if ( $useParserCache ) {
1118 $parserOutput = MediaWikiServices
::getInstance()->getParserCache()
1119 ->get( $this, $parserOptions );
1120 if ( $parserOutput !== false ) {
1121 return $parserOutput;
1125 if ( $oldid === null ||
$oldid === 0 ) {
1126 $oldid = $this->getLatest();
1129 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1132 return $pool->getParserOutput();
1136 * Do standard deferred updates after page view (existing or missing page)
1137 * @param User $user The relevant user
1138 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1140 public function doViewUpdates( User
$user, $oldid = 0 ) {
1141 if ( wfReadOnly() ) {
1145 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1146 // Update newtalk / watchlist notification status
1148 $user->clearNotification( $this->mTitle
, $oldid );
1149 } catch ( DBError
$e ) {
1150 // Avoid outage if the master is not reachable
1151 MWExceptionHandler
::logException( $e );
1156 * Perform the actions of a page purging
1158 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1159 * controlled how much purging was done.
1161 public function doPurge() {
1162 // Avoid PHP 7.1 warning of passing $this by reference
1165 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1169 $this->mTitle
->invalidateCache();
1172 HTMLFileCache
::clearFileCache( $this->getTitle() );
1173 // Send purge after above page_touched update was committed
1174 DeferredUpdates
::addUpdate(
1175 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1176 DeferredUpdates
::PRESEND
1179 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1180 $messageCache = MessageCache
::singleton();
1181 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1188 * Insert a new empty page record for this article.
1189 * This *must* be followed up by creating a revision
1190 * and running $this->updateRevisionOn( ... );
1191 * or else the record will be left in a funky state.
1192 * Best if all done inside a transaction.
1194 * @param IDatabase $dbw
1195 * @param int|null $pageId Custom page ID that will be used for the insert statement
1197 * @return bool|int The newly created page_id key; false if the row was not
1198 * inserted, e.g. because the title already existed or because the specified
1199 * page ID is already in use.
1201 public function insertOn( $dbw, $pageId = null ) {
1202 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1206 'page_namespace' => $this->mTitle
->getNamespace(),
1207 'page_title' => $this->mTitle
->getDBkey(),
1208 'page_restrictions' => '',
1209 'page_is_redirect' => 0, // Will set this shortly...
1211 'page_random' => wfRandom(),
1212 'page_touched' => $dbw->timestamp(),
1213 'page_latest' => 0, // Fill this in shortly...
1214 'page_len' => 0, // Fill this in shortly...
1215 ] +
$pageIdForInsert,
1220 if ( $dbw->affectedRows() > 0 ) {
1221 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1222 $this->mId
= $newid;
1223 $this->mTitle
->resetArticleID( $newid );
1227 return false; // nothing changed
1232 * Update the page record to point to a newly saved revision.
1234 * @param IDatabase $dbw
1235 * @param Revision $revision For ID number, and text used to set
1236 * length and redirect status fields
1237 * @param int $lastRevision If given, will not overwrite the page field
1238 * when different from the currently set value.
1239 * Giving 0 indicates the new page flag should be set on.
1240 * @param bool $lastRevIsRedirect If given, will optimize adding and
1241 * removing rows in redirect table.
1242 * @return bool Success; false if the page row was missing or page_latest changed
1244 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1245 $lastRevIsRedirect = null
1247 global $wgContentHandlerUseDB;
1249 // Assertion to try to catch T92046
1250 if ( (int)$revision->getId() === 0 ) {
1251 throw new InvalidArgumentException(
1252 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1256 $content = $revision->getContent();
1257 $len = $content ?
$content->getSize() : 0;
1258 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1260 $conditions = [ 'page_id' => $this->getId() ];
1262 if ( !is_null( $lastRevision ) ) {
1263 // An extra check against threads stepping on each other
1264 $conditions['page_latest'] = $lastRevision;
1268 'page_latest' => $revision->getId(),
1269 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1270 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1271 'page_is_redirect' => $rt !== null ?
1 : 0,
1275 if ( $wgContentHandlerUseDB ) {
1276 $row['page_content_model'] = $revision->getContentModel();
1279 $dbw->update( 'page',
1284 $result = $dbw->affectedRows() > 0;
1286 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1287 $this->setLastEdit( $revision );
1288 $this->mLatest
= $revision->getId();
1289 $this->mIsRedirect
= (bool)$rt;
1290 // Update the LinkCache.
1291 LinkCache
::singleton()->addGoodLinkObj(
1297 $revision->getContentModel()
1305 * Add row to the redirect table if this is a redirect, remove otherwise.
1307 * @param IDatabase $dbw
1308 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1309 * or NULL if this is not a redirect
1310 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1311 * removing rows in redirect table.
1312 * @return bool True on success, false on failure
1315 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1316 // Always update redirects (target link might have changed)
1317 // Update/Insert if we don't know if the last revision was a redirect or not
1318 // Delete if changing from redirect to non-redirect
1319 $isRedirect = !is_null( $redirectTitle );
1321 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1325 if ( $isRedirect ) {
1326 $this->insertRedirectEntry( $redirectTitle );
1328 // This is not a redirect, remove row from redirect table
1329 $where = [ 'rd_from' => $this->getId() ];
1330 $dbw->delete( 'redirect', $where, __METHOD__
);
1333 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1334 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1337 return ( $dbw->affectedRows() != 0 );
1341 * If the given revision is newer than the currently set page_latest,
1342 * update the page record. Otherwise, do nothing.
1344 * @deprecated since 1.24, use updateRevisionOn instead
1346 * @param IDatabase $dbw
1347 * @param Revision $revision
1350 public function updateIfNewerOn( $dbw, $revision ) {
1351 $row = $dbw->selectRow(
1352 [ 'revision', 'page' ],
1353 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1355 'page_id' => $this->getId(),
1356 'page_latest=rev_id' ],
1360 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1363 $prev = $row->rev_id
;
1364 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1366 // No or missing previous revision; mark the page as new
1368 $lastRevIsRedirect = null;
1371 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1377 * Get the content that needs to be saved in order to undo all revisions
1378 * between $undo and $undoafter. Revisions must belong to the same page,
1379 * must exist and must not be deleted
1380 * @param Revision $undo
1381 * @param Revision $undoafter Must be an earlier revision than $undo
1382 * @return Content|bool Content on success, false on failure
1384 * Before we had the Content object, this was done in getUndoText
1386 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1387 $handler = $undo->getContentHandler();
1388 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1392 * Returns true if this page's content model supports sections.
1396 * @todo The skin should check this and not offer section functionality if
1397 * sections are not supported.
1398 * @todo The EditPage should check this and not offer section functionality
1399 * if sections are not supported.
1401 public function supportsSections() {
1402 return $this->getContentHandler()->supportsSections();
1406 * @param string|int|null|bool $sectionId Section identifier as a number or string
1407 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1408 * or 'new' for a new section.
1409 * @param Content $sectionContent New content of the section.
1410 * @param string $sectionTitle New section's subject, only if $section is "new".
1411 * @param string $edittime Revision timestamp or null to use the current revision.
1413 * @throws MWException
1414 * @return Content|null New complete article content, or null if error.
1417 * @deprecated since 1.24, use replaceSectionAtRev instead
1419 public function replaceSectionContent(
1420 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1423 if ( $edittime && $sectionId !== 'new' ) {
1424 $dbr = wfGetDB( DB_REPLICA
);
1425 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1426 // Try the master if this thread may have just added it.
1427 // This could be abstracted into a Revision method, but we don't want
1428 // to encourage loading of revisions by timestamp.
1430 && wfGetLB()->getServerCount() > 1
1431 && wfGetLB()->hasOrMadeRecentMasterChanges()
1433 $dbw = wfGetDB( DB_MASTER
);
1434 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1437 $baseRevId = $rev->getId();
1441 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1445 * @param string|int|null|bool $sectionId Section identifier as a number or string
1446 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1447 * or 'new' for a new section.
1448 * @param Content $sectionContent New content of the section.
1449 * @param string $sectionTitle New section's subject, only if $section is "new".
1450 * @param int|null $baseRevId
1452 * @throws MWException
1453 * @return Content|null New complete article content, or null if error.
1457 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1458 $sectionTitle = '', $baseRevId = null
1460 if ( strval( $sectionId ) === '' ) {
1461 // Whole-page edit; let the whole text through
1462 $newContent = $sectionContent;
1464 if ( !$this->supportsSections() ) {
1465 throw new MWException( "sections not supported for content model " .
1466 $this->getContentHandler()->getModelID() );
1469 // T32711: always use current version when adding a new section
1470 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1471 $oldContent = $this->getContent();
1473 $rev = Revision
::newFromId( $baseRevId );
1475 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1476 $this->getId() . "; section: $sectionId)\n" );
1480 $oldContent = $rev->getContent();
1483 if ( !$oldContent ) {
1484 wfDebug( __METHOD__
. ": no page text\n" );
1488 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1495 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1497 * @return int Updated $flags
1499 public function checkFlags( $flags ) {
1500 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1501 if ( $this->exists() ) {
1502 $flags |
= EDIT_UPDATE
;
1512 * Change an existing article or create a new article. Updates RC and all necessary caches,
1513 * optionally via the deferred update array.
1515 * @param Content $content New content
1516 * @param string $summary Edit summary
1517 * @param int $flags Bitfield:
1519 * Article is known or assumed to be non-existent, create a new one
1521 * Article is known or assumed to be pre-existing, update it
1523 * Mark this edit minor, if the user is allowed to do so
1525 * Do not log the change in recentchanges
1527 * Mark the edit a "bot" edit regardless of user rights
1529 * Fill in blank summaries with generated text where possible
1531 * Signal that the page retrieve/save cycle happened entirely in this request.
1533 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1534 * article will be detected. If EDIT_UPDATE is specified and the article
1535 * doesn't exist, the function will return an edit-gone-missing error. If
1536 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1537 * error will be returned. These two conditions are also possible with
1538 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1540 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1541 * This is not the parent revision ID, rather the revision ID for older
1542 * content used as the source for a rollback, for example.
1543 * @param User $user The user doing the edit
1544 * @param string $serialFormat Format for storing the content in the
1546 * @param array|null $tags Change tags to apply to this edit
1547 * Callers are responsible for permission checks
1548 * (with ChangeTags::canAddTagsAccompanyingChange)
1549 * @param Int $undidRevId Id of revision that was undone or 0
1551 * @throws MWException
1552 * @return Status Possible errors:
1553 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1554 * set the fatal flag of $status.
1555 * edit-gone-missing: In update mode, but the article didn't exist.
1556 * edit-conflict: In update mode, the article changed unexpectedly.
1557 * edit-no-change: Warning that the text was the same as before.
1558 * edit-already-exists: In creation mode, but the article already exists.
1560 * Extensions may define additional errors.
1562 * $return->value will contain an associative array with members as follows:
1563 * new: Boolean indicating if the function attempted to create a new article.
1564 * revision: The revision object for the inserted revision, or null.
1567 * @throws MWException
1569 public function doEditContent(
1570 Content
$content, $summary, $flags = 0, $baseRevId = false,
1571 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1573 global $wgUser, $wgUseAutomaticEditSummaries;
1575 // Old default parameter for $tags was null
1576 if ( $tags === null ) {
1580 // Low-level sanity check
1581 if ( $this->mTitle
->getText() === '' ) {
1582 throw new MWException( 'Something is trying to edit an article with an empty title' );
1584 // Make sure the given content type is allowed for this page
1585 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1586 return Status
::newFatal( 'content-not-allowed-here',
1587 ContentHandler
::getLocalizedName( $content->getModel() ),
1588 $this->mTitle
->getPrefixedText()
1592 // Load the data from the master database if needed.
1593 // The caller may already loaded it from the master or even loaded it using
1594 // SELECT FOR UPDATE, so do not override that using clear().
1595 $this->loadPageData( 'fromdbmaster' );
1597 $user = $user ?
: $wgUser;
1598 $flags = $this->checkFlags( $flags );
1600 // Avoid PHP 7.1 warning of passing $this by reference
1603 // Trigger pre-save hook (using provided edit summary)
1604 $hookStatus = Status
::newGood( [] );
1605 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1606 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1607 // Check if the hook rejected the attempted save
1608 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1609 if ( $hookStatus->isOK() ) {
1610 // Hook returned false but didn't call fatal(); use generic message
1611 $hookStatus->fatal( 'edit-hook-aborted' );
1617 $old_revision = $this->getRevision(); // current revision
1618 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1620 $handler = $content->getContentHandler();
1621 $tag = $handler->getChangeTag( $old_content, $content, $flags );
1622 // If there is no applicable tag, null is returned, so we need to check
1627 // Provide autosummaries if summary is not provided and autosummaries are enabled
1628 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1629 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1632 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1633 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1639 // Get the pre-save transform content and final parser output
1640 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1641 $pstContent = $editInfo->pstContent
; // Content object
1643 'bot' => ( $flags & EDIT_FORCE_BOT
),
1644 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1645 'serialized' => $pstContent->serialize( $serialFormat ),
1646 'serialFormat' => $serialFormat,
1647 'baseRevId' => $baseRevId,
1648 'oldRevision' => $old_revision,
1649 'oldContent' => $old_content,
1650 'oldId' => $this->getLatest(),
1651 'oldIsRedirect' => $this->isRedirect(),
1652 'oldCountable' => $this->isCountable(),
1653 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1654 'undidRevId' => $undidRevId
1657 // Actually create the revision and create/update the page
1658 if ( $flags & EDIT_UPDATE
) {
1659 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1661 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1664 // Promote user to any groups they meet the criteria for
1665 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1666 $user->addAutopromoteOnceGroups( 'onEdit' );
1667 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1674 * @param Content $content Pre-save transform content
1677 * @param string $summary
1678 * @param array $meta
1680 * @throws DBUnexpectedError
1682 * @throws FatalError
1683 * @throws MWException
1685 private function doModify(
1686 Content
$content, $flags, User
$user, $summary, array $meta
1688 global $wgUseRCPatrol;
1690 // Update article, but only if changed.
1691 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1693 // Convenience variables
1694 $now = wfTimestampNow();
1695 $oldid = $meta['oldId'];
1696 /** @var Content|null $oldContent */
1697 $oldContent = $meta['oldContent'];
1698 $newsize = $content->getSize();
1701 // Article gone missing
1702 $status->fatal( 'edit-gone-missing' );
1705 } elseif ( !$oldContent ) {
1706 // Sanity check for T39225
1707 throw new MWException( "Could not find text for current revision {$oldid}." );
1710 $changed = !$content->equals( $oldContent );
1712 $dbw = wfGetDB( DB_MASTER
);
1715 // @TODO: pass content object?!
1716 $revision = new Revision( [
1717 'page' => $this->getId(),
1718 'title' => $this->mTitle
, // for determining the default content model
1719 'comment' => $summary,
1720 'minor_edit' => $meta['minor'],
1721 'text' => $meta['serialized'],
1723 'parent_id' => $oldid,
1724 'user' => $user->getId(),
1725 'user_text' => $user->getName(),
1726 'timestamp' => $now,
1727 'content_model' => $content->getModel(),
1728 'content_format' => $meta['serialFormat'],
1731 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1732 $status->merge( $prepStatus );
1733 if ( !$status->isOK() ) {
1737 $dbw->startAtomic( __METHOD__
);
1738 // Get the latest page_latest value while locking it.
1739 // Do a CAS style check to see if it's the same as when this method
1740 // started. If it changed then bail out before touching the DB.
1741 $latestNow = $this->lockAndGetLatest();
1742 if ( $latestNow != $oldid ) {
1743 $dbw->endAtomic( __METHOD__
);
1744 // Page updated or deleted in the mean time
1745 $status->fatal( 'edit-conflict' );
1750 // At this point we are now comitted to returning an OK
1751 // status unless some DB query error or other exception comes up.
1752 // This way callers don't have to call rollback() if $status is bad
1753 // unless they actually try to catch exceptions (which is rare).
1755 // Save the revision text
1756 $revisionId = $revision->insertOn( $dbw );
1757 // Update page_latest and friends to reflect the new revision
1758 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1759 throw new MWException( "Failed to update page row to use new revision." );
1762 Hooks
::run( 'NewRevisionFromEditComplete',
1763 [ $this, $revision, $meta['baseRevId'], $user ] );
1765 // Update recentchanges
1766 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1767 // Mark as patrolled if the user can do so
1768 $patrolled = $wgUseRCPatrol && !count(
1769 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1770 // Add RC row to the DB
1771 RecentChange
::notifyEdit(
1774 $revision->isMinor(),
1778 $this->getTimestamp(),
1781 $oldContent ?
$oldContent->getSize() : 0,
1789 $user->incEditCount();
1791 $dbw->endAtomic( __METHOD__
);
1792 $this->mTimestamp
= $now;
1794 // T34948: revision ID must be set to page {{REVISIONID}} and
1795 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1796 // Since we don't insert a new revision into the database, the least
1797 // error-prone way is to reuse given old revision.
1798 $revision = $meta['oldRevision'];
1802 // Return the new revision to the caller
1803 $status->value
['revision'] = $revision;
1805 $status->warning( 'edit-no-change' );
1806 // Update page_touched as updateRevisionOn() was not called.
1807 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1808 $this->mTitle
->invalidateCache( $now );
1811 // Do secondary updates once the main changes have been committed...
1812 DeferredUpdates
::addUpdate(
1813 new AtomicSectionUpdate(
1817 $revision, &$user, $content, $summary, &$flags,
1818 $changed, $meta, &$status
1820 // Update links tables, site stats, etc.
1821 $this->doEditUpdates(
1825 'changed' => $changed,
1826 'oldcountable' => $meta['oldCountable'],
1827 'oldrevision' => $meta['oldRevision']
1830 // Avoid PHP 7.1 warning of passing $this by reference
1832 // Trigger post-save hook
1833 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1834 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1835 $meta['undidRevId'] ];
1836 Hooks
::run( 'PageContentSaveComplete', $params );
1839 DeferredUpdates
::PRESEND
1846 * @param Content $content Pre-save transform content
1849 * @param string $summary
1850 * @param array $meta
1852 * @throws DBUnexpectedError
1854 * @throws FatalError
1855 * @throws MWException
1857 private function doCreate(
1858 Content
$content, $flags, User
$user, $summary, array $meta
1860 global $wgUseRCPatrol, $wgUseNPPatrol;
1862 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1864 $now = wfTimestampNow();
1865 $newsize = $content->getSize();
1866 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1867 $status->merge( $prepStatus );
1868 if ( !$status->isOK() ) {
1872 $dbw = wfGetDB( DB_MASTER
);
1873 $dbw->startAtomic( __METHOD__
);
1875 // Add the page record unless one already exists for the title
1876 $newid = $this->insertOn( $dbw );
1877 if ( $newid === false ) {
1878 $dbw->endAtomic( __METHOD__
); // nothing inserted
1879 $status->fatal( 'edit-already-exists' );
1881 return $status; // nothing done
1884 // At this point we are now comitted to returning an OK
1885 // status unless some DB query error or other exception comes up.
1886 // This way callers don't have to call rollback() if $status is bad
1887 // unless they actually try to catch exceptions (which is rare).
1889 // @TODO: pass content object?!
1890 $revision = new Revision( [
1892 'title' => $this->mTitle
, // for determining the default content model
1893 'comment' => $summary,
1894 'minor_edit' => $meta['minor'],
1895 'text' => $meta['serialized'],
1897 'user' => $user->getId(),
1898 'user_text' => $user->getName(),
1899 'timestamp' => $now,
1900 'content_model' => $content->getModel(),
1901 'content_format' => $meta['serialFormat'],
1904 // Save the revision text...
1905 $revisionId = $revision->insertOn( $dbw );
1906 // Update the page record with revision data
1907 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1908 throw new MWException( "Failed to update page row to use new revision." );
1911 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1913 // Update recentchanges
1914 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1915 // Mark as patrolled if the user can do so
1916 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1917 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1918 // Add RC row to the DB
1919 RecentChange
::notifyNew(
1922 $revision->isMinor(),
1934 $user->incEditCount();
1936 $dbw->endAtomic( __METHOD__
);
1937 $this->mTimestamp
= $now;
1939 // Return the new revision to the caller
1940 $status->value
['revision'] = $revision;
1942 // Do secondary updates once the main changes have been committed...
1943 DeferredUpdates
::addUpdate(
1944 new AtomicSectionUpdate(
1948 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1950 // Update links, etc.
1951 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1952 // Avoid PHP 7.1 warning of passing $this by reference
1954 // Trigger post-create hook
1955 $params = [ &$wikiPage, &$user, $content, $summary,
1956 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1957 Hooks
::run( 'PageContentInsertComplete', $params );
1958 // Trigger post-save hook
1959 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1960 Hooks
::run( 'PageContentSaveComplete', $params );
1963 DeferredUpdates
::PRESEND
1970 * Get parser options suitable for rendering the primary article wikitext
1972 * @see ContentHandler::makeParserOptions
1974 * @param IContextSource|User|string $context One of the following:
1975 * - IContextSource: Use the User and the Language of the provided
1977 * - User: Use the provided User object and $wgLang for the language,
1978 * so use an IContextSource object if possible.
1979 * - 'canonical': Canonical options (anonymous user with default
1980 * preferences and content language).
1981 * @return ParserOptions
1983 public function makeParserOptions( $context ) {
1984 $options = $this->getContentHandler()->makeParserOptions( $context );
1986 if ( $this->getTitle()->isConversionTable() ) {
1987 // @todo ConversionTable should become a separate content model, so
1988 // we don't need special cases like this one.
1989 $options->disableContentConversion();
1996 * Prepare content which is about to be saved.
1998 * Prior to 1.30, this returned a stdClass object with the same class
2001 * @param Content $content
2002 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2003 * revision ID is also accepted, but this is deprecated.
2004 * @param User|null $user
2005 * @param string|null $serialFormat
2006 * @param bool $useCache Check shared prepared edit cache
2008 * @return PreparedEdit
2012 public function prepareContentForEdit(
2013 Content
$content, $revision = null, User
$user = null,
2014 $serialFormat = null, $useCache = true
2016 global $wgContLang, $wgUser, $wgAjaxEditStash;
2018 if ( is_object( $revision ) ) {
2019 $revid = $revision->getId();
2022 // This code path is deprecated, and nothing is known to
2023 // use it, so performance here shouldn't be a worry.
2024 if ( $revid !== null ) {
2025 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
2026 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2032 $user = is_null( $user ) ?
$wgUser : $user;
2033 // XXX: check $user->getId() here???
2035 // Use a sane default for $serialFormat, see T59026
2036 if ( $serialFormat === null ) {
2037 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2040 if ( $this->mPreparedEdit
2041 && isset( $this->mPreparedEdit
->newContent
)
2042 && $this->mPreparedEdit
->newContent
->equals( $content )
2043 && $this->mPreparedEdit
->revid
== $revid
2044 && $this->mPreparedEdit
->format
== $serialFormat
2045 // XXX: also check $user here?
2048 return $this->mPreparedEdit
;
2051 // The edit may have already been prepared via api.php?action=stashedit
2052 $cachedEdit = $useCache && $wgAjaxEditStash
2053 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2056 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2057 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2059 $edit = new PreparedEdit();
2060 if ( $cachedEdit ) {
2061 $edit->timestamp
= $cachedEdit->timestamp
;
2063 $edit->timestamp
= wfTimestampNow();
2065 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2066 $edit->revid
= $revid;
2068 if ( $cachedEdit ) {
2069 $edit->pstContent
= $cachedEdit->pstContent
;
2071 $edit->pstContent
= $content
2072 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2076 $edit->format
= $serialFormat;
2077 $edit->popts
= $this->makeParserOptions( 'canonical' );
2078 if ( $cachedEdit ) {
2079 $edit->output
= $cachedEdit->output
;
2082 // We get here if vary-revision is set. This means that this page references
2083 // itself (such as via self-transclusion). In this case, we need to make sure
2084 // that any such self-references refer to the newly-saved revision, and not
2085 // to the previous one, which could otherwise happen due to replica DB lag.
2086 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2087 $edit->popts
->setCurrentRevisionCallback(
2088 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2089 if ( $title->equals( $revision->getTitle() ) ) {
2092 return call_user_func( $oldCallback, $title, $parser );
2097 // Try to avoid a second parse if {{REVISIONID}} is used
2098 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2099 ? DB_MASTER
// use the best possible guess
2100 : DB_REPLICA
; // T154554
2102 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2103 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2111 $edit->output
= $edit->pstContent
2112 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2116 $edit->newContent
= $content;
2117 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2119 // NOTE: B/C for hooks! don't use these fields!
2120 $edit->newText
= $edit->newContent
2121 ? ContentHandler
::getContentText( $edit->newContent
)
2123 $edit->oldText
= $edit->oldContent
2124 ? ContentHandler
::getContentText( $edit->oldContent
)
2126 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2128 if ( $edit->output
) {
2129 $edit->output
->setCacheTime( wfTimestampNow() );
2132 // Process cache the result
2133 $this->mPreparedEdit
= $edit;
2139 * Do standard deferred updates after page edit.
2140 * Update links tables, site stats, search index and message cache.
2141 * Purges pages that include this page if the text was changed here.
2142 * Every 100th edit, prune the recent changes table.
2144 * @param Revision $revision
2145 * @param User $user User object that did the revision
2146 * @param array $options Array of options, following indexes are used:
2147 * - changed: bool, whether the revision changed the content (default true)
2148 * - created: bool, whether the revision created the page (default false)
2149 * - moved: bool, whether the page was moved (default false)
2150 * - restored: bool, whether the page was undeleted (default false)
2151 * - oldrevision: Revision object for the pre-update revision (default null)
2152 * - oldcountable: bool, null, or string 'no-change' (default null):
2153 * - bool: whether the page was counted as an article before that
2154 * revision, only used in changed is true and created is false
2155 * - null: if created is false, don't update the article count; if created
2156 * is true, do update the article count
2157 * - 'no-change': don't update the article count, ever
2159 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2160 global $wgRCWatchCategoryMembership;
2166 'restored' => false,
2167 'oldrevision' => null,
2168 'oldcountable' => null
2170 $content = $revision->getContent();
2172 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2174 // See if the parser output before $revision was inserted is still valid
2176 if ( !$this->mPreparedEdit
) {
2177 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2178 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2179 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2180 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2181 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2183 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2184 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2185 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2187 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2188 $editInfo = $this->mPreparedEdit
;
2192 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2193 // $text is usually already pre-save transformed once. Avoid using the edit stash
2194 // as any prepared content from there or in doEditContent() was already rejected.
2195 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2198 // Save it to the parser cache.
2199 // Make sure the cache time matches page_touched to avoid double parsing.
2200 MediaWikiServices
::getInstance()->getParserCache()->save(
2201 $editInfo->output
, $this, $editInfo->popts
,
2202 $revision->getTimestamp(), $editInfo->revid
2205 // Update the links tables and other secondary data
2207 $recursive = $options['changed']; // T52785
2208 $updates = $content->getSecondaryDataUpdates(
2209 $this->getTitle(), null, $recursive, $editInfo->output
2211 foreach ( $updates as $update ) {
2212 $update->setCause( 'edit-page', $user->getName() );
2213 if ( $update instanceof LinksUpdate
) {
2214 $update->setRevision( $revision );
2215 $update->setTriggeringUser( $user );
2217 DeferredUpdates
::addUpdate( $update );
2219 if ( $wgRCWatchCategoryMembership
2220 && $this->getContentHandler()->supportsCategories() === true
2221 && ( $options['changed'] ||
$options['created'] )
2222 && !$options['restored']
2224 // Note: jobs are pushed after deferred updates, so the job should be able to see
2225 // the recent change entry (also done via deferred updates) and carry over any
2226 // bot/deletion/IP flags, ect.
2227 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2230 'pageId' => $this->getId(),
2231 'revTimestamp' => $revision->getTimestamp()
2237 // Avoid PHP 7.1 warning of passing $this by reference
2240 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2242 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2243 // Flush old entries from the `recentchanges` table
2244 if ( mt_rand( 0, 9 ) == 0 ) {
2245 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2249 if ( !$this->exists() ) {
2253 $id = $this->getId();
2254 $title = $this->mTitle
->getPrefixedDBkey();
2255 $shortTitle = $this->mTitle
->getDBkey();
2257 if ( $options['oldcountable'] === 'no-change' ||
2258 ( !$options['changed'] && !$options['moved'] )
2261 } elseif ( $options['created'] ) {
2262 $good = (int)$this->isCountable( $editInfo );
2263 } elseif ( $options['oldcountable'] !== null ) {
2264 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2268 $edits = $options['changed'] ?
1 : 0;
2269 $total = $options['created'] ?
1 : 0;
2271 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2272 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2274 // If this is another user's talk page, update newtalk.
2275 // Don't do this if $options['changed'] = false (null-edits) nor if
2276 // it's a minor edit and the user doesn't want notifications for those.
2277 if ( $options['changed']
2278 && $this->mTitle
->getNamespace() == NS_USER_TALK
2279 && $shortTitle != $user->getTitleKey()
2280 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2282 $recipient = User
::newFromName( $shortTitle, false );
2283 if ( !$recipient ) {
2284 wfDebug( __METHOD__
. ": invalid username\n" );
2286 // Avoid PHP 7.1 warning of passing $this by reference
2289 // Allow extensions to prevent user notification
2290 // when a new message is added to their talk page
2291 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2292 if ( User
::isIP( $shortTitle ) ) {
2293 // An anonymous user
2294 $recipient->setNewtalk( true, $revision );
2295 } elseif ( $recipient->isLoggedIn() ) {
2296 $recipient->setNewtalk( true, $revision );
2298 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2304 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2305 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2308 if ( $options['created'] ) {
2309 self
::onArticleCreate( $this->mTitle
);
2310 } elseif ( $options['changed'] ) { // T52785
2311 self
::onArticleEdit( $this->mTitle
, $revision );
2314 ResourceLoaderWikiModule
::invalidateModuleCache(
2315 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2320 * Update the article's restriction field, and leave a log entry.
2321 * This works for protection both existing and non-existing pages.
2323 * @param array $limit Set of restriction keys
2324 * @param array $expiry Per restriction type expiration
2325 * @param int &$cascade Set to false if cascading protection isn't allowed.
2326 * @param string $reason
2327 * @param User $user The user updating the restrictions
2328 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2329 * ($user should be able to add the specified tags before this is called)
2330 * @return Status Status object; if action is taken, $status->value is the log_id of the
2331 * protection log entry.
2333 public function doUpdateRestrictions( array $limit, array $expiry,
2334 &$cascade, $reason, User
$user, $tags = null
2336 global $wgCascadingRestrictionLevels;
2338 if ( wfReadOnly() ) {
2339 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2342 $this->loadPageData( 'fromdbmaster' );
2343 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2344 $id = $this->getId();
2350 // Take this opportunity to purge out expired restrictions
2351 Title
::purgeExpiredRestrictions();
2353 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2354 // we expect a single selection, but the schema allows otherwise.
2355 $isProtected = false;
2359 $dbw = wfGetDB( DB_MASTER
);
2361 foreach ( $restrictionTypes as $action ) {
2362 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2363 $expiry[$action] = 'infinity';
2365 if ( !isset( $limit[$action] ) ) {
2366 $limit[$action] = '';
2367 } elseif ( $limit[$action] != '' ) {
2371 // Get current restrictions on $action
2372 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2373 if ( $current != '' ) {
2374 $isProtected = true;
2377 if ( $limit[$action] != $current ) {
2379 } elseif ( $limit[$action] != '' ) {
2380 // Only check expiry change if the action is actually being
2381 // protected, since expiry does nothing on an not-protected
2383 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2389 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2393 // If nothing has changed, do nothing
2395 return Status
::newGood();
2398 if ( !$protect ) { // No protection at all means unprotection
2399 $revCommentMsg = 'unprotectedarticle-comment';
2400 $logAction = 'unprotect';
2401 } elseif ( $isProtected ) {
2402 $revCommentMsg = 'modifiedarticleprotection-comment';
2403 $logAction = 'modify';
2405 $revCommentMsg = 'protectedarticle-comment';
2406 $logAction = 'protect';
2409 $logRelationsValues = [];
2410 $logRelationsField = null;
2411 $logParamsDetails = [];
2413 // Null revision (used for change tag insertion)
2414 $nullRevision = null;
2416 if ( $id ) { // Protection of existing page
2417 // Avoid PHP 7.1 warning of passing $this by reference
2420 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2421 return Status
::newGood();
2424 // Only certain restrictions can cascade...
2425 $editrestriction = isset( $limit['edit'] )
2426 ?
[ $limit['edit'] ]
2427 : $this->mTitle
->getRestrictions( 'edit' );
2428 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2429 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2431 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2432 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2435 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2436 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2437 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2439 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2440 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2443 // The schema allows multiple restrictions
2444 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2448 // insert null revision to identify the page protection change as edit summary
2449 $latest = $this->getLatest();
2450 $nullRevision = $this->insertProtectNullRevision(
2459 if ( $nullRevision === null ) {
2460 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2463 $logRelationsField = 'pr_id';
2465 // Update restrictions table
2466 foreach ( $limit as $action => $restrictions ) {
2468 'page_restrictions',
2471 'pr_type' => $action
2475 if ( $restrictions != '' ) {
2476 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2478 'page_restrictions',
2481 'pr_type' => $action,
2482 'pr_level' => $restrictions,
2483 'pr_cascade' => $cascadeValue,
2484 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2488 $logRelationsValues[] = $dbw->insertId();
2489 $logParamsDetails[] = [
2491 'level' => $restrictions,
2492 'expiry' => $expiry[$action],
2493 'cascade' => (bool)$cascadeValue,
2498 // Clear out legacy restriction fields
2501 [ 'page_restrictions' => '' ],
2502 [ 'page_id' => $id ],
2506 // Avoid PHP 7.1 warning of passing $this by reference
2509 Hooks
::run( 'NewRevisionFromEditComplete',
2510 [ $this, $nullRevision, $latest, $user ] );
2511 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2512 } else { // Protection of non-existing page (also known as "title protection")
2513 // Cascade protection is meaningless in this case
2516 if ( $limit['create'] != '' ) {
2517 $commentFields = CommentStore
::newKey( 'pt_reason' )->insert( $dbw, $reason );
2518 $dbw->replace( 'protected_titles',
2519 [ [ 'pt_namespace', 'pt_title' ] ],
2521 'pt_namespace' => $this->mTitle
->getNamespace(),
2522 'pt_title' => $this->mTitle
->getDBkey(),
2523 'pt_create_perm' => $limit['create'],
2524 'pt_timestamp' => $dbw->timestamp(),
2525 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2526 'pt_user' => $user->getId(),
2527 ] +
$commentFields, __METHOD__
2529 $logParamsDetails[] = [
2531 'level' => $limit['create'],
2532 'expiry' => $expiry['create'],
2535 $dbw->delete( 'protected_titles',
2537 'pt_namespace' => $this->mTitle
->getNamespace(),
2538 'pt_title' => $this->mTitle
->getDBkey()
2544 $this->mTitle
->flushRestrictions();
2545 InfoAction
::invalidateCache( $this->mTitle
);
2547 if ( $logAction == 'unprotect' ) {
2550 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2552 '4::description' => $protectDescriptionLog, // parameter for IRC
2553 '5:bool:cascade' => $cascade,
2554 'details' => $logParamsDetails, // parameter for localize and api
2558 // Update the protection log
2559 $logEntry = new ManualLogEntry( 'protect', $logAction );
2560 $logEntry->setTarget( $this->mTitle
);
2561 $logEntry->setComment( $reason );
2562 $logEntry->setPerformer( $user );
2563 $logEntry->setParameters( $params );
2564 if ( !is_null( $nullRevision ) ) {
2565 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2567 $logEntry->setTags( $tags );
2568 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2569 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2571 $logId = $logEntry->insert();
2572 $logEntry->publish( $logId );
2574 return Status
::newGood( $logId );
2578 * Insert a new null revision for this page.
2580 * @param string $revCommentMsg Comment message key for the revision
2581 * @param array $limit Set of restriction keys
2582 * @param array $expiry Per restriction type expiration
2583 * @param int $cascade Set to false if cascading protection isn't allowed.
2584 * @param string $reason
2585 * @param User|null $user
2586 * @return Revision|null Null on error
2588 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2589 array $expiry, $cascade, $reason, $user = null
2591 $dbw = wfGetDB( DB_MASTER
);
2593 // Prepare a null revision to be added to the history
2594 $editComment = wfMessage(
2596 $this->mTitle
->getPrefixedText(),
2597 $user ?
$user->getName() : ''
2598 )->inContentLanguage()->text();
2600 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2602 $protectDescription = $this->protectDescription( $limit, $expiry );
2603 if ( $protectDescription ) {
2604 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2605 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2606 ->inContentLanguage()->text();
2609 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2610 $editComment .= wfMessage( 'brackets' )->params(
2611 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2612 )->inContentLanguage()->text();
2615 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2617 $nullRev->insertOn( $dbw );
2619 // Update page record and touch page
2620 $oldLatest = $nullRev->getParentId();
2621 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2628 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2631 protected function formatExpiry( $expiry ) {
2634 if ( $expiry != 'infinity' ) {
2637 $wgContLang->timeanddate( $expiry, false, false ),
2638 $wgContLang->date( $expiry, false, false ),
2639 $wgContLang->time( $expiry, false, false )
2640 )->inContentLanguage()->text();
2642 return wfMessage( 'protect-expiry-indefinite' )
2643 ->inContentLanguage()->text();
2648 * Builds the description to serve as comment for the edit.
2650 * @param array $limit Set of restriction keys
2651 * @param array $expiry Per restriction type expiration
2654 public function protectDescription( array $limit, array $expiry ) {
2655 $protectDescription = '';
2657 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2658 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2659 # All possible message keys are listed here for easier grepping:
2660 # * restriction-create
2661 # * restriction-edit
2662 # * restriction-move
2663 # * restriction-upload
2664 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2665 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2666 # with '' filtered out. All possible message keys are listed below:
2667 # * protect-level-autoconfirmed
2668 # * protect-level-sysop
2669 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2670 ->inContentLanguage()->text();
2672 $expiryText = $this->formatExpiry( $expiry[$action] );
2674 if ( $protectDescription !== '' ) {
2675 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2677 $protectDescription .= wfMessage( 'protect-summary-desc' )
2678 ->params( $actionText, $restrictionsText, $expiryText )
2679 ->inContentLanguage()->text();
2682 return $protectDescription;
2686 * Builds the description to serve as comment for the log entry.
2688 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2689 * protect description text. Keep them in old format to avoid breaking compatibility.
2690 * TODO: Fix protection log to store structured description and format it on-the-fly.
2692 * @param array $limit Set of restriction keys
2693 * @param array $expiry Per restriction type expiration
2696 public function protectDescriptionLog( array $limit, array $expiry ) {
2699 $protectDescriptionLog = '';
2701 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2702 $expiryText = $this->formatExpiry( $expiry[$action] );
2703 $protectDescriptionLog .= $wgContLang->getDirMark() .
2704 "[$action=$restrictions] ($expiryText)";
2707 return trim( $protectDescriptionLog );
2711 * Take an array of page restrictions and flatten it to a string
2712 * suitable for insertion into the page_restrictions field.
2714 * @param string[] $limit
2716 * @throws MWException
2719 protected static function flattenRestrictions( $limit ) {
2720 if ( !is_array( $limit ) ) {
2721 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2727 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2728 $bits[] = "$action=$restrictions";
2731 return implode( ':', $bits );
2735 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2736 * backwards compatibility, if you care about error reporting you should use
2737 * doDeleteArticleReal() instead.
2739 * Deletes the article with database consistency, writes logs, purges caches
2741 * @param string $reason Delete reason for deletion log
2742 * @param bool $suppress Suppress all revisions and log the deletion in
2743 * the suppression log instead of the deletion log
2744 * @param int $u1 Unused
2745 * @param bool $u2 Unused
2746 * @param array|string &$error Array of errors to append to
2747 * @param User $user The deleting user
2748 * @return bool True if successful
2750 public function doDeleteArticle(
2751 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2753 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2754 return $status->isGood();
2758 * Back-end article deletion
2759 * Deletes the article with database consistency, writes logs, purges caches
2763 * @param string $reason Delete reason for deletion log
2764 * @param bool $suppress Suppress all revisions and log the deletion in
2765 * the suppression log instead of the deletion log
2766 * @param int $u1 Unused
2767 * @param bool $u2 Unused
2768 * @param array|string &$error Array of errors to append to
2769 * @param User $user The deleting user
2770 * @param array $tags Tags to apply to the deletion action
2771 * @param string $logsubtype
2772 * @return Status Status object; if successful, $status->value is the log_id of the
2773 * deletion log entry. If the page couldn't be deleted because it wasn't
2774 * found, $status is a non-fatal 'cannotdelete' error
2776 public function doDeleteArticleReal(
2777 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2778 $tags = [], $logsubtype = 'delete'
2780 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2782 wfDebug( __METHOD__
. "\n" );
2784 $status = Status
::newGood();
2786 if ( $this->mTitle
->getDBkey() === '' ) {
2787 $status->error( 'cannotdelete',
2788 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2792 // Avoid PHP 7.1 warning of passing $this by reference
2795 $user = is_null( $user ) ?
$wgUser : $user;
2796 if ( !Hooks
::run( 'ArticleDelete',
2797 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2799 if ( $status->isOK() ) {
2800 // Hook aborted but didn't set a fatal status
2801 $status->fatal( 'delete-hook-aborted' );
2806 $dbw = wfGetDB( DB_MASTER
);
2807 $dbw->startAtomic( __METHOD__
);
2809 $this->loadPageData( self
::READ_LATEST
);
2810 $id = $this->getId();
2811 // T98706: lock the page from various other updates but avoid using
2812 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2813 // the revisions queries (which also JOIN on user). Only lock the page
2814 // row and CAS check on page_latest to see if the trx snapshot matches.
2815 $lockedLatest = $this->lockAndGetLatest();
2816 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2817 $dbw->endAtomic( __METHOD__
);
2818 // Page not there or trx snapshot is stale
2819 $status->error( 'cannotdelete',
2820 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2824 // Given the lock above, we can be confident in the title and page ID values
2825 $namespace = $this->getTitle()->getNamespace();
2826 $dbKey = $this->getTitle()->getDBkey();
2828 // At this point we are now comitted to returning an OK
2829 // status unless some DB query error or other exception comes up.
2830 // This way callers don't have to call rollback() if $status is bad
2831 // unless they actually try to catch exceptions (which is rare).
2833 // we need to remember the old content so we can use it to generate all deletion updates.
2834 $revision = $this->getRevision();
2836 $content = $this->getContent( Revision
::RAW
);
2837 } catch ( Exception
$ex ) {
2838 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2839 . $ex->getMessage() );
2844 $revCommentStore = new CommentStore( 'rev_comment' );
2845 $arCommentStore = new CommentStore( 'ar_comment' );
2847 $revQuery = Revision
::getQueryInfo();
2850 // Bitfields to further suppress the content
2852 $bitfield = Revision
::SUPPRESSED_ALL
;
2853 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2856 // For now, shunt the revision data into the archive table.
2857 // Text is *not* removed from the text table; bulk storage
2858 // is left intact to avoid breaking block-compression or
2859 // immutable storage schemes.
2860 // In the future, we may keep revisions and mark them with
2861 // the rev_deleted field, which is reserved for this purpose.
2863 // Get all of the page revisions
2864 $res = $dbw->select(
2865 $revQuery['tables'],
2866 $revQuery['fields'],
2867 [ 'rev_page' => $id ],
2873 // Build their equivalent archive rows
2877 /** @var int[] Revision IDs of edits that were made by IPs */
2880 foreach ( $res as $row ) {
2881 $comment = $revCommentStore->getComment( $row );
2883 'ar_namespace' => $namespace,
2884 'ar_title' => $dbKey,
2885 'ar_user' => $row->rev_user
,
2886 'ar_user_text' => $row->rev_user_text
,
2887 'ar_timestamp' => $row->rev_timestamp
,
2888 'ar_minor_edit' => $row->rev_minor_edit
,
2889 'ar_rev_id' => $row->rev_id
,
2890 'ar_parent_id' => $row->rev_parent_id
,
2891 'ar_text_id' => $row->rev_text_id
,
2894 'ar_len' => $row->rev_len
,
2895 'ar_page_id' => $id,
2896 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2897 'ar_sha1' => $row->rev_sha1
,
2898 ] +
$arCommentStore->insert( $dbw, $comment );
2899 if ( $wgContentHandlerUseDB ) {
2900 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2901 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2903 $rowsInsert[] = $rowInsert;
2904 $revids[] = $row->rev_id
;
2906 // Keep track of IP edits, so that the corresponding rows can
2907 // be deleted in the ip_changes table.
2908 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2909 $ipRevIds[] = $row->rev_id
;
2912 // Copy them into the archive table
2913 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2914 // Save this so we can pass it to the ArticleDeleteComplete hook.
2915 $archivedRevisionCount = $dbw->affectedRows();
2917 // Clone the title and wikiPage, so we have the information we need when
2918 // we log and run the ArticleDeleteComplete hook.
2919 $logTitle = clone $this->mTitle
;
2920 $wikiPageBeforeDelete = clone $this;
2922 // Now that it's safely backed up, delete it
2923 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2924 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2925 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2926 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2929 // Also delete records from ip_changes as applicable.
2930 if ( count( $ipRevIds ) > 0 ) {
2931 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2934 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2935 $logtype = $suppress ?
'suppress' : 'delete';
2937 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2938 $logEntry->setPerformer( $user );
2939 $logEntry->setTarget( $logTitle );
2940 $logEntry->setComment( $reason );
2941 $logEntry->setTags( $tags );
2942 $logid = $logEntry->insert();
2944 $dbw->onTransactionPreCommitOrIdle(
2945 function () use ( $dbw, $logEntry, $logid ) {
2946 // T58776: avoid deadlocks (especially from FileDeleteForm)
2947 $logEntry->publish( $logid );
2952 $dbw->endAtomic( __METHOD__
);
2954 $this->doDeleteUpdates( $id, $content, $revision, $user );
2956 Hooks
::run( 'ArticleDeleteComplete', [
2957 &$wikiPageBeforeDelete,
2963 $archivedRevisionCount
2965 $status->value
= $logid;
2967 // Show log excerpt on 404 pages rather than just a link
2968 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2969 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2970 $cache->set( $key, 1, $cache::TTL_DAY
);
2976 * Lock the page row for this title+id and return page_latest (or 0)
2978 * @return int Returns 0 if no row was found with this title+id
2981 public function lockAndGetLatest() {
2982 return (int)wfGetDB( DB_MASTER
)->selectField(
2986 'page_id' => $this->getId(),
2987 // Typically page_id is enough, but some code might try to do
2988 // updates assuming the title is the same, so verify that
2989 'page_namespace' => $this->getTitle()->getNamespace(),
2990 'page_title' => $this->getTitle()->getDBkey()
2998 * Do some database updates after deletion
3000 * @param int $id The page_id value of the page being deleted
3001 * @param Content|null $content Optional page content to be used when determining
3002 * the required updates. This may be needed because $this->getContent()
3003 * may already return null when the page proper was deleted.
3004 * @param Revision|null $revision The latest page revision
3005 * @param User|null $user The user that caused the deletion
3007 public function doDeleteUpdates(
3008 $id, Content
$content = null, Revision
$revision = null, User
$user = null
3011 $countable = $this->isCountable();
3012 } catch ( Exception
$ex ) {
3013 // fallback for deleting broken pages for which we cannot load the content for
3014 // some reason. Note that doDeleteArticleReal() already logged this problem.
3018 // Update site status
3019 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3021 // Delete pagelinks, update secondary indexes, etc
3022 $updates = $this->getDeletionUpdates( $content );
3023 foreach ( $updates as $update ) {
3024 DeferredUpdates
::addUpdate( $update );
3027 $causeAgent = $user ?
$user->getName() : 'unknown';
3028 // Reparse any pages transcluding this page
3029 LinksUpdate
::queueRecursiveJobsForTable(
3030 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3031 // Reparse any pages including this image
3032 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3033 LinksUpdate
::queueRecursiveJobsForTable(
3034 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3038 self
::onArticleDelete( $this->mTitle
);
3039 ResourceLoaderWikiModule
::invalidateModuleCache(
3040 $this->mTitle
, $revision, null, wfWikiID()
3043 // Reset this object and the Title object
3044 $this->loadFromRow( false, self
::READ_LATEST
);
3047 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3051 * Roll back the most recent consecutive set of edits to a page
3052 * from the same user; fails if there are no eligible edits to
3053 * roll back to, e.g. user is the sole contributor. This function
3054 * performs permissions checks on $user, then calls commitRollback()
3055 * to do the dirty work
3057 * @todo Separate the business/permission stuff out from backend code
3058 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3060 * @param string $fromP Name of the user whose edits to rollback.
3061 * @param string $summary Custom summary. Set to default summary if empty.
3062 * @param string $token Rollback token.
3063 * @param bool $bot If true, mark all reverted edits as bot.
3065 * @param array &$resultDetails Array contains result-specific array of additional values
3066 * 'alreadyrolled' : 'current' (rev)
3067 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3069 * @param User $user The user performing the rollback
3070 * @param array|null $tags Change tags to apply to the rollback
3071 * Callers are responsible for permission checks
3072 * (with ChangeTags::canAddTagsAccompanyingChange)
3074 * @return array Array of errors, each error formatted as
3075 * array(messagekey, param1, param2, ...).
3076 * On success, the array is empty. This array can also be passed to
3077 * OutputPage::showPermissionsErrorPage().
3079 public function doRollback(
3080 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3082 $resultDetails = null;
3084 // Check permissions
3085 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3086 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3087 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3089 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3090 $errors[] = [ 'sessionfailure' ];
3093 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3094 $errors[] = [ 'actionthrottledtext' ];
3097 // If there were errors, bail out now
3098 if ( !empty( $errors ) ) {
3102 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3106 * Backend implementation of doRollback(), please refer there for parameter
3107 * and return value documentation
3109 * NOTE: This function does NOT check ANY permissions, it just commits the
3110 * rollback to the DB. Therefore, you should only call this function direct-
3111 * ly if you want to use custom permissions checks. If you don't, use
3112 * doRollback() instead.
3113 * @param string $fromP Name of the user whose edits to rollback.
3114 * @param string $summary Custom summary. Set to default summary if empty.
3115 * @param bool $bot If true, mark all reverted edits as bot.
3117 * @param array &$resultDetails Contains result-specific array of additional values
3118 * @param User $guser The user performing the rollback
3119 * @param array|null $tags Change tags to apply to the rollback
3120 * Callers are responsible for permission checks
3121 * (with ChangeTags::canAddTagsAccompanyingChange)
3125 public function commitRollback( $fromP, $summary, $bot,
3126 &$resultDetails, User
$guser, $tags = null
3128 global $wgUseRCPatrol, $wgContLang;
3130 $dbw = wfGetDB( DB_MASTER
);
3132 if ( wfReadOnly() ) {
3133 return [ [ 'readonlytext' ] ];
3136 // Get the last editor
3137 $current = $this->getRevision();
3138 if ( is_null( $current ) ) {
3139 // Something wrong... no page?
3140 return [ [ 'notanarticle' ] ];
3143 $from = str_replace( '_', ' ', $fromP );
3144 // User name given should match up with the top revision.
3145 // If the user was deleted then $from should be empty.
3146 if ( $from != $current->getUserText() ) {
3147 $resultDetails = [ 'current' => $current ];
3148 return [ [ 'alreadyrolled',
3149 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3150 htmlspecialchars( $fromP ),
3151 htmlspecialchars( $current->getUserText() )
3155 // Get the last edit not by this person...
3156 // Note: these may not be public values
3157 $user = intval( $current->getUser( Revision
::RAW
) );
3158 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3159 $s = $dbw->selectRow( 'revision',
3160 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3161 [ 'rev_page' => $current->getPage(),
3162 "rev_user != {$user} OR rev_user_text != {$user_text}"
3164 [ 'USE INDEX' => 'page_timestamp',
3165 'ORDER BY' => 'rev_timestamp DESC' ]
3167 if ( $s === false ) {
3168 // No one else ever edited this page
3169 return [ [ 'cantrollback' ] ];
3170 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3171 ||
$s->rev_deleted
& Revision
::DELETED_USER
3173 // Only admins can see this text
3174 return [ [ 'notvisiblerev' ] ];
3177 // Generate the edit summary if necessary
3178 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3179 if ( empty( $summary ) ) {
3180 if ( $from == '' ) { // no public user name
3181 $summary = wfMessage( 'revertpage-nouser' );
3183 $summary = wfMessage( 'revertpage' );
3187 // Allow the custom summary to use the same args as the default message
3189 $target->getUserText(), $from, $s->rev_id
,
3190 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3191 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3193 if ( $summary instanceof Message
) {
3194 $summary = $summary->params( $args )->inContentLanguage()->text();
3196 $summary = wfMsgReplaceArgs( $summary, $args );
3199 // Trim spaces on user supplied text
3200 $summary = trim( $summary );
3203 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3205 if ( $guser->isAllowed( 'minoredit' ) ) {
3206 $flags |
= EDIT_MINOR
;
3209 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3210 $flags |
= EDIT_FORCE_BOT
;
3213 $targetContent = $target->getContent();
3214 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3216 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3217 $tags[] = 'mw-rollback';
3220 // Actually store the edit
3221 $status = $this->doEditContent(
3231 // Set patrolling and bot flag on the edits, which gets rollbacked.
3232 // This is done even on edit failure to have patrolling in that case (T64157).
3234 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3235 // Mark all reverted edits as bot
3239 if ( $wgUseRCPatrol ) {
3240 // Mark all reverted edits as patrolled
3241 $set['rc_patrolled'] = 1;
3244 if ( count( $set ) ) {
3245 $dbw->update( 'recentchanges', $set,
3247 'rc_cur_id' => $current->getPage(),
3248 'rc_user_text' => $current->getUserText(),
3249 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3255 if ( !$status->isOK() ) {
3256 return $status->getErrorsArray();
3259 // raise error, when the edit is an edit without a new version
3260 $statusRev = isset( $status->value
['revision'] )
3261 ?
$status->value
['revision']
3263 if ( !( $statusRev instanceof Revision
) ) {
3264 $resultDetails = [ 'current' => $current ];
3265 return [ [ 'alreadyrolled',
3266 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3267 htmlspecialchars( $fromP ),
3268 htmlspecialchars( $current->getUserText() )
3272 if ( $changingContentModel ) {
3273 // If the content model changed during the rollback,
3274 // make sure it gets logged to Special:Log/contentmodel
3275 $log = new ManualLogEntry( 'contentmodel', 'change' );
3276 $log->setPerformer( $guser );
3277 $log->setTarget( $this->mTitle
);
3278 $log->setComment( $summary );
3279 $log->setParameters( [
3280 '4::oldmodel' => $current->getContentModel(),
3281 '5::newmodel' => $targetContent->getModel(),
3284 $logId = $log->insert( $dbw );
3285 $log->publish( $logId );
3288 $revId = $statusRev->getId();
3290 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3293 'summary' => $summary,
3294 'current' => $current,
3295 'target' => $target,
3304 * The onArticle*() functions are supposed to be a kind of hooks
3305 * which should be called whenever any of the specified actions
3308 * This is a good place to put code to clear caches, for instance.
3310 * This is called on page move and undelete, as well as edit
3312 * @param Title $title
3314 public static function onArticleCreate( Title
$title ) {
3315 // Update existence markers on article/talk tabs...
3316 $other = $title->getOtherPage();
3318 $other->purgeSquid();
3320 $title->touchLinks();
3321 $title->purgeSquid();
3322 $title->deleteTitleProtection();
3324 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3326 // Invalidate caches of articles which include this page
3327 DeferredUpdates
::addUpdate(
3328 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3331 if ( $title->getNamespace() == NS_CATEGORY
) {
3332 // Load the Category object, which will schedule a job to create
3333 // the category table row if necessary. Checking a replica DB is ok
3334 // here, in the worst case it'll run an unnecessary recount job on
3335 // a category that probably doesn't have many members.
3336 Category
::newFromTitle( $title )->getID();
3341 * Clears caches when article is deleted
3343 * @param Title $title
3345 public static function onArticleDelete( Title
$title ) {
3346 // Update existence markers on article/talk tabs...
3347 $other = $title->getOtherPage();
3349 $other->purgeSquid();
3351 $title->touchLinks();
3352 $title->purgeSquid();
3354 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3357 HTMLFileCache
::clearFileCache( $title );
3358 InfoAction
::invalidateCache( $title );
3361 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3362 MessageCache
::singleton()->updateMessageOverride( $title, null );
3366 if ( $title->getNamespace() == NS_FILE
) {
3367 DeferredUpdates
::addUpdate(
3368 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3373 if ( $title->getNamespace() == NS_USER_TALK
) {
3374 $user = User
::newFromName( $title->getText(), false );
3376 $user->setNewtalk( false );
3381 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3385 * Purge caches on page update etc
3387 * @param Title $title
3388 * @param Revision|null $revision Revision that was just saved, may be null
3390 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3391 // Invalidate caches of articles which include this page
3392 DeferredUpdates
::addUpdate(
3393 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3396 // Invalidate the caches of all pages which redirect here
3397 DeferredUpdates
::addUpdate(
3398 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3401 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3403 // Purge CDN for this page only
3404 $title->purgeSquid();
3405 // Clear file cache for this page only
3406 HTMLFileCache
::clearFileCache( $title );
3408 $revid = $revision ?
$revision->getId() : null;
3409 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3410 InfoAction
::invalidateCache( $title, $revid );
3417 * Returns a list of categories this page is a member of.
3418 * Results will include hidden categories
3420 * @return TitleArray
3422 public function getCategories() {
3423 $id = $this->getId();
3425 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3428 $dbr = wfGetDB( DB_REPLICA
);
3429 $res = $dbr->select( 'categorylinks',
3430 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3431 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3432 // as not being aliases, and NS_CATEGORY is numeric
3433 [ 'cl_from' => $id ],
3436 return TitleArray
::newFromResult( $res );
3440 * Returns a list of hidden categories this page is a member of.
3441 * Uses the page_props and categorylinks tables.
3443 * @return array Array of Title objects
3445 public function getHiddenCategories() {
3447 $id = $this->getId();
3453 $dbr = wfGetDB( DB_REPLICA
);
3454 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3456 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3457 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3460 if ( $res !== false ) {
3461 foreach ( $res as $row ) {
3462 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3470 * Auto-generates a deletion reason
3472 * @param bool &$hasHistory Whether the page has a history
3473 * @return string|bool String containing deletion reason or empty string, or boolean false
3474 * if no revision occurred
3476 public function getAutoDeleteReason( &$hasHistory ) {
3477 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3481 * Update all the appropriate counts in the category table, given that
3482 * we've added the categories $added and deleted the categories $deleted.
3484 * This should only be called from deferred updates or jobs to avoid contention.
3486 * @param array $added The names of categories that were added
3487 * @param array $deleted The names of categories that were deleted
3488 * @param int $id Page ID (this should be the original deleted page ID)
3490 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3491 $id = $id ?
: $this->getId();
3492 $ns = $this->getTitle()->getNamespace();
3494 $addFields = [ 'cat_pages = cat_pages + 1' ];
3495 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3496 if ( $ns == NS_CATEGORY
) {
3497 $addFields[] = 'cat_subcats = cat_subcats + 1';
3498 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3499 } elseif ( $ns == NS_FILE
) {
3500 $addFields[] = 'cat_files = cat_files + 1';
3501 $removeFields[] = 'cat_files = cat_files - 1';
3504 $dbw = wfGetDB( DB_MASTER
);
3506 if ( count( $added ) ) {
3507 $existingAdded = $dbw->selectFieldValues(
3510 [ 'cat_title' => $added ],
3514 // For category rows that already exist, do a plain
3515 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3516 // to avoid creating gaps in the cat_id sequence.
3517 if ( count( $existingAdded ) ) {
3521 [ 'cat_title' => $existingAdded ],
3526 $missingAdded = array_diff( $added, $existingAdded );
3527 if ( count( $missingAdded ) ) {
3529 foreach ( $missingAdded as $cat ) {
3531 'cat_title' => $cat,
3533 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3534 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3547 if ( count( $deleted ) ) {
3551 [ 'cat_title' => $deleted ],
3556 foreach ( $added as $catName ) {
3557 $cat = Category
::newFromName( $catName );
3558 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3561 foreach ( $deleted as $catName ) {
3562 $cat = Category
::newFromName( $catName );
3563 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3566 // Refresh counts on categories that should be empty now, to
3567 // trigger possible deletion. Check master for the most
3568 // up-to-date cat_pages.
3569 if ( count( $deleted ) ) {
3570 $rows = $dbw->select(
3572 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3573 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3576 foreach ( $rows as $row ) {
3577 $cat = Category
::newFromRow( $row );
3578 // T166757: do the update after this DB commit
3579 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3580 $cat->refreshCounts();
3587 * Opportunistically enqueue link update jobs given fresh parser output if useful
3589 * @param ParserOutput $parserOutput Current version page output
3592 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3593 if ( wfReadOnly() ) {
3597 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3598 [ $this, $this->mTitle
, $parserOutput ]
3603 $config = RequestContext
::getMain()->getConfig();
3606 'isOpportunistic' => true,
3607 'rootJobTimestamp' => $parserOutput->getCacheTime()
3610 if ( $this->mTitle
->areRestrictionsCascading() ) {
3611 // If the page is cascade protecting, the links should really be up-to-date
3612 JobQueueGroup
::singleton()->lazyPush(
3613 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3615 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3616 // Assume the output contains "dynamic" time/random based magic words.
3617 // Only update pages that expired due to dynamic content and NOT due to edits
3618 // to referenced templates/files. When the cache expires due to dynamic content,
3619 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3620 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3621 // template/file edit already triggered recursive RefreshLinksJob jobs.
3622 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3623 // If a page is uncacheable, do not keep spamming a job for it.
3624 // Although it would be de-duplicated, it would still waste I/O.
3625 $cache = ObjectCache
::getLocalClusterInstance();
3626 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3627 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3628 if ( $cache->add( $key, time(), $ttl ) ) {
3629 JobQueueGroup
::singleton()->lazyPush(
3630 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3638 * Returns a list of updates to be performed when this page is deleted. The
3639 * updates should remove any information about this page from secondary data
3640 * stores such as links tables.
3642 * @param Content|null $content Optional Content object for determining the
3643 * necessary updates.
3644 * @return DeferrableUpdate[]
3646 public function getDeletionUpdates( Content
$content = null ) {
3648 // load content object, which may be used to determine the necessary updates.
3649 // XXX: the content may not be needed to determine the updates.
3651 $content = $this->getContent( Revision
::RAW
);
3652 } catch ( Exception
$ex ) {
3653 // If we can't load the content, something is wrong. Perhaps that's why
3654 // the user is trying to delete the page, so let's not fail in that case.
3655 // Note that doDeleteArticleReal() will already have logged an issue with
3656 // loading the content.
3663 $updates = $content->getDeletionUpdates( $this );
3666 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3671 * Whether this content displayed on this page
3672 * comes from the local database
3677 public function isLocal() {
3682 * The display name for the site this content
3683 * come from. If a subclass overrides isLocal(),
3684 * this could return something other than the
3690 public function getWikiDisplayName() {
3696 * Get the source URL for the content on this page,
3697 * typically the canonical URL, but may be a remote
3698 * link if the content comes from another site
3703 public function getSourceURL() {
3704 return $this->getTitle()->getCanonicalURL();
3708 * @param WANObjectCache $cache
3712 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3713 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3715 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );