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 MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\RevisionRenderer
;
28 use MediaWiki\Revision\RevisionStore
;
29 use MediaWiki\Revision\SlotRecord
;
30 use MediaWiki\Storage\DerivedPageDataUpdater
;
31 use MediaWiki\Storage\PageUpdater
;
32 use MediaWiki\Storage\RevisionSlotsUpdate
;
33 use Wikimedia\Assert\Assert
;
34 use Wikimedia\Rdbms\FakeResultWrapper
;
35 use Wikimedia\Rdbms\IDatabase
;
36 use Wikimedia\Rdbms\LoadBalancer
;
39 * Class representing a MediaWiki article and history.
41 * Some fields are public only for backwards-compatibility. Use accessors.
42 * In the past, this class was part of Article.php and everything was public.
44 class WikiPage
implements Page
, IDBAccessObject
{
45 // Constants for $mDataLoadedFrom and related
50 public $mTitle = null;
55 public $mDataLoaded = false; // !< Boolean
56 public $mIsRedirect = false; // !< Boolean
57 public $mLatest = false; // !< Integer (false means "not loaded")
60 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
61 public $mPreparedEdit = false;
66 protected $mId = null;
69 * @var int One of the READ_* constants
71 protected $mDataLoadedFrom = self
::READ_NONE
;
76 protected $mRedirectTarget = null;
81 protected $mLastRevision = null;
84 * @var string Timestamp of the current revision or empty string if not loaded
86 protected $mTimestamp = '';
91 protected $mTouched = '19700101000000';
96 protected $mLinksUpdated = '19700101000000';
99 * @var DerivedPageDataUpdater|null
101 private $derivedDataUpdater = null;
104 * Constructor and clear the article
105 * @param Title $title Reference to a Title object.
107 public function __construct( Title
$title ) {
108 $this->mTitle
= $title;
112 * Makes sure that the mTitle object is cloned
113 * to the newly cloned WikiPage.
115 public function __clone() {
116 $this->mTitle
= clone $this->mTitle
;
120 * Create a WikiPage object of the appropriate class for the given title.
122 * @param Title $title
124 * @throws MWException
125 * @return WikiPage|WikiCategoryPage|WikiFilePage
127 public static function factory( Title
$title ) {
128 $ns = $title->getNamespace();
130 if ( $ns == NS_MEDIA
) {
131 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
132 } elseif ( $ns < 0 ) {
133 throw new MWException( "Invalid or virtual namespace $ns given." );
137 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
143 $page = new WikiFilePage( $title );
146 $page = new WikiCategoryPage( $title );
149 $page = new WikiPage( $title );
156 * Constructor from a page id
158 * @param int $id Article ID to load
159 * @param string|int $from One of the following values:
160 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
161 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
163 * @return WikiPage|null
165 public static function newFromID( $id, $from = 'fromdb' ) {
166 // page ids are never 0 or negative, see T63166
171 $from = self
::convertSelectType( $from );
172 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
173 $pageQuery = self
::getQueryInfo();
174 $row = $db->selectRow(
175 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
176 [], $pageQuery['joins']
181 return self
::newFromRow( $row, $from );
185 * Constructor from a database row
188 * @param object $row Database row containing at least fields returned by selectFields().
189 * @param string|int $from Source of $data:
190 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
191 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
192 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
195 public static function newFromRow( $row, $from = 'fromdb' ) {
196 $page = self
::factory( Title
::newFromRow( $row ) );
197 $page->loadFromRow( $row, $from );
202 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
204 * @param object|string|int $type
207 protected static function convertSelectType( $type ) {
210 return self
::READ_NORMAL
;
212 return self
::READ_LATEST
;
214 return self
::READ_LOCKING
;
216 // It may already be an integer or whatever else
222 * @return RevisionStore
224 private function getRevisionStore() {
225 return MediaWikiServices
::getInstance()->getRevisionStore();
229 * @return RevisionRenderer
231 private function getRevisionRenderer() {
232 return MediaWikiServices
::getInstance()->getRevisionRenderer();
236 * @return ParserCache
238 private function getParserCache() {
239 return MediaWikiServices
::getInstance()->getParserCache();
243 * @return LoadBalancer
245 private function getDBLoadBalancer() {
246 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
250 * @todo Move this UI stuff somewhere else
252 * @see ContentHandler::getActionOverrides
255 public function getActionOverrides() {
256 return $this->getContentHandler()->getActionOverrides();
260 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
262 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
264 * @return ContentHandler
268 public function getContentHandler() {
269 return ContentHandler
::getForModelID( $this->getContentModel() );
273 * Get the title object of the article
274 * @return Title Title object of this page
276 public function getTitle() {
277 return $this->mTitle
;
284 public function clear() {
285 $this->mDataLoaded
= false;
286 $this->mDataLoadedFrom
= self
::READ_NONE
;
288 $this->clearCacheFields();
292 * Clear the object cache fields
295 protected function clearCacheFields() {
297 $this->mRedirectTarget
= null; // Title object if set
298 $this->mLastRevision
= null; // Latest revision
299 $this->mTouched
= '19700101000000';
300 $this->mLinksUpdated
= '19700101000000';
301 $this->mTimestamp
= '';
302 $this->mIsRedirect
= false;
303 $this->mLatest
= false;
304 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
305 // checks the requested rev ID and content against the cached one. For most
306 // content types, the output should not change during the lifetime of this cache.
307 // Clearing it can cause extra parses on edit for no reason.
311 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
315 public function clearPreparedEdit() {
316 $this->mPreparedEdit
= false;
320 * Return the list of revision fields that should be selected to create
323 * @deprecated since 1.31, use self::getQueryInfo() instead.
326 public static function selectFields() {
327 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
329 wfDeprecated( __METHOD__
, '1.31' );
340 'page_links_updated',
345 if ( $wgContentHandlerUseDB ) {
346 $fields[] = 'page_content_model';
349 if ( $wgPageLanguageUseDB ) {
350 $fields[] = 'page_lang';
357 * Return the tables, fields, and join conditions to be selected to create
360 * @return array With three keys:
361 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
362 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
363 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
365 public static function getQueryInfo() {
366 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
369 'tables' => [ 'page' ],
379 'page_links_updated',
386 if ( $wgContentHandlerUseDB ) {
387 $ret['fields'][] = 'page_content_model';
390 if ( $wgPageLanguageUseDB ) {
391 $ret['fields'][] = 'page_lang';
398 * Fetch a page record with the given conditions
399 * @param IDatabase $dbr
400 * @param array $conditions
401 * @param array $options
402 * @return object|bool Database result resource, or false on failure
404 protected function pageData( $dbr, $conditions, $options = [] ) {
405 $pageQuery = self
::getQueryInfo();
407 // Avoid PHP 7.1 warning of passing $this by reference
410 Hooks
::run( 'ArticlePageDataBefore', [
411 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
414 $row = $dbr->selectRow(
415 $pageQuery['tables'],
416 $pageQuery['fields'],
423 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
429 * Fetch a page record matching the Title object's namespace and title
430 * using a sanitized title string
432 * @param IDatabase $dbr
433 * @param Title $title
434 * @param array $options
435 * @return object|bool Database result resource, or false on failure
437 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
438 return $this->pageData( $dbr, [
439 'page_namespace' => $title->getNamespace(),
440 'page_title' => $title->getDBkey() ], $options );
444 * Fetch a page record matching the requested ID
446 * @param IDatabase $dbr
448 * @param array $options
449 * @return object|bool Database result resource, or false on failure
451 public function pageDataFromId( $dbr, $id, $options = [] ) {
452 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
456 * Load the object from a given source by title
458 * @param object|string|int $from One of the following:
459 * - A DB query result object.
460 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
461 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
462 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
463 * using SELECT FOR UPDATE.
467 public function loadPageData( $from = 'fromdb' ) {
468 $from = self
::convertSelectType( $from );
469 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
470 // We already have the data from the correct location, no need to load it twice.
474 if ( is_int( $from ) ) {
475 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
476 $loadBalancer = $this->getDBLoadBalancer();
477 $db = $loadBalancer->getConnection( $index );
478 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
481 && $index == DB_REPLICA
482 && $loadBalancer->getServerCount() > 1
483 && $loadBalancer->hasOrMadeRecentMasterChanges()
485 $from = self
::READ_LATEST
;
486 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
487 $db = $loadBalancer->getConnection( $index );
488 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
491 // No idea from where the caller got this data, assume replica DB.
493 $from = self
::READ_NORMAL
;
496 $this->loadFromRow( $data, $from );
500 * Checks whether the page data was loaded using the given database access mode (or better).
504 * @param string|int $from One of the following:
505 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
506 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
507 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
508 * using SELECT FOR UPDATE.
512 public function wasLoadedFrom( $from ) {
513 $from = self
::convertSelectType( $from );
515 if ( !is_int( $from ) ) {
516 // No idea from where the caller got this data, assume replica DB.
517 $from = self
::READ_NORMAL
;
520 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
528 * Load the object from a database row
531 * @param object|bool $data DB row containing fields returned by selectFields() or false
532 * @param string|int $from One of the following:
533 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
534 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
535 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
536 * the master DB using SELECT FOR UPDATE
538 public function loadFromRow( $data, $from ) {
539 $lc = MediaWikiServices
::getInstance()->getLinkCache();
540 $lc->clearLink( $this->mTitle
);
543 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
545 $this->mTitle
->loadFromRow( $data );
547 // Old-fashioned restrictions
548 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
550 $this->mId
= intval( $data->page_id
);
551 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
552 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
553 $this->mIsRedirect
= intval( $data->page_is_redirect
);
554 $this->mLatest
= intval( $data->page_latest
);
555 // T39225: $latest may no longer match the cached latest Revision object.
556 // Double-check the ID of any cached latest Revision object for consistency.
557 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
558 $this->mLastRevision
= null;
559 $this->mTimestamp
= '';
562 $lc->addBadLinkObj( $this->mTitle
);
564 $this->mTitle
->loadFromRow( false );
566 $this->clearCacheFields();
571 $this->mDataLoaded
= true;
572 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
576 * @return int Page ID
578 public function getId() {
579 if ( !$this->mDataLoaded
) {
580 $this->loadPageData();
586 * @return bool Whether or not the page exists in the database
588 public function exists() {
589 if ( !$this->mDataLoaded
) {
590 $this->loadPageData();
592 return $this->mId
> 0;
596 * Check if this page is something we're going to be showing
597 * some sort of sensible content for. If we return false, page
598 * views (plain action=view) will return an HTTP 404 response,
599 * so spiders and robots can know they're following a bad link.
603 public function hasViewableContent() {
604 return $this->mTitle
->isKnown();
608 * Tests if the article content represents a redirect
612 public function isRedirect() {
613 if ( !$this->mDataLoaded
) {
614 $this->loadPageData();
617 return (bool)$this->mIsRedirect
;
621 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
623 * Will use the revisions actual content model if the page exists,
624 * and the page's default if the page doesn't exist yet.
630 public function getContentModel() {
631 if ( $this->exists() ) {
632 $cache = ObjectCache
::getMainWANInstance();
634 return $cache->getWithSetCallback(
635 $cache->makeKey( 'page-content-model', $this->getLatest() ),
638 $rev = $this->getRevision();
640 // Look at the revision's actual content model
641 return $rev->getContentModel();
643 $title = $this->mTitle
->getPrefixedDBkey();
644 wfWarn( "Page $title exists but has no (visible) revisions!" );
645 return $this->mTitle
->getContentModel();
651 // use the default model for this page
652 return $this->mTitle
->getContentModel();
656 * Loads page_touched and returns a value indicating if it should be used
657 * @return bool True if this page exists and is not a redirect
659 public function checkTouched() {
660 if ( !$this->mDataLoaded
) {
661 $this->loadPageData();
663 return ( $this->mId
&& !$this->mIsRedirect
);
667 * Get the page_touched field
668 * @return string Containing GMT timestamp
670 public function getTouched() {
671 if ( !$this->mDataLoaded
) {
672 $this->loadPageData();
674 return $this->mTouched
;
678 * Get the page_links_updated field
679 * @return string|null Containing GMT timestamp
681 public function getLinksTimestamp() {
682 if ( !$this->mDataLoaded
) {
683 $this->loadPageData();
685 return $this->mLinksUpdated
;
689 * Get the page_latest field
690 * @return int The rev_id of current revision
692 public function getLatest() {
693 if ( !$this->mDataLoaded
) {
694 $this->loadPageData();
696 return (int)$this->mLatest
;
700 * Get the Revision object of the oldest revision
701 * @return Revision|null
703 public function getOldestRevision() {
704 // Try using the replica DB first, then try the master
705 $rev = $this->mTitle
->getFirstRevision();
707 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
713 * Loads everything except the text
714 * This isn't necessary for all uses, so it's only done if needed.
716 protected function loadLastEdit() {
717 if ( $this->mLastRevision
!== null ) {
718 return; // already loaded
721 $latest = $this->getLatest();
723 return; // page doesn't exist or is missing page_latest info
726 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
727 // T39225: if session S1 loads the page row FOR UPDATE, the result always
728 // includes the latest changes committed. This is true even within REPEATABLE-READ
729 // transactions, where S1 normally only sees changes committed before the first S1
730 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
731 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
732 // happened after the first S1 SELECT.
733 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
734 $flags = Revision
::READ_LOCKING
;
735 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
736 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
737 // Bug T93976: if page_latest was loaded from the master, fetch the
738 // revision from there as well, as it may not exist yet on a replica DB.
739 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
740 $flags = Revision
::READ_LATEST
;
741 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
743 $dbr = wfGetDB( DB_REPLICA
);
744 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
747 if ( $revision ) { // sanity
748 $this->setLastEdit( $revision );
753 * Set the latest revision
754 * @param Revision $revision
756 protected function setLastEdit( Revision
$revision ) {
757 $this->mLastRevision
= $revision;
758 $this->mTimestamp
= $revision->getTimestamp();
762 * Get the latest revision
763 * @return Revision|null
765 public function getRevision() {
766 $this->loadLastEdit();
767 if ( $this->mLastRevision
) {
768 return $this->mLastRevision
;
774 * Get the latest revision
775 * @return RevisionRecord|null
777 public function getRevisionRecord() {
778 $this->loadLastEdit();
779 if ( $this->mLastRevision
) {
780 return $this->mLastRevision
->getRevisionRecord();
786 * Get the content of the current revision. No side-effects...
788 * @param int $audience One of:
789 * Revision::FOR_PUBLIC to be displayed to all users
790 * Revision::FOR_THIS_USER to be displayed to $wgUser
791 * Revision::RAW get the text regardless of permissions
792 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
793 * to the $audience parameter
794 * @return Content|null The content of the current revision
798 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
799 $this->loadLastEdit();
800 if ( $this->mLastRevision
) {
801 return $this->mLastRevision
->getContent( $audience, $user );
807 * @return string MW timestamp of last article revision
809 public function getTimestamp() {
810 // Check if the field has been filled by WikiPage::setTimestamp()
811 if ( !$this->mTimestamp
) {
812 $this->loadLastEdit();
815 return wfTimestamp( TS_MW
, $this->mTimestamp
);
819 * Set the page timestamp (use only to avoid DB queries)
820 * @param string $ts MW timestamp of last article revision
823 public function setTimestamp( $ts ) {
824 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
828 * @param int $audience One of:
829 * Revision::FOR_PUBLIC to be displayed to all users
830 * Revision::FOR_THIS_USER to be displayed to the given user
831 * Revision::RAW get the text regardless of permissions
832 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
833 * to the $audience parameter
834 * @return int User ID for the user that made the last article revision
836 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
837 $this->loadLastEdit();
838 if ( $this->mLastRevision
) {
839 return $this->mLastRevision
->getUser( $audience, $user );
846 * Get the User object of the user who created the page
847 * @param int $audience One of:
848 * Revision::FOR_PUBLIC to be displayed to all users
849 * Revision::FOR_THIS_USER to be displayed to the given user
850 * Revision::RAW get the text regardless of permissions
851 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
852 * to the $audience parameter
855 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
856 $revision = $this->getOldestRevision();
858 $userName = $revision->getUserText( $audience, $user );
859 return User
::newFromName( $userName, false );
866 * @param int $audience One of:
867 * Revision::FOR_PUBLIC to be displayed to all users
868 * Revision::FOR_THIS_USER to be displayed to the given user
869 * Revision::RAW get the text regardless of permissions
870 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
871 * to the $audience parameter
872 * @return string Username of the user that made the last article revision
874 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
875 $this->loadLastEdit();
876 if ( $this->mLastRevision
) {
877 return $this->mLastRevision
->getUserText( $audience, $user );
884 * @param int $audience One of:
885 * Revision::FOR_PUBLIC to be displayed to all users
886 * Revision::FOR_THIS_USER to be displayed to the given user
887 * Revision::RAW get the text regardless of permissions
888 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
889 * to the $audience parameter
890 * @return string Comment stored for the last article revision
892 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
893 $this->loadLastEdit();
894 if ( $this->mLastRevision
) {
895 return $this->mLastRevision
->getComment( $audience, $user );
902 * Returns true if last revision was marked as "minor edit"
904 * @return bool Minor edit indicator for the last article revision.
906 public function getMinorEdit() {
907 $this->loadLastEdit();
908 if ( $this->mLastRevision
) {
909 return $this->mLastRevision
->isMinor();
916 * Determine whether a page would be suitable for being counted as an
917 * article in the site_stats table based on the title & its content
919 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
920 * if false, the current database state will be used
923 public function isCountable( $editInfo = false ) {
924 global $wgArticleCountMethod;
926 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
928 if ( !$this->mTitle
->isContentPage() ) {
933 // NOTE: only the main slot can make a page a redirect
934 $content = $editInfo->pstContent
;
936 $content = $this->getContent();
939 if ( !$content ||
$content->isRedirect() ) {
945 if ( $wgArticleCountMethod === 'link' ) {
946 // nasty special case to avoid re-parsing to detect links
949 // ParserOutput::getLinks() is a 2D array of page links, so
950 // to be really correct we would need to recurse in the array
951 // but the main array should only have items in it if there are
953 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
955 // NOTE: keep in sync with revisionRenderer::getLinkCount
956 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
957 [ 'pl_from' => $this->getId() ], __METHOD__
);
961 return $content->isCountable( $hasLinks );
965 * If this page is a redirect, get its target
967 * The target will be fetched from the redirect table if possible.
968 * If this page doesn't have an entry there, call insertRedirect()
969 * @return Title|null Title object, or null if this page is not a redirect
971 public function getRedirectTarget() {
972 if ( !$this->mTitle
->isRedirect() ) {
976 if ( $this->mRedirectTarget
!== null ) {
977 return $this->mRedirectTarget
;
980 // Query the redirect table
981 $dbr = wfGetDB( DB_REPLICA
);
982 $row = $dbr->selectRow( 'redirect',
983 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
984 [ 'rd_from' => $this->getId() ],
988 // rd_fragment and rd_interwiki were added later, populate them if empty
989 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
990 // (T203942) We can't redirect to Media namespace because it's virtual.
991 // We don't want to modify Title objects farther down the
992 // line. So, let's fix this here by changing to File namespace.
993 if ( $row->rd_namespace
== NS_MEDIA
) {
994 $namespace = NS_FILE
;
996 $namespace = $row->rd_namespace
;
998 $this->mRedirectTarget
= Title
::makeTitle(
999 $namespace, $row->rd_title
,
1000 $row->rd_fragment
, $row->rd_interwiki
1002 return $this->mRedirectTarget
;
1005 // This page doesn't have an entry in the redirect table
1006 $this->mRedirectTarget
= $this->insertRedirect();
1007 return $this->mRedirectTarget
;
1011 * Insert an entry for this page into the redirect table if the content is a redirect
1013 * The database update will be deferred via DeferredUpdates
1015 * Don't call this function directly unless you know what you're doing.
1016 * @return Title|null Title object or null if not a redirect
1018 public function insertRedirect() {
1019 $content = $this->getContent();
1020 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1025 // Update the DB post-send if the page has not cached since now
1026 $latest = $this->getLatest();
1027 DeferredUpdates
::addCallableUpdate(
1028 function () use ( $retval, $latest ) {
1029 $this->insertRedirectEntry( $retval, $latest );
1031 DeferredUpdates
::POSTSEND
,
1032 wfGetDB( DB_MASTER
)
1039 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1040 * @param Title $rt Redirect target
1041 * @param int|null $oldLatest Prior page_latest for check and set
1043 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1044 $dbw = wfGetDB( DB_MASTER
);
1045 $dbw->startAtomic( __METHOD__
);
1047 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1048 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1049 $truncatedFragment = $contLang->truncateForDatabase( $rt->getFragment(), 255 );
1053 'rd_from' => $this->getId(),
1054 'rd_namespace' => $rt->getNamespace(),
1055 'rd_title' => $rt->getDBkey(),
1056 'rd_fragment' => $truncatedFragment,
1057 'rd_interwiki' => $rt->getInterwiki(),
1061 'rd_namespace' => $rt->getNamespace(),
1062 'rd_title' => $rt->getDBkey(),
1063 'rd_fragment' => $truncatedFragment,
1064 'rd_interwiki' => $rt->getInterwiki(),
1070 $dbw->endAtomic( __METHOD__
);
1074 * Get the Title object or URL this page redirects to
1076 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1078 public function followRedirect() {
1079 return $this->getRedirectURL( $this->getRedirectTarget() );
1083 * Get the Title object or URL to use for a redirect. We use Title
1084 * objects for same-wiki, non-special redirects and URLs for everything
1086 * @param Title $rt Redirect target
1087 * @return bool|Title|string False, Title object of local target, or string with URL
1089 public function getRedirectURL( $rt ) {
1094 if ( $rt->isExternal() ) {
1095 if ( $rt->isLocal() ) {
1096 // Offsite wikis need an HTTP redirect.
1097 // This can be hard to reverse and may produce loops,
1098 // so they may be disabled in the site configuration.
1099 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1100 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1102 // External pages without "local" bit set are not valid
1108 if ( $rt->isSpecialPage() ) {
1109 // Gotta handle redirects to special pages differently:
1110 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1111 // Some pages are not valid targets.
1112 if ( $rt->isValidRedirectTarget() ) {
1113 return $rt->getFullURL();
1123 * Get a list of users who have edited this article, not including the user who made
1124 * the most recent revision, which you can get from $article->getUser() if you want it
1125 * @return UserArrayFromResult
1127 public function getContributors() {
1128 // @todo: This is expensive; cache this info somewhere.
1130 $dbr = wfGetDB( DB_REPLICA
);
1132 $actorMigration = ActorMigration
::newMigration();
1133 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1135 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1138 'user_id' => $actorQuery['fields']['rev_user'],
1139 'user_name' => $actorQuery['fields']['rev_user_text'],
1140 'actor_id' => $actorQuery['fields']['rev_actor'],
1141 'user_real_name' => 'MIN(user_real_name)',
1142 'timestamp' => 'MAX(rev_timestamp)',
1145 $conds = [ 'rev_page' => $this->getId() ];
1147 // The user who made the top revision gets credited as "this page was last edited by
1148 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1149 $user = $this->getUser()
1150 ? User
::newFromId( $this->getUser() )
1151 : User
::newFromName( $this->getUserText(), false );
1152 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1155 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1158 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1159 ] +
$actorQuery['joins'];
1162 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1163 'ORDER BY' => 'timestamp DESC',
1166 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1167 return new UserArrayFromResult( $res );
1171 * Should the parser cache be used?
1173 * @param ParserOptions $parserOptions ParserOptions to check
1177 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1178 return $parserOptions->getStubThreshold() == 0
1180 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1181 && $this->getContentHandler()->isParserCacheSupported();
1185 * Get a ParserOutput for the given ParserOptions and revision ID.
1187 * The parser cache will be used if possible. Cache misses that result
1188 * in parser runs are debounced with PoolCounter.
1190 * XXX merge this with updateParserCache()?
1193 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1194 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1195 * get the current revision (default value)
1196 * @param bool $forceParse Force reindexing, regardless of cache settings
1197 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1199 public function getParserOutput(
1200 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1203 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1205 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1206 throw new InvalidArgumentException(
1207 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1211 wfDebug( __METHOD__
.
1212 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1213 if ( $parserOptions->getStubThreshold() ) {
1214 wfIncrStats( 'pcache.miss.stub' );
1217 if ( $useParserCache ) {
1218 $parserOutput = $this->getParserCache()
1219 ->get( $this, $parserOptions );
1220 if ( $parserOutput !== false ) {
1221 return $parserOutput;
1225 if ( $oldid === null ||
$oldid === 0 ) {
1226 $oldid = $this->getLatest();
1229 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1232 return $pool->getParserOutput();
1236 * Do standard deferred updates after page view (existing or missing page)
1237 * @param User $user The relevant user
1238 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1240 public function doViewUpdates( User
$user, $oldid = 0 ) {
1241 if ( wfReadOnly() ) {
1245 // Update newtalk / watchlist notification status;
1246 // Avoid outage if the master is not reachable by using a deferred updated
1247 DeferredUpdates
::addCallableUpdate(
1248 function () use ( $user, $oldid ) {
1249 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1251 $user->clearNotification( $this->mTitle
, $oldid );
1253 DeferredUpdates
::PRESEND
1258 * Perform the actions of a page purging
1260 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1261 * controlled how much purging was done.
1263 public function doPurge() {
1264 // Avoid PHP 7.1 warning of passing $this by reference
1267 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1271 $this->mTitle
->invalidateCache();
1274 HTMLFileCache
::clearFileCache( $this->getTitle() );
1275 // Send purge after above page_touched update was committed
1276 DeferredUpdates
::addUpdate(
1277 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1278 DeferredUpdates
::PRESEND
1281 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1282 $messageCache = MessageCache
::singleton();
1283 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1290 * Insert a new empty page record for this article.
1291 * This *must* be followed up by creating a revision
1292 * and running $this->updateRevisionOn( ... );
1293 * or else the record will be left in a funky state.
1294 * Best if all done inside a transaction.
1296 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1298 * @param IDatabase $dbw
1299 * @param int|null $pageId Custom page ID that will be used for the insert statement
1301 * @return bool|int The newly created page_id key; false if the row was not
1302 * inserted, e.g. because the title already existed or because the specified
1303 * page ID is already in use.
1305 public function insertOn( $dbw, $pageId = null ) {
1306 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1310 'page_namespace' => $this->mTitle
->getNamespace(),
1311 'page_title' => $this->mTitle
->getDBkey(),
1312 'page_restrictions' => '',
1313 'page_is_redirect' => 0, // Will set this shortly...
1315 'page_random' => wfRandom(),
1316 'page_touched' => $dbw->timestamp(),
1317 'page_latest' => 0, // Fill this in shortly...
1318 'page_len' => 0, // Fill this in shortly...
1319 ] +
$pageIdForInsert,
1324 if ( $dbw->affectedRows() > 0 ) {
1325 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1326 $this->mId
= $newid;
1327 $this->mTitle
->resetArticleID( $newid );
1331 return false; // nothing changed
1336 * Update the page record to point to a newly saved revision.
1338 * @todo Factor out into a PageStore service, or move into PageUpdater.
1340 * @param IDatabase $dbw
1341 * @param Revision $revision For ID number, and text used to set
1342 * length and redirect status fields
1343 * @param int|null $lastRevision If given, will not overwrite the page field
1344 * when different from the currently set value.
1345 * Giving 0 indicates the new page flag should be set on.
1346 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1347 * removing rows in redirect table.
1348 * @return bool Success; false if the page row was missing or page_latest changed
1350 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1351 $lastRevIsRedirect = null
1353 global $wgContentHandlerUseDB;
1355 // TODO: move into PageUpdater or PageStore
1356 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1357 // and in the compat stub!
1359 // Assertion to try to catch T92046
1360 if ( (int)$revision->getId() === 0 ) {
1361 throw new InvalidArgumentException(
1362 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1366 $content = $revision->getContent();
1367 $len = $content ?
$content->getSize() : 0;
1368 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1370 $conditions = [ 'page_id' => $this->getId() ];
1372 if ( !is_null( $lastRevision ) ) {
1373 // An extra check against threads stepping on each other
1374 $conditions['page_latest'] = $lastRevision;
1377 $revId = $revision->getId();
1378 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1381 'page_latest' => $revId,
1382 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1383 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1384 'page_is_redirect' => $rt !== null ?
1 : 0,
1388 if ( $wgContentHandlerUseDB ) {
1389 $row['page_content_model'] = $revision->getContentModel();
1392 $dbw->update( 'page',
1397 $result = $dbw->affectedRows() > 0;
1399 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1400 $this->setLastEdit( $revision );
1401 $this->mLatest
= $revision->getId();
1402 $this->mIsRedirect
= (bool)$rt;
1403 // Update the LinkCache.
1404 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1405 $linkCache->addGoodLinkObj(
1411 $revision->getContentModel()
1419 * Add row to the redirect table if this is a redirect, remove otherwise.
1421 * @param IDatabase $dbw
1422 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1423 * or NULL if this is not a redirect
1424 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1425 * removing rows in redirect table.
1426 * @return bool True on success, false on failure
1429 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1430 // Always update redirects (target link might have changed)
1431 // Update/Insert if we don't know if the last revision was a redirect or not
1432 // Delete if changing from redirect to non-redirect
1433 $isRedirect = !is_null( $redirectTitle );
1435 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1439 if ( $isRedirect ) {
1440 $this->insertRedirectEntry( $redirectTitle );
1442 // This is not a redirect, remove row from redirect table
1443 $where = [ 'rd_from' => $this->getId() ];
1444 $dbw->delete( 'redirect', $where, __METHOD__
);
1447 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1448 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1451 return ( $dbw->affectedRows() != 0 );
1455 * If the given revision is newer than the currently set page_latest,
1456 * update the page record. Otherwise, do nothing.
1458 * @deprecated since 1.24, use updateRevisionOn instead
1460 * @param IDatabase $dbw
1461 * @param Revision $revision
1464 public function updateIfNewerOn( $dbw, $revision ) {
1465 $row = $dbw->selectRow(
1466 [ 'revision', 'page' ],
1467 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1469 'page_id' => $this->getId(),
1470 'page_latest=rev_id' ],
1474 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1477 $prev = $row->rev_id
;
1478 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1480 // No or missing previous revision; mark the page as new
1482 $lastRevIsRedirect = null;
1485 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1491 * Helper method for checking whether two revisions have differences that go
1492 * beyond the main slot.
1494 * MCR migration note: this method should go away!
1496 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1498 * @param Revision $a
1499 * @param Revision $b
1502 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1503 $aSlots = $a->getRevisionRecord()->getSlots();
1504 $bSlots = $b->getRevisionRecord()->getSlots();
1505 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1507 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1511 * Get the content that needs to be saved in order to undo all revisions
1512 * between $undo and $undoafter. Revisions must belong to the same page,
1513 * must exist and must not be deleted
1515 * @param Revision $undo
1516 * @param Revision $undoafter Must be an earlier revision than $undo
1517 * @return Content|bool Content on success, false on failure
1519 * Before we had the Content object, this was done in getUndoText
1521 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1522 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1524 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1525 // Cannot yet undo edits that involve anything other the main slot.
1529 $handler = $undo->getContentHandler();
1530 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1534 * Returns true if this page's content model supports sections.
1538 * @todo The skin should check this and not offer section functionality if
1539 * sections are not supported.
1540 * @todo The EditPage should check this and not offer section functionality
1541 * if sections are not supported.
1543 public function supportsSections() {
1544 return $this->getContentHandler()->supportsSections();
1548 * @param string|int|null|bool $sectionId Section identifier as a number or string
1549 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1550 * or 'new' for a new section.
1551 * @param Content $sectionContent New content of the section.
1552 * @param string $sectionTitle New section's subject, only if $section is "new".
1553 * @param string $edittime Revision timestamp or null to use the current revision.
1555 * @throws MWException
1556 * @return Content|null New complete article content, or null if error.
1559 * @deprecated since 1.24, use replaceSectionAtRev instead
1561 public function replaceSectionContent(
1562 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1565 if ( $edittime && $sectionId !== 'new' ) {
1566 $lb = $this->getDBLoadBalancer();
1567 $dbr = $lb->getConnection( DB_REPLICA
);
1568 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1569 // Try the master if this thread may have just added it.
1570 // This could be abstracted into a Revision method, but we don't want
1571 // to encourage loading of revisions by timestamp.
1573 && $lb->getServerCount() > 1
1574 && $lb->hasOrMadeRecentMasterChanges()
1576 $dbw = $lb->getConnection( DB_MASTER
);
1577 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1580 $baseRevId = $rev->getId();
1584 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1588 * @param string|int|null|bool $sectionId Section identifier as a number or string
1589 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1590 * or 'new' for a new section.
1591 * @param Content $sectionContent New content of the section.
1592 * @param string $sectionTitle New section's subject, only if $section is "new".
1593 * @param int|null $baseRevId
1595 * @throws MWException
1596 * @return Content|null New complete article content, or null if error.
1600 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1601 $sectionTitle = '', $baseRevId = null
1603 if ( strval( $sectionId ) === '' ) {
1604 // Whole-page edit; let the whole text through
1605 $newContent = $sectionContent;
1607 if ( !$this->supportsSections() ) {
1608 throw new MWException( "sections not supported for content model " .
1609 $this->getContentHandler()->getModelID() );
1612 // T32711: always use current version when adding a new section
1613 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1614 $oldContent = $this->getContent();
1616 $rev = Revision
::newFromId( $baseRevId );
1618 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1619 $this->getId() . "; section: $sectionId)\n" );
1623 $oldContent = $rev->getContent();
1626 if ( !$oldContent ) {
1627 wfDebug( __METHOD__
. ": no page text\n" );
1631 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1638 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1640 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1641 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1644 * @return int Updated $flags
1646 public function checkFlags( $flags ) {
1647 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1648 if ( $this->exists() ) {
1649 $flags |
= EDIT_UPDATE
;
1659 * @return DerivedPageDataUpdater
1661 private function newDerivedDataUpdater() {
1662 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1664 $derivedDataUpdater = new DerivedPageDataUpdater(
1665 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1666 $this->getRevisionStore(),
1667 $this->getRevisionRenderer(),
1668 $this->getParserCache(),
1669 JobQueueGroup
::singleton(),
1670 MessageCache
::singleton(),
1671 MediaWikiServices
::getInstance()->getContentLanguage(),
1672 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1675 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1676 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1678 return $derivedDataUpdater;
1682 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1683 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1684 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1685 * returned matches that caller's expectations, allowing an existing instance to be re-used
1686 * if the given parameters match that instance's internal state according to
1687 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1688 * match the existign one.
1690 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1691 * created, replacing any DerivedPageDataUpdater currently cached.
1693 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1697 * @param User|null $forUser The user that will be used for, or was used for, PST.
1698 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1699 * to perform updates, if the edit was already saved.
1700 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1701 * if the edit was not yet saved.
1702 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1703 * revision as the edit's parent revision. This ensures that the same
1704 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1706 * @return DerivedPageDataUpdater
1708 private function getDerivedDataUpdater(
1709 User
$forUser = null,
1710 RevisionRecord
$forRevision = null,
1711 RevisionSlotsUpdate
$forUpdate = null,
1714 if ( !$forRevision && !$forUpdate ) {
1715 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1716 // going to use it with.
1717 $this->derivedDataUpdater
= null;
1720 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1721 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1722 // to it did not yet initialize it, because we don't know what data it will be
1723 // initialized with.
1724 $this->derivedDataUpdater
= null;
1727 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1728 // However, there is no good way to construct a cache key. We'd need to check against all
1729 // cached instances.
1731 if ( $this->derivedDataUpdater
1732 && !$this->derivedDataUpdater
->isReusableFor(
1736 $forEdit ?
$this->getLatest() : null
1739 $this->derivedDataUpdater
= null;
1742 if ( !$this->derivedDataUpdater
) {
1743 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1746 return $this->derivedDataUpdater
;
1750 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1752 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1753 * and to protected such conflict resolution from concurrent edits using a check-and-set
1759 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1760 * that may already have been returned via getDerivedDataUpdater to be re-used.
1762 * @return PageUpdater
1764 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1765 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1767 $pageUpdater = new PageUpdater(
1769 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1770 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1771 $this->getDBLoadBalancer(),
1772 $this->getRevisionStore()
1775 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1776 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1777 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1779 return $pageUpdater;
1783 * Change an existing article or create a new article. Updates RC and all necessary caches,
1784 * optionally via the deferred update array.
1786 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1787 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1788 * apply the autopatrol right as appropriate.
1790 * @param Content $content New content
1791 * @param string|CommentStoreComment $summary Edit summary
1792 * @param int $flags Bitfield:
1794 * Article is known or assumed to be non-existent, create a new one
1796 * Article is known or assumed to be pre-existing, update it
1798 * Mark this edit minor, if the user is allowed to do so
1800 * Do not log the change in recentchanges
1802 * Mark the edit a "bot" edit regardless of user rights
1804 * Fill in blank summaries with generated text where possible
1806 * Signal that the page retrieve/save cycle happened entirely in this request.
1808 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1809 * article will be detected. If EDIT_UPDATE is specified and the article
1810 * doesn't exist, the function will return an edit-gone-missing error. If
1811 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1812 * error will be returned. These two conditions are also possible with
1813 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1815 * @param bool|int $originalRevId: The ID of an original revision that the edit
1816 * restores or repeats. The new revision is expected to have the exact same content as
1817 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1818 * which are created to record things like page moves.
1819 * @param User|null $user The user doing the edit
1820 * @param string|null $serialFormat IGNORED.
1821 * @param array|null $tags Change tags to apply to this edit
1822 * Callers are responsible for permission checks
1823 * (with ChangeTags::canAddTagsAccompanyingChange)
1824 * @param Int $undidRevId Id of revision that was undone or 0
1826 * @throws MWException
1827 * @return Status Possible errors:
1828 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1829 * set the fatal flag of $status.
1830 * edit-gone-missing: In update mode, but the article didn't exist.
1831 * edit-conflict: In update mode, the article changed unexpectedly.
1832 * edit-no-change: Warning that the text was the same as before.
1833 * edit-already-exists: In creation mode, but the article already exists.
1835 * Extensions may define additional errors.
1837 * $return->value will contain an associative array with members as follows:
1838 * new: Boolean indicating if the function attempted to create a new article.
1839 * revision: The revision object for the inserted revision, or null.
1842 * @throws MWException
1844 public function doEditContent(
1845 Content
$content, $summary, $flags = 0, $originalRevId = false,
1846 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1848 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1850 if ( !( $summary instanceof CommentStoreComment
) ) {
1851 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1858 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1859 // Checking the minoredit right should be done in the same place the 'bot' right is
1860 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1861 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1862 $flags = ( $flags & ~EDIT_MINOR
);
1865 $slotsUpdate = new RevisionSlotsUpdate();
1866 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1868 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1869 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1870 // used by this PageUpdater. However, there is no guarantee for this.
1871 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1872 $updater->setContent( SlotRecord
::MAIN
, $content );
1873 $updater->setOriginalRevisionId( $originalRevId );
1874 $updater->setUndidRevisionId( $undidRevId );
1876 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1878 // TODO: this logic should not be in the storage layer, it's here for compatibility
1879 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1880 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1881 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1882 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1885 $updater->addTags( $tags );
1887 $revRec = $updater->saveRevision(
1892 // $revRec will be null if the edit failed, or if no new revision was created because
1893 // the content did not change.
1895 // update cached fields
1896 // TODO: this is currently redundant to what is done in updateRevisionOn.
1897 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1898 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1899 $this->mLatest
= $revRec->getId();
1902 return $updater->getStatus();
1906 * Get parser options suitable for rendering the primary article wikitext
1908 * @see ParserOptions::newCanonical
1910 * @param IContextSource|User|string $context One of the following:
1911 * - IContextSource: Use the User and the Language of the provided
1913 * - User: Use the provided User object and $wgLang for the language,
1914 * so use an IContextSource object if possible.
1915 * - 'canonical': Canonical options (anonymous user with default
1916 * preferences and content language).
1917 * @return ParserOptions
1919 public function makeParserOptions( $context ) {
1920 $options = ParserOptions
::newCanonical( $context );
1922 if ( $this->getTitle()->isConversionTable() ) {
1923 // @todo ConversionTable should become a separate content model, so
1924 // we don't need special cases like this one.
1925 $options->disableContentConversion();
1932 * Prepare content which is about to be saved.
1934 * Prior to 1.30, this returned a stdClass.
1936 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1938 * @param Content $content
1939 * @param Revision|RevisionRecord|int|null $revision Revision object.
1940 * For backwards compatibility, a revision ID is also accepted,
1941 * but this is deprecated.
1942 * Used with vary-revision or vary-revision-id.
1943 * @param User|null $user
1944 * @param string|null $serialFormat IGNORED
1945 * @param bool $useCache Check shared prepared edit cache
1947 * @return PreparedEdit
1951 public function prepareContentForEdit(
1955 $serialFormat = null,
1964 if ( !is_object( $revision ) ) {
1966 // This code path is deprecated, and nothing is known to
1967 // use it, so performance here shouldn't be a worry.
1968 if ( $revid !== null ) {
1969 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1970 $store = $this->getRevisionStore();
1971 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1975 } elseif ( $revision instanceof Revision
) {
1976 $revision = $revision->getRevisionRecord();
1979 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
1980 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1982 if ( !$updater->isUpdatePrepared() ) {
1983 $updater->prepareContent( $user, $slots, $useCache );
1986 $updater->prepareUpdate(
1989 'causeAction' => 'prepare-edit',
1990 'causeAgent' => $user->getName(),
1996 return $updater->getPreparedEdit();
2000 * Do standard deferred updates after page edit.
2001 * Update links tables, site stats, search index and message cache.
2002 * Purges pages that include this page if the text was changed here.
2003 * Every 100th edit, prune the recent changes table.
2005 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2007 * @param Revision $revision
2008 * @param User $user User object that did the revision
2009 * @param array $options Array of options, following indexes are used:
2010 * - changed: bool, whether the revision changed the content (default true)
2011 * - created: bool, whether the revision created the page (default false)
2012 * - moved: bool, whether the page was moved (default false)
2013 * - restored: bool, whether the page was undeleted (default false)
2014 * - oldrevision: Revision object for the pre-update revision (default null)
2015 * - oldcountable: bool, null, or string 'no-change' (default null):
2016 * - bool: whether the page was counted as an article before that
2017 * revision, only used in changed is true and created is false
2018 * - null: if created is false, don't update the article count; if created
2019 * is true, do update the article count
2020 * - 'no-change': don't update the article count, ever
2021 * - causeAction: an arbitrary string identifying the reason for the update.
2022 * See DataUpdate::getCauseAction(). (default 'edit-page')
2023 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2024 * (string, defaults to the passed user)
2026 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2028 'causeAction' => 'edit-page',
2029 'causeAgent' => $user->getName(),
2032 $revision = $revision->getRevisionRecord();
2034 $updater = $this->getDerivedDataUpdater( $user, $revision );
2036 $updater->prepareUpdate( $revision, $options );
2038 $updater->doUpdates();
2042 * Update the parser cache.
2044 * @note This is a temporary workaround until there is a proper data updater class.
2045 * It will become deprecated soon.
2047 * @param array $options
2048 * - causeAction: an arbitrary string identifying the reason for the update.
2049 * See DataUpdate::getCauseAction(). (default 'edit-page')
2050 * - causeAgent: name of the user who caused the update (string, defaults to the
2051 * user who created the revision)
2054 public function updateParserCache( array $options = [] ) {
2055 $revision = $this->getRevisionRecord();
2056 if ( !$revision ||
!$revision->getId() ) {
2057 LoggerFactory
::getInstance( 'wikipage' )->info(
2058 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2062 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2064 $updater = $this->getDerivedDataUpdater( $user, $revision );
2065 $updater->prepareUpdate( $revision, $options );
2066 $updater->doParserCacheUpdate();
2070 * Do secondary data updates (such as updating link tables).
2071 * Secondary data updates are only a small part of the updates needed after saving
2072 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2073 * secondary data updates). This method is provided for partial purges.
2075 * @note This is a temporary workaround until there is a proper data updater class.
2076 * It will become deprecated soon.
2078 * @param array $options
2079 * - recursive (bool, default true): whether to do a recursive update (update pages that
2080 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2081 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2082 * was something that did not really change the page, such as a null edit.
2083 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2084 * user who created the revision)
2085 * - causeAction: an arbitrary string identifying the reason for the update.
2086 * See DataUpdate::getCauseAction(). (default 'unknown')
2087 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2088 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2089 * Note that even when this is set to false, some updates might still get deferred (as
2090 * some update might directly add child updates to DeferredUpdates).
2091 * - transactionTicket: a transaction ticket from LBFactory::getEmptyTransactionTicket(),
2092 * only when defer is false (default: null)
2095 public function doSecondaryDataUpdates( array $options = [] ) {
2096 $options['recursive'] = $options['recursive'] ??
true;
2097 $revision = $this->getRevisionRecord();
2098 if ( !$revision ||
!$revision->getId() ) {
2099 LoggerFactory
::getInstance( 'wikipage' )->info(
2100 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2104 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2106 $updater = $this->getDerivedDataUpdater( $user, $revision );
2107 $updater->prepareUpdate( $revision, $options );
2108 $updater->doSecondaryDataUpdates( $options );
2112 * Update the article's restriction field, and leave a log entry.
2113 * This works for protection both existing and non-existing pages.
2115 * @param array $limit Set of restriction keys
2116 * @param array $expiry Per restriction type expiration
2117 * @param int &$cascade Set to false if cascading protection isn't allowed.
2118 * @param string $reason
2119 * @param User $user The user updating the restrictions
2120 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2121 * ($user should be able to add the specified tags before this is called)
2122 * @return Status Status object; if action is taken, $status->value is the log_id of the
2123 * protection log entry.
2125 public function doUpdateRestrictions( array $limit, array $expiry,
2126 &$cascade, $reason, User
$user, $tags = null
2128 global $wgCascadingRestrictionLevels;
2130 if ( wfReadOnly() ) {
2131 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2134 $this->loadPageData( 'fromdbmaster' );
2135 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2136 $id = $this->getId();
2142 // Take this opportunity to purge out expired restrictions
2143 Title
::purgeExpiredRestrictions();
2145 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2146 // we expect a single selection, but the schema allows otherwise.
2147 $isProtected = false;
2151 $dbw = wfGetDB( DB_MASTER
);
2153 foreach ( $restrictionTypes as $action ) {
2154 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2155 $expiry[$action] = 'infinity';
2157 if ( !isset( $limit[$action] ) ) {
2158 $limit[$action] = '';
2159 } elseif ( $limit[$action] != '' ) {
2163 // Get current restrictions on $action
2164 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2165 if ( $current != '' ) {
2166 $isProtected = true;
2169 if ( $limit[$action] != $current ) {
2171 } elseif ( $limit[$action] != '' ) {
2172 // Only check expiry change if the action is actually being
2173 // protected, since expiry does nothing on an not-protected
2175 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2181 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2185 // If nothing has changed, do nothing
2187 return Status
::newGood();
2190 if ( !$protect ) { // No protection at all means unprotection
2191 $revCommentMsg = 'unprotectedarticle-comment';
2192 $logAction = 'unprotect';
2193 } elseif ( $isProtected ) {
2194 $revCommentMsg = 'modifiedarticleprotection-comment';
2195 $logAction = 'modify';
2197 $revCommentMsg = 'protectedarticle-comment';
2198 $logAction = 'protect';
2201 $logRelationsValues = [];
2202 $logRelationsField = null;
2203 $logParamsDetails = [];
2205 // Null revision (used for change tag insertion)
2206 $nullRevision = null;
2208 if ( $id ) { // Protection of existing page
2209 // Avoid PHP 7.1 warning of passing $this by reference
2212 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2213 return Status
::newGood();
2216 // Only certain restrictions can cascade...
2217 $editrestriction = isset( $limit['edit'] )
2218 ?
[ $limit['edit'] ]
2219 : $this->mTitle
->getRestrictions( 'edit' );
2220 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2221 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2223 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2224 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2227 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2228 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2229 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2231 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2232 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2235 // The schema allows multiple restrictions
2236 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2240 // insert null revision to identify the page protection change as edit summary
2241 $latest = $this->getLatest();
2242 $nullRevision = $this->insertProtectNullRevision(
2251 if ( $nullRevision === null ) {
2252 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2255 $logRelationsField = 'pr_id';
2257 // Update restrictions table
2258 foreach ( $limit as $action => $restrictions ) {
2260 'page_restrictions',
2263 'pr_type' => $action
2267 if ( $restrictions != '' ) {
2268 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2270 'page_restrictions',
2273 'pr_type' => $action,
2274 'pr_level' => $restrictions,
2275 'pr_cascade' => $cascadeValue,
2276 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2280 $logRelationsValues[] = $dbw->insertId();
2281 $logParamsDetails[] = [
2283 'level' => $restrictions,
2284 'expiry' => $expiry[$action],
2285 'cascade' => (bool)$cascadeValue,
2290 // Clear out legacy restriction fields
2293 [ 'page_restrictions' => '' ],
2294 [ 'page_id' => $id ],
2298 // Avoid PHP 7.1 warning of passing $this by reference
2301 Hooks
::run( 'NewRevisionFromEditComplete',
2302 [ $this, $nullRevision, $latest, $user ] );
2303 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2304 } else { // Protection of non-existing page (also known as "title protection")
2305 // Cascade protection is meaningless in this case
2308 if ( $limit['create'] != '' ) {
2309 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2310 $dbw->replace( 'protected_titles',
2311 [ [ 'pt_namespace', 'pt_title' ] ],
2313 'pt_namespace' => $this->mTitle
->getNamespace(),
2314 'pt_title' => $this->mTitle
->getDBkey(),
2315 'pt_create_perm' => $limit['create'],
2316 'pt_timestamp' => $dbw->timestamp(),
2317 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2318 'pt_user' => $user->getId(),
2319 ] +
$commentFields, __METHOD__
2321 $logParamsDetails[] = [
2323 'level' => $limit['create'],
2324 'expiry' => $expiry['create'],
2327 $dbw->delete( 'protected_titles',
2329 'pt_namespace' => $this->mTitle
->getNamespace(),
2330 'pt_title' => $this->mTitle
->getDBkey()
2336 $this->mTitle
->flushRestrictions();
2337 InfoAction
::invalidateCache( $this->mTitle
);
2339 if ( $logAction == 'unprotect' ) {
2342 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2344 '4::description' => $protectDescriptionLog, // parameter for IRC
2345 '5:bool:cascade' => $cascade,
2346 'details' => $logParamsDetails, // parameter for localize and api
2350 // Update the protection log
2351 $logEntry = new ManualLogEntry( 'protect', $logAction );
2352 $logEntry->setTarget( $this->mTitle
);
2353 $logEntry->setComment( $reason );
2354 $logEntry->setPerformer( $user );
2355 $logEntry->setParameters( $params );
2356 if ( !is_null( $nullRevision ) ) {
2357 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2359 $logEntry->setTags( $tags );
2360 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2361 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2363 $logId = $logEntry->insert();
2364 $logEntry->publish( $logId );
2366 return Status
::newGood( $logId );
2370 * Insert a new null revision for this page.
2372 * @param string $revCommentMsg Comment message key for the revision
2373 * @param array $limit Set of restriction keys
2374 * @param array $expiry Per restriction type expiration
2375 * @param int $cascade Set to false if cascading protection isn't allowed.
2376 * @param string $reason
2377 * @param User|null $user
2378 * @return Revision|null Null on error
2380 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2381 array $expiry, $cascade, $reason, $user = null
2383 $dbw = wfGetDB( DB_MASTER
);
2385 // Prepare a null revision to be added to the history
2386 $editComment = wfMessage(
2388 $this->mTitle
->getPrefixedText(),
2389 $user ?
$user->getName() : ''
2390 )->inContentLanguage()->text();
2392 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2394 $protectDescription = $this->protectDescription( $limit, $expiry );
2395 if ( $protectDescription ) {
2396 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2397 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2398 ->inContentLanguage()->text();
2401 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2402 $editComment .= wfMessage( 'brackets' )->params(
2403 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2404 )->inContentLanguage()->text();
2407 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2409 $nullRev->insertOn( $dbw );
2411 // Update page record and touch page
2412 $oldLatest = $nullRev->getParentId();
2413 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2420 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2423 protected function formatExpiry( $expiry ) {
2424 if ( $expiry != 'infinity' ) {
2425 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2428 $contLang->timeanddate( $expiry, false, false ),
2429 $contLang->date( $expiry, false, false ),
2430 $contLang->time( $expiry, false, false )
2431 )->inContentLanguage()->text();
2433 return wfMessage( 'protect-expiry-indefinite' )
2434 ->inContentLanguage()->text();
2439 * Builds the description to serve as comment for the edit.
2441 * @param array $limit Set of restriction keys
2442 * @param array $expiry Per restriction type expiration
2445 public function protectDescription( array $limit, array $expiry ) {
2446 $protectDescription = '';
2448 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2449 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2450 # All possible message keys are listed here for easier grepping:
2451 # * restriction-create
2452 # * restriction-edit
2453 # * restriction-move
2454 # * restriction-upload
2455 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2456 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2457 # with '' filtered out. All possible message keys are listed below:
2458 # * protect-level-autoconfirmed
2459 # * protect-level-sysop
2460 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2461 ->inContentLanguage()->text();
2463 $expiryText = $this->formatExpiry( $expiry[$action] );
2465 if ( $protectDescription !== '' ) {
2466 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2468 $protectDescription .= wfMessage( 'protect-summary-desc' )
2469 ->params( $actionText, $restrictionsText, $expiryText )
2470 ->inContentLanguage()->text();
2473 return $protectDescription;
2477 * Builds the description to serve as comment for the log entry.
2479 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2480 * protect description text. Keep them in old format to avoid breaking compatibility.
2481 * TODO: Fix protection log to store structured description and format it on-the-fly.
2483 * @param array $limit Set of restriction keys
2484 * @param array $expiry Per restriction type expiration
2487 public function protectDescriptionLog( array $limit, array $expiry ) {
2488 $protectDescriptionLog = '';
2490 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2491 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2492 $expiryText = $this->formatExpiry( $expiry[$action] );
2493 $protectDescriptionLog .=
2495 "[$action=$restrictions] ($expiryText)";
2498 return trim( $protectDescriptionLog );
2502 * Take an array of page restrictions and flatten it to a string
2503 * suitable for insertion into the page_restrictions field.
2505 * @param string[] $limit
2507 * @throws MWException
2510 protected static function flattenRestrictions( $limit ) {
2511 if ( !is_array( $limit ) ) {
2512 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2518 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2519 $bits[] = "$action=$restrictions";
2522 return implode( ':', $bits );
2526 * Determines if deletion of this page would be batched (executed over time by the job queue)
2527 * or not (completed in the same request as the delete call).
2529 * It is unlikely but possible that an edit from another request could push the page over the
2530 * batching threshold after this function is called, but before the caller acts upon the
2531 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2532 * is provided as an unreliable but situationally useful help for some common cases.
2534 * @param int $safetyMargin Added to the revision count when checking for batching
2535 * @return bool True if deletion would be batched, false otherwise
2537 public function isBatchedDelete( $safetyMargin = 0 ) {
2538 global $wgDeleteRevisionsBatchSize;
2540 $dbr = wfGetDB( DB_REPLICA
);
2541 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2542 $revCount +
= $safetyMargin;
2544 return $revCount >= $wgDeleteRevisionsBatchSize;
2548 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2549 * backwards compatibility, if you care about error reporting you should use
2550 * doDeleteArticleReal() instead.
2552 * Deletes the article with database consistency, writes logs, purges caches
2554 * @param string $reason Delete reason for deletion log
2555 * @param bool $suppress Suppress all revisions and log the deletion in
2556 * the suppression log instead of the deletion log
2557 * @param int|null $u1 Unused
2558 * @param bool|null $u2 Unused
2559 * @param array|string &$error Array of errors to append to
2560 * @param User|null $user The deleting user
2561 * @param bool $immediate false allows deleting over time via the job queue
2562 * @return bool True if successful
2563 * @throws FatalError
2564 * @throws MWException
2566 public function doDeleteArticle(
2567 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2570 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2571 [], 'delete', $immediate );
2573 // Returns true if the page was actually deleted, or is scheduled for deletion
2574 return $status->isOK();
2578 * Back-end article deletion
2579 * Deletes the article with database consistency, writes logs, purges caches
2583 * @param string $reason Delete reason for deletion log
2584 * @param bool $suppress Suppress all revisions and log the deletion in
2585 * the suppression log instead of the deletion log
2586 * @param int|null $u1 Unused
2587 * @param bool|null $u2 Unused
2588 * @param array|string &$error Array of errors to append to
2589 * @param User|null $deleter The deleting user
2590 * @param array $tags Tags to apply to the deletion action
2591 * @param string $logsubtype
2592 * @param bool $immediate false allows deleting over time via the job queue
2593 * @return Status Status object; if successful, $status->value is the log_id of the
2594 * deletion log entry. If the page couldn't be deleted because it wasn't
2595 * found, $status is a non-fatal 'cannotdelete' error
2596 * @throws FatalError
2597 * @throws MWException
2599 public function doDeleteArticleReal(
2600 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2601 $tags = [], $logsubtype = 'delete', $immediate = false
2605 wfDebug( __METHOD__
. "\n" );
2607 $status = Status
::newGood();
2609 // Avoid PHP 7.1 warning of passing $this by reference
2612 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2613 if ( !Hooks
::run( 'ArticleDelete',
2614 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2616 if ( $status->isOK() ) {
2617 // Hook aborted but didn't set a fatal status
2618 $status->fatal( 'delete-hook-aborted' );
2623 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2624 $logsubtype, $immediate );
2628 * Back-end article deletion
2630 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2631 * Deletions can often be completed inline without involving the job queue.
2633 * Potentially called many times per deletion operation for pages with many revisions.
2635 public function doDeleteArticleBatched(
2636 $reason, $suppress, User
$deleter, $tags,
2637 $logsubtype, $immediate = false, $webRequestId = null
2639 wfDebug( __METHOD__
. "\n" );
2641 $status = Status
::newGood();
2643 $dbw = wfGetDB( DB_MASTER
);
2644 $dbw->startAtomic( __METHOD__
);
2646 $this->loadPageData( self
::READ_LATEST
);
2647 $id = $this->getId();
2648 // T98706: lock the page from various other updates but avoid using
2649 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2650 // the revisions queries (which also JOIN on user). Only lock the page
2651 // row and CAS check on page_latest to see if the trx snapshot matches.
2652 $lockedLatest = $this->lockAndGetLatest();
2653 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2654 $dbw->endAtomic( __METHOD__
);
2655 // Page not there or trx snapshot is stale
2656 $status->error( 'cannotdelete',
2657 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2661 // At this point we are now committed to returning an OK
2662 // status unless some DB query error or other exception comes up.
2663 // This way callers don't have to call rollback() if $status is bad
2664 // unless they actually try to catch exceptions (which is rare).
2666 // we need to remember the old content so we can use it to generate all deletion updates.
2667 $revision = $this->getRevision();
2669 $content = $this->getContent( Revision
::RAW
);
2670 } catch ( Exception
$ex ) {
2671 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2672 . $ex->getMessage() );
2677 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2678 // one batch of revisions and defer archival of any others to the job queue.
2679 $explictTrxLogged = false;
2681 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2682 if ( $done ||
!$immediate ) {
2685 $dbw->endAtomic( __METHOD__
);
2686 if ( $dbw->explicitTrxActive() ) {
2687 // Explict transactions may never happen here in practice. Log to be sure.
2688 if ( !$explictTrxLogged ) {
2689 $explictTrxLogged = true;
2690 LoggerFactory
::getInstance( 'wfDebug' )->debug(
2691 'explicit transaction active in ' . __METHOD__
. ' while deleting {title}', [
2692 'title' => $this->getTitle()->getText(),
2697 if ( $dbw->trxLevel() ) {
2700 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
2701 $lbFactory->waitForReplication();
2702 $dbw->startAtomic( __METHOD__
);
2705 // If done archiving, also delete the article.
2707 $dbw->endAtomic( __METHOD__
);
2710 'wikiPageId' => $id,
2711 'requestId' => $webRequestId ?? WebRequest
::getRequestId(),
2712 'reason' => $reason,
2713 'suppress' => $suppress,
2714 'userId' => $deleter->getId(),
2715 'tags' => json_encode( $tags ),
2716 'logsubtype' => $logsubtype,
2719 $job = new DeletePageJob( $this->getTitle(), $jobParams );
2720 JobQueueGroup
::singleton()->push( $job );
2722 $status->warning( 'delete-scheduled',
2723 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2725 // Get archivedRevisionCount by db query, because there's no better alternative.
2726 // Jobs cannot pass a count of archived revisions to the next job, because additional
2727 // deletion operations can be started while the first is running. Jobs from each
2728 // gracefully interleave, but would not know about each other's count. Deduplication
2729 // in the job queue to avoid simultaneous deletion operations would add overhead.
2730 // Number of archived revisions cannot be known beforehand, because edits can be made
2731 // while deletion operations are being processed, changing the number of archivals.
2732 $archivedRevisionCount = $dbw->selectField(
2733 'archive', 'COUNT(*)',
2735 'ar_namespace' => $this->getTitle()->getNamespace(),
2736 'ar_title' => $this->getTitle()->getDBkey(),
2741 // Clone the title and wikiPage, so we have the information we need when
2742 // we log and run the ArticleDeleteComplete hook.
2743 $logTitle = clone $this->mTitle
;
2744 $wikiPageBeforeDelete = clone $this;
2746 // Now that it's safely backed up, delete it
2747 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2749 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2750 $logtype = $suppress ?
'suppress' : 'delete';
2752 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2753 $logEntry->setPerformer( $deleter );
2754 $logEntry->setTarget( $logTitle );
2755 $logEntry->setComment( $reason );
2756 $logEntry->setTags( $tags );
2757 $logid = $logEntry->insert();
2759 $dbw->onTransactionPreCommitOrIdle(
2760 function () use ( $logEntry, $logid ) {
2761 // T58776: avoid deadlocks (especially from FileDeleteForm)
2762 $logEntry->publish( $logid );
2767 $dbw->endAtomic( __METHOD__
);
2769 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2771 Hooks
::run( 'ArticleDeleteComplete', [
2772 &$wikiPageBeforeDelete,
2778 $archivedRevisionCount
2780 $status->value
= $logid;
2782 // Show log excerpt on 404 pages rather than just a link
2783 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2784 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2785 $cache->set( $key, 1, $cache::TTL_DAY
);
2792 * Archives revisions as part of page deletion.
2794 * @param IDatabase $dbw
2796 * @param bool $suppress Suppress all revisions and log the deletion in
2797 * the suppression log instead of the deletion log
2800 protected function archiveRevisions( $dbw, $id, $suppress ) {
2801 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2802 $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage,
2803 $wgDeleteRevisionsBatchSize;
2805 // Given the lock above, we can be confident in the title and page ID values
2806 $namespace = $this->getTitle()->getNamespace();
2807 $dbKey = $this->getTitle()->getDBkey();
2809 $commentStore = CommentStore
::getStore();
2810 $actorMigration = ActorMigration
::newMigration();
2812 $revQuery = Revision
::getQueryInfo();
2815 // Bitfields to further suppress the content
2817 $bitfield = Revision
::SUPPRESSED_ALL
;
2818 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2821 // For now, shunt the revision data into the archive table.
2822 // Text is *not* removed from the text table; bulk storage
2823 // is left intact to avoid breaking block-compression or
2824 // immutable storage schemes.
2825 // In the future, we may keep revisions and mark them with
2826 // the rev_deleted field, which is reserved for this purpose.
2828 // Lock rows in `revision` and its temp tables, but not any others.
2829 // Note array_intersect() preserves keys from the first arg, and we're
2830 // assuming $revQuery has `revision` primary and isn't using subtables
2831 // for anything we care about.
2832 $dbw->lockForUpdate(
2834 $revQuery['tables'],
2835 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2837 [ 'rev_page' => $id ],
2843 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2844 // so we can copy it to the archive table.
2845 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2846 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2847 $revQuery['fields'][] = 'rev_text_id';
2849 if ( $wgContentHandlerUseDB ) {
2850 $revQuery['fields'][] = 'rev_content_model';
2851 $revQuery['fields'][] = 'rev_content_format';
2855 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2856 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2857 $res = $dbw->select(
2858 $revQuery['tables'],
2859 $revQuery['fields'],
2860 [ 'rev_page' => $id ],
2862 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize +
1 ],
2866 // Build their equivalent archive rows
2870 /** @var int[] Revision IDs of edits that were made by IPs */
2874 foreach ( $res as $row ) {
2875 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2880 $comment = $commentStore->getComment( 'rev_comment', $row );
2881 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2883 'ar_namespace' => $namespace,
2884 'ar_title' => $dbKey,
2885 'ar_timestamp' => $row->rev_timestamp
,
2886 'ar_minor_edit' => $row->rev_minor_edit
,
2887 'ar_rev_id' => $row->rev_id
,
2888 'ar_parent_id' => $row->rev_parent_id
,
2890 * ar_text_id should probably not be written to when the multi content schema has
2891 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2892 * default for the field in WMF production currently so we must keep writing
2893 * writing until a default of 0 is set.
2894 * Task: https://phabricator.wikimedia.org/T190148
2895 * Copying the value from the revision table should not lead to any issues for now.
2897 'ar_len' => $row->rev_len
,
2898 'ar_page_id' => $id,
2899 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2900 'ar_sha1' => $row->rev_sha1
,
2901 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2902 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2904 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2905 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2907 if ( $wgContentHandlerUseDB ) {
2908 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2909 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2913 $rowsInsert[] = $rowInsert;
2914 $revids[] = $row->rev_id
;
2916 // Keep track of IP edits, so that the corresponding rows can
2917 // be deleted in the ip_changes table.
2918 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2919 $ipRevIds[] = $row->rev_id
;
2923 // This conditional is just a sanity check
2924 if ( count( $revids ) > 0 ) {
2925 // Copy them into the archive table
2926 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2928 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__
);
2929 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2930 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2932 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2933 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2936 // Also delete records from ip_changes as applicable.
2937 if ( count( $ipRevIds ) > 0 ) {
2938 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2946 * Lock the page row for this title+id and return page_latest (or 0)
2948 * @return int Returns 0 if no row was found with this title+id
2951 public function lockAndGetLatest() {
2952 return (int)wfGetDB( DB_MASTER
)->selectField(
2956 'page_id' => $this->getId(),
2957 // Typically page_id is enough, but some code might try to do
2958 // updates assuming the title is the same, so verify that
2959 'page_namespace' => $this->getTitle()->getNamespace(),
2960 'page_title' => $this->getTitle()->getDBkey()
2968 * Do some database updates after deletion
2970 * @param int $id The page_id value of the page being deleted
2971 * @param Content|null $content Page content to be used when determining
2972 * the required updates. This may be needed because $this->getContent()
2973 * may already return null when the page proper was deleted.
2974 * @param RevisionRecord|Revision|null $revision The current page revision at the time of
2975 * deletion, used when determining the required updates. This may be needed because
2976 * $this->getRevision() may already return null when the page proper was deleted.
2977 * @param User|null $user The user that caused the deletion
2979 public function doDeleteUpdates(
2980 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2982 if ( $id !== $this->getId() ) {
2983 throw new InvalidArgumentException( 'Mismatching page ID' );
2987 $countable = $this->isCountable();
2988 } catch ( Exception
$ex ) {
2989 // fallback for deleting broken pages for which we cannot load the content for
2990 // some reason. Note that doDeleteArticleReal() already logged this problem.
2994 // Update site status
2995 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2996 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2999 // Delete pagelinks, update secondary indexes, etc
3000 $updates = $this->getDeletionUpdates(
3001 $revision ?
$revision->getRevisionRecord() : $content
3003 foreach ( $updates as $update ) {
3004 DeferredUpdates
::addUpdate( $update );
3007 $causeAgent = $user ?
$user->getName() : 'unknown';
3008 // Reparse any pages transcluding this page
3009 LinksUpdate
::queueRecursiveJobsForTable(
3010 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3011 // Reparse any pages including this image
3012 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3013 LinksUpdate
::queueRecursiveJobsForTable(
3014 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3018 self
::onArticleDelete( $this->mTitle
);
3019 ResourceLoaderWikiModule
::invalidateModuleCache(
3020 $this->mTitle
, $revision, null, wfWikiID()
3023 // Reset this object and the Title object
3024 $this->loadFromRow( false, self
::READ_LATEST
);
3027 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3031 * Roll back the most recent consecutive set of edits to a page
3032 * from the same user; fails if there are no eligible edits to
3033 * roll back to, e.g. user is the sole contributor. This function
3034 * performs permissions checks on $user, then calls commitRollback()
3035 * to do the dirty work
3037 * @todo Separate the business/permission stuff out from backend code
3038 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3040 * @param string $fromP Name of the user whose edits to rollback.
3041 * @param string $summary Custom summary. Set to default summary if empty.
3042 * @param string $token Rollback token.
3043 * @param bool $bot If true, mark all reverted edits as bot.
3045 * @param array &$resultDetails Array contains result-specific array of additional values
3046 * 'alreadyrolled' : 'current' (rev)
3047 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3049 * @param User $user The user performing the rollback
3050 * @param array|null $tags Change tags to apply to the rollback
3051 * Callers are responsible for permission checks
3052 * (with ChangeTags::canAddTagsAccompanyingChange)
3054 * @return array Array of errors, each error formatted as
3055 * array(messagekey, param1, param2, ...).
3056 * On success, the array is empty. This array can also be passed to
3057 * OutputPage::showPermissionsErrorPage().
3059 public function doRollback(
3060 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3062 $resultDetails = null;
3064 // Check permissions
3065 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3066 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3067 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3069 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3070 $errors[] = [ 'sessionfailure' ];
3073 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3074 $errors[] = [ 'actionthrottledtext' ];
3077 // If there were errors, bail out now
3078 if ( !empty( $errors ) ) {
3082 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3086 * Backend implementation of doRollback(), please refer there for parameter
3087 * and return value documentation
3089 * NOTE: This function does NOT check ANY permissions, it just commits the
3090 * rollback to the DB. Therefore, you should only call this function direct-
3091 * ly if you want to use custom permissions checks. If you don't, use
3092 * doRollback() instead.
3093 * @param string $fromP Name of the user whose edits to rollback.
3094 * @param string $summary Custom summary. Set to default summary if empty.
3095 * @param bool $bot If true, mark all reverted edits as bot.
3097 * @param array &$resultDetails Contains result-specific array of additional values
3098 * @param User $guser The user performing the rollback
3099 * @param array|null $tags Change tags to apply to the rollback
3100 * Callers are responsible for permission checks
3101 * (with ChangeTags::canAddTagsAccompanyingChange)
3103 * @return array An array of error messages, as returned by Status::getErrorsArray()
3105 public function commitRollback( $fromP, $summary, $bot,
3106 &$resultDetails, User
$guser, $tags = null
3108 global $wgUseRCPatrol;
3110 $dbw = wfGetDB( DB_MASTER
);
3112 if ( wfReadOnly() ) {
3113 return [ [ 'readonlytext' ] ];
3116 // Begin revision creation cycle by creating a PageUpdater.
3117 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3118 $updater = $this->newPageUpdater( $guser );
3119 $current = $updater->grabParentRevision();
3121 if ( is_null( $current ) ) {
3122 // Something wrong... no page?
3123 return [ [ 'notanarticle' ] ];
3126 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
3127 $legacyCurrent = new Revision( $current );
3128 $from = str_replace( '_', ' ', $fromP );
3130 // User name given should match up with the top revision.
3131 // If the revision's user is not visible, then $from should be empty.
3132 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
3133 $resultDetails = [ 'current' => $legacyCurrent ];
3134 return [ [ 'alreadyrolled',
3135 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3136 htmlspecialchars( $fromP ),
3137 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3141 // Get the last edit not by this person...
3142 // Note: these may not be public values
3143 $actorWhere = ActorMigration
::newMigration()->getWhere(
3146 $current->getUser( RevisionRecord
::RAW
)
3149 $s = $dbw->selectRow(
3150 [ 'revision' ] +
$actorWhere['tables'],
3151 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3153 'rev_page' => $current->getPageId(),
3154 'NOT(' . $actorWhere['conds'] . ')',
3158 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3159 'ORDER BY' => 'rev_timestamp DESC'
3161 $actorWhere['joins']
3163 if ( $s === false ) {
3164 // No one else ever edited this page
3165 return [ [ 'cantrollback' ] ];
3166 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3167 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3169 // Only admins can see this text
3170 return [ [ 'notvisiblerev' ] ];
3173 // Generate the edit summary if necessary
3174 $target = $this->getRevisionStore()->getRevisionById(
3176 RevisionStore
::READ_LATEST
3178 if ( empty( $summary ) ) {
3179 if ( !$currentEditorForPublic ) { // no public user name
3180 $summary = wfMessage( 'revertpage-nouser' );
3182 $summary = wfMessage( 'revertpage' );
3185 $legacyTarget = new Revision( $target );
3186 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3188 // Allow the custom summary to use the same args as the default message
3189 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3191 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3192 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3194 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3196 $contLang->timeanddate( $current->getTimestamp() )
3198 if ( $summary instanceof Message
) {
3199 $summary = $summary->params( $args )->inContentLanguage()->text();
3201 $summary = wfMsgReplaceArgs( $summary, $args );
3204 // Trim spaces on user supplied text
3205 $summary = trim( $summary );
3208 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3210 if ( $guser->isAllowed( 'minoredit' ) ) {
3211 $flags |
= EDIT_MINOR
;
3214 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3215 $flags |
= EDIT_FORCE_BOT
;
3218 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3219 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3220 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3221 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3223 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3224 $tags[] = 'mw-rollback';
3227 // Build rollback revision:
3228 // Restore old content
3229 // TODO: MCR: test this once we can store multiple slots
3230 foreach ( $target->getSlots()->getSlots() as $slot ) {
3231 $updater->inheritSlot( $slot );
3234 // Remove extra slots
3235 // TODO: MCR: test this once we can store multiple slots
3236 foreach ( $current->getSlotRoles() as $role ) {
3237 if ( !$target->hasSlot( $role ) ) {
3238 $updater->removeSlot( $role );
3242 $updater->setOriginalRevisionId( $target->getId() );
3243 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3244 $updater->addTags( $tags );
3246 // TODO: this logic should not be in the storage layer, it's here for compatibility
3247 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3248 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3249 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
3250 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3253 // Actually store the rollback
3254 $rev = $updater->saveRevision(
3255 CommentStoreComment
::newUnsavedComment( $summary ),
3259 // Set patrolling and bot flag on the edits, which gets rollbacked.
3260 // This is done even on edit failure to have patrolling in that case (T64157).
3262 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3263 // Mark all reverted edits as bot
3267 if ( $wgUseRCPatrol ) {
3268 // Mark all reverted edits as patrolled
3269 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3272 if ( count( $set ) ) {
3273 $actorWhere = ActorMigration
::newMigration()->getWhere(
3276 $current->getUser( RevisionRecord
::RAW
),
3279 $dbw->update( 'recentchanges', $set,
3281 'rc_cur_id' => $current->getPageId(),
3282 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3283 $actorWhere['conds'], // No tables/joins are needed for rc_user
3289 if ( !$updater->wasSuccessful() ) {
3290 return $updater->getStatus()->getErrorsArray();
3293 // Report if the edit was not created because it did not change the content.
3294 if ( $updater->isUnchanged() ) {
3295 $resultDetails = [ 'current' => $legacyCurrent ];
3296 return [ [ 'alreadyrolled',
3297 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3298 htmlspecialchars( $fromP ),
3299 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3303 if ( $changingContentModel ) {
3304 // If the content model changed during the rollback,
3305 // make sure it gets logged to Special:Log/contentmodel
3306 $log = new ManualLogEntry( 'contentmodel', 'change' );
3307 $log->setPerformer( $guser );
3308 $log->setTarget( $this->mTitle
);
3309 $log->setComment( $summary );
3310 $log->setParameters( [
3311 '4::oldmodel' => $currentContent->getModel(),
3312 '5::newmodel' => $targetContent->getModel(),
3315 $logId = $log->insert( $dbw );
3316 $log->publish( $logId );
3319 $revId = $rev->getId();
3321 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3324 'summary' => $summary,
3325 'current' => $legacyCurrent,
3326 'target' => $legacyTarget,
3331 // TODO: make this return a Status object and wrap $resultDetails in that.
3336 * The onArticle*() functions are supposed to be a kind of hooks
3337 * which should be called whenever any of the specified actions
3340 * This is a good place to put code to clear caches, for instance.
3342 * This is called on page move and undelete, as well as edit
3344 * @param Title $title
3346 public static function onArticleCreate( Title
$title ) {
3347 // TODO: move this into a PageEventEmitter service
3349 // Update existence markers on article/talk tabs...
3350 $other = $title->getOtherPage();
3352 $other->purgeSquid();
3354 $title->touchLinks();
3355 $title->purgeSquid();
3356 $title->deleteTitleProtection();
3358 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3360 // Invalidate caches of articles which include this page
3361 DeferredUpdates
::addUpdate(
3362 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3365 if ( $title->getNamespace() == NS_CATEGORY
) {
3366 // Load the Category object, which will schedule a job to create
3367 // the category table row if necessary. Checking a replica DB is ok
3368 // here, in the worst case it'll run an unnecessary recount job on
3369 // a category that probably doesn't have many members.
3370 Category
::newFromTitle( $title )->getID();
3375 * Clears caches when article is deleted
3377 * @param Title $title
3379 public static function onArticleDelete( Title
$title ) {
3380 // TODO: move this into a PageEventEmitter service
3382 // Update existence markers on article/talk tabs...
3383 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3384 BacklinkCache
::get( $title )->clear();
3385 $other = $title->getOtherPage();
3387 $other->purgeSquid();
3389 $title->touchLinks();
3390 $title->purgeSquid();
3392 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3395 HTMLFileCache
::clearFileCache( $title );
3396 InfoAction
::invalidateCache( $title );
3399 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3400 MessageCache
::singleton()->updateMessageOverride( $title, null );
3404 if ( $title->getNamespace() == NS_FILE
) {
3405 DeferredUpdates
::addUpdate(
3406 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3411 if ( $title->getNamespace() == NS_USER_TALK
) {
3412 $user = User
::newFromName( $title->getText(), false );
3414 $user->setNewtalk( false );
3419 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3421 // Purge cross-wiki cache entities referencing this page
3422 self
::purgeInterwikiCheckKey( $title );
3426 * Purge caches on page update etc
3428 * @param Title $title
3429 * @param Revision|null $revision Revision that was just saved, may be null
3430 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3431 * If not given, all slots are assumed to have changed.
3433 public static function onArticleEdit(
3435 Revision
$revision = null,
3436 $slotsChanged = null
3438 // TODO: move this into a PageEventEmitter service
3440 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3441 // Invalidate caches of articles which include this page.
3442 // Only for the main slot, because only the main slot is transcluded.
3443 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3444 DeferredUpdates
::addUpdate(
3445 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3449 // Invalidate the caches of all pages which redirect here
3450 DeferredUpdates
::addUpdate(
3451 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3454 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3456 // Purge CDN for this page only
3457 $title->purgeSquid();
3458 // Clear file cache for this page only
3459 HTMLFileCache
::clearFileCache( $title );
3461 // Purge ?action=info cache
3462 $revid = $revision ?
$revision->getId() : null;
3463 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3464 InfoAction
::invalidateCache( $title, $revid );
3467 // Purge cross-wiki cache entities referencing this page
3468 self
::purgeInterwikiCheckKey( $title );
3474 * Purge the check key for cross-wiki cache entries referencing this page
3476 * @param Title $title
3478 private static function purgeInterwikiCheckKey( Title
$title ) {
3479 global $wgEnableScaryTranscluding;
3481 if ( !$wgEnableScaryTranscluding ) {
3482 return; // @todo: perhaps this wiki is only used as a *source* for content?
3485 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3486 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3487 $cache->resetCheckKey(
3488 // Do not include the namespace since there can be multiple aliases to it
3489 // due to different namespace text definitions on different wikis. This only
3490 // means that some cache invalidations happen that are not strictly needed.
3491 $cache->makeGlobalKey( 'interwiki-page', wfWikiID(), $title->getDBkey() )
3497 * Returns a list of categories this page is a member of.
3498 * Results will include hidden categories
3500 * @return TitleArray
3502 public function getCategories() {
3503 $id = $this->getId();
3505 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3508 $dbr = wfGetDB( DB_REPLICA
);
3509 $res = $dbr->select( 'categorylinks',
3510 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3511 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3512 // as not being aliases, and NS_CATEGORY is numeric
3513 [ 'cl_from' => $id ],
3516 return TitleArray
::newFromResult( $res );
3520 * Returns a list of hidden categories this page is a member of.
3521 * Uses the page_props and categorylinks tables.
3523 * @return array Array of Title objects
3525 public function getHiddenCategories() {
3527 $id = $this->getId();
3533 $dbr = wfGetDB( DB_REPLICA
);
3534 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3536 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3537 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3540 if ( $res !== false ) {
3541 foreach ( $res as $row ) {
3542 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3550 * Auto-generates a deletion reason
3552 * @param bool &$hasHistory Whether the page has a history
3553 * @return string|bool String containing deletion reason or empty string, or boolean false
3554 * if no revision occurred
3556 public function getAutoDeleteReason( &$hasHistory ) {
3557 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3561 * Update all the appropriate counts in the category table, given that
3562 * we've added the categories $added and deleted the categories $deleted.
3564 * This should only be called from deferred updates or jobs to avoid contention.
3566 * @param array $added The names of categories that were added
3567 * @param array $deleted The names of categories that were deleted
3568 * @param int $id Page ID (this should be the original deleted page ID)
3570 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3571 $id = $id ?
: $this->getId();
3572 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3574 $addFields = [ 'cat_pages = cat_pages + 1' ];
3575 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3576 if ( $type !== 'page' ) {
3577 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3578 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3581 $dbw = wfGetDB( DB_MASTER
);
3583 if ( count( $added ) ) {
3584 $existingAdded = $dbw->selectFieldValues(
3587 [ 'cat_title' => $added ],
3591 // For category rows that already exist, do a plain
3592 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3593 // to avoid creating gaps in the cat_id sequence.
3594 if ( count( $existingAdded ) ) {
3598 [ 'cat_title' => $existingAdded ],
3603 $missingAdded = array_diff( $added, $existingAdded );
3604 if ( count( $missingAdded ) ) {
3606 foreach ( $missingAdded as $cat ) {
3608 'cat_title' => $cat,
3610 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3611 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3624 if ( count( $deleted ) ) {
3628 [ 'cat_title' => $deleted ],
3633 foreach ( $added as $catName ) {
3634 $cat = Category
::newFromName( $catName );
3635 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3638 foreach ( $deleted as $catName ) {
3639 $cat = Category
::newFromName( $catName );
3640 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3641 // Refresh counts on categories that should be empty now (after commit, T166757)
3642 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3643 $cat->refreshCountsIfEmpty();
3649 * Opportunistically enqueue link update jobs given fresh parser output if useful
3651 * @param ParserOutput $parserOutput Current version page output
3654 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3655 if ( wfReadOnly() ) {
3659 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3660 [ $this, $this->mTitle
, $parserOutput ]
3665 $config = RequestContext
::getMain()->getConfig();
3668 'isOpportunistic' => true,
3669 'rootJobTimestamp' => $parserOutput->getCacheTime()
3672 if ( $this->mTitle
->areRestrictionsCascading() ) {
3673 // If the page is cascade protecting, the links should really be up-to-date
3674 JobQueueGroup
::singleton()->lazyPush(
3675 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3677 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3678 // Assume the output contains "dynamic" time/random based magic words.
3679 // Only update pages that expired due to dynamic content and NOT due to edits
3680 // to referenced templates/files. When the cache expires due to dynamic content,
3681 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3682 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3683 // template/file edit already triggered recursive RefreshLinksJob jobs.
3684 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3685 // If a page is uncacheable, do not keep spamming a job for it.
3686 // Although it would be de-duplicated, it would still waste I/O.
3687 $cache = ObjectCache
::getLocalClusterInstance();
3688 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3689 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3690 if ( $cache->add( $key, time(), $ttl ) ) {
3691 JobQueueGroup
::singleton()->lazyPush(
3692 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3700 * Returns a list of updates to be performed when this page is deleted. The
3701 * updates should remove any information about this page from secondary data
3702 * stores such as links tables.
3704 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3705 * object for backwards compatibility.
3706 * @return DeferrableUpdate[]
3708 public function getDeletionUpdates( $rev = null ) {
3710 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3713 $rev = $this->getRevisionRecord();
3714 } catch ( Exception
$ex ) {
3715 // If we can't load the content, something is wrong. Perhaps that's why
3716 // the user is trying to delete the page, so let's not fail in that case.
3717 // Note that doDeleteArticleReal() will already have logged an issue with
3718 // loading the content.
3719 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3725 } elseif ( $rev instanceof Content
) {
3726 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3728 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3730 $slotContent = array_map( function ( SlotRecord
$slot ) {
3731 return $slot->getContent( Revision
::RAW
);
3732 }, $rev->getSlots()->getSlots() );
3735 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3737 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3738 // model here, not the content object!
3739 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3740 /** @var Content $content */
3741 foreach ( $slotContent as $role => $content ) {
3742 $handler = $content->getContentHandler();
3744 $updates = $handler->getDeletionUpdates(
3748 $allUpdates = array_merge( $allUpdates, $updates );
3750 // TODO: remove B/C hack in 1.32!
3751 $legacyUpdates = $content->getDeletionUpdates( $this );
3753 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3754 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3755 return !( $update instanceof LinksDeletionUpdate
);
3758 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3761 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3763 // TODO: hard deprecate old hook in 1.33
3764 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3769 * Whether this content displayed on this page
3770 * comes from the local database
3775 public function isLocal() {
3780 * The display name for the site this content
3781 * come from. If a subclass overrides isLocal(),
3782 * this could return something other than the
3788 public function getWikiDisplayName() {
3794 * Get the source URL for the content on this page,
3795 * typically the canonical URL, but may be a remote
3796 * link if the content comes from another site
3801 public function getSourceURL() {
3802 return $this->getTitle()->getCanonicalURL();
3806 * @param WANObjectCache $cache
3810 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3811 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3813 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );