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() ) {
1051 'rd_from' => $this->getId(),
1052 'rd_namespace' => $rt->getNamespace(),
1053 'rd_title' => $rt->getDBkey(),
1054 'rd_fragment' => $rt->getFragment(),
1055 'rd_interwiki' => $rt->getInterwiki(),
1059 'rd_namespace' => $rt->getNamespace(),
1060 'rd_title' => $rt->getDBkey(),
1061 'rd_fragment' => $rt->getFragment(),
1062 'rd_interwiki' => $rt->getInterwiki(),
1068 $dbw->endAtomic( __METHOD__
);
1072 * Get the Title object or URL this page redirects to
1074 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1076 public function followRedirect() {
1077 return $this->getRedirectURL( $this->getRedirectTarget() );
1081 * Get the Title object or URL to use for a redirect. We use Title
1082 * objects for same-wiki, non-special redirects and URLs for everything
1084 * @param Title $rt Redirect target
1085 * @return bool|Title|string False, Title object of local target, or string with URL
1087 public function getRedirectURL( $rt ) {
1092 if ( $rt->isExternal() ) {
1093 if ( $rt->isLocal() ) {
1094 // Offsite wikis need an HTTP redirect.
1095 // This can be hard to reverse and may produce loops,
1096 // so they may be disabled in the site configuration.
1097 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1098 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1100 // External pages without "local" bit set are not valid
1106 if ( $rt->isSpecialPage() ) {
1107 // Gotta handle redirects to special pages differently:
1108 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1109 // Some pages are not valid targets.
1110 if ( $rt->isValidRedirectTarget() ) {
1111 return $rt->getFullURL();
1121 * Get a list of users who have edited this article, not including the user who made
1122 * the most recent revision, which you can get from $article->getUser() if you want it
1123 * @return UserArrayFromResult
1125 public function getContributors() {
1126 // @todo: This is expensive; cache this info somewhere.
1128 $dbr = wfGetDB( DB_REPLICA
);
1130 $actorMigration = ActorMigration
::newMigration();
1131 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1133 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1136 'user_id' => $actorQuery['fields']['rev_user'],
1137 'user_name' => $actorQuery['fields']['rev_user_text'],
1138 'actor_id' => $actorQuery['fields']['rev_actor'],
1139 'user_real_name' => 'MIN(user_real_name)',
1140 'timestamp' => 'MAX(rev_timestamp)',
1143 $conds = [ 'rev_page' => $this->getId() ];
1145 // The user who made the top revision gets credited as "this page was last edited by
1146 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1147 $user = $this->getUser()
1148 ? User
::newFromId( $this->getUser() )
1149 : User
::newFromName( $this->getUserText(), false );
1150 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1153 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1156 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1157 ] +
$actorQuery['joins'];
1160 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1161 'ORDER BY' => 'timestamp DESC',
1164 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1165 return new UserArrayFromResult( $res );
1169 * Should the parser cache be used?
1171 * @param ParserOptions $parserOptions ParserOptions to check
1175 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1176 return $parserOptions->getStubThreshold() == 0
1178 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1179 && $this->getContentHandler()->isParserCacheSupported();
1183 * Get a ParserOutput for the given ParserOptions and revision ID.
1185 * The parser cache will be used if possible. Cache misses that result
1186 * in parser runs are debounced with PoolCounter.
1188 * XXX merge this with updateParserCache()?
1191 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1192 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1193 * get the current revision (default value)
1194 * @param bool $forceParse Force reindexing, regardless of cache settings
1195 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1197 public function getParserOutput(
1198 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1201 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1203 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1204 throw new InvalidArgumentException(
1205 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1209 wfDebug( __METHOD__
.
1210 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1211 if ( $parserOptions->getStubThreshold() ) {
1212 wfIncrStats( 'pcache.miss.stub' );
1215 if ( $useParserCache ) {
1216 $parserOutput = $this->getParserCache()
1217 ->get( $this, $parserOptions );
1218 if ( $parserOutput !== false ) {
1219 return $parserOutput;
1223 if ( $oldid === null ||
$oldid === 0 ) {
1224 $oldid = $this->getLatest();
1227 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1230 return $pool->getParserOutput();
1234 * Do standard deferred updates after page view (existing or missing page)
1235 * @param User $user The relevant user
1236 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1238 public function doViewUpdates( User
$user, $oldid = 0 ) {
1239 if ( wfReadOnly() ) {
1243 // Update newtalk / watchlist notification status;
1244 // Avoid outage if the master is not reachable by using a deferred updated
1245 DeferredUpdates
::addCallableUpdate(
1246 function () use ( $user, $oldid ) {
1247 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1249 $user->clearNotification( $this->mTitle
, $oldid );
1251 DeferredUpdates
::PRESEND
1256 * Perform the actions of a page purging
1258 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1259 * controlled how much purging was done.
1261 public function doPurge() {
1262 // Avoid PHP 7.1 warning of passing $this by reference
1265 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1269 $this->mTitle
->invalidateCache();
1272 HTMLFileCache
::clearFileCache( $this->getTitle() );
1273 // Send purge after above page_touched update was committed
1274 DeferredUpdates
::addUpdate(
1275 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1276 DeferredUpdates
::PRESEND
1279 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1280 $messageCache = MessageCache
::singleton();
1281 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1288 * Insert a new empty page record for this article.
1289 * This *must* be followed up by creating a revision
1290 * and running $this->updateRevisionOn( ... );
1291 * or else the record will be left in a funky state.
1292 * Best if all done inside a transaction.
1294 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1296 * @param IDatabase $dbw
1297 * @param int|null $pageId Custom page ID that will be used for the insert statement
1299 * @return bool|int The newly created page_id key; false if the row was not
1300 * inserted, e.g. because the title already existed or because the specified
1301 * page ID is already in use.
1303 public function insertOn( $dbw, $pageId = null ) {
1304 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1308 'page_namespace' => $this->mTitle
->getNamespace(),
1309 'page_title' => $this->mTitle
->getDBkey(),
1310 'page_restrictions' => '',
1311 'page_is_redirect' => 0, // Will set this shortly...
1313 'page_random' => wfRandom(),
1314 'page_touched' => $dbw->timestamp(),
1315 'page_latest' => 0, // Fill this in shortly...
1316 'page_len' => 0, // Fill this in shortly...
1317 ] +
$pageIdForInsert,
1322 if ( $dbw->affectedRows() > 0 ) {
1323 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1324 $this->mId
= $newid;
1325 $this->mTitle
->resetArticleID( $newid );
1329 return false; // nothing changed
1334 * Update the page record to point to a newly saved revision.
1336 * @todo Factor out into a PageStore service, or move into PageUpdater.
1338 * @param IDatabase $dbw
1339 * @param Revision $revision For ID number, and text used to set
1340 * length and redirect status fields
1341 * @param int|null $lastRevision If given, will not overwrite the page field
1342 * when different from the currently set value.
1343 * Giving 0 indicates the new page flag should be set on.
1344 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1345 * removing rows in redirect table.
1346 * @return bool Success; false if the page row was missing or page_latest changed
1348 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1349 $lastRevIsRedirect = null
1351 global $wgContentHandlerUseDB;
1353 // TODO: move into PageUpdater or PageStore
1354 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1355 // and in the compat stub!
1357 // Assertion to try to catch T92046
1358 if ( (int)$revision->getId() === 0 ) {
1359 throw new InvalidArgumentException(
1360 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1364 $content = $revision->getContent();
1365 $len = $content ?
$content->getSize() : 0;
1366 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1368 $conditions = [ 'page_id' => $this->getId() ];
1370 if ( !is_null( $lastRevision ) ) {
1371 // An extra check against threads stepping on each other
1372 $conditions['page_latest'] = $lastRevision;
1375 $revId = $revision->getId();
1376 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1379 'page_latest' => $revId,
1380 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1381 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1382 'page_is_redirect' => $rt !== null ?
1 : 0,
1386 if ( $wgContentHandlerUseDB ) {
1387 $row['page_content_model'] = $revision->getContentModel();
1390 $dbw->update( 'page',
1395 $result = $dbw->affectedRows() > 0;
1397 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1398 $this->setLastEdit( $revision );
1399 $this->mLatest
= $revision->getId();
1400 $this->mIsRedirect
= (bool)$rt;
1401 // Update the LinkCache.
1402 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1403 $linkCache->addGoodLinkObj(
1409 $revision->getContentModel()
1417 * Add row to the redirect table if this is a redirect, remove otherwise.
1419 * @param IDatabase $dbw
1420 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1421 * or NULL if this is not a redirect
1422 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1423 * removing rows in redirect table.
1424 * @return bool True on success, false on failure
1427 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1428 // Always update redirects (target link might have changed)
1429 // Update/Insert if we don't know if the last revision was a redirect or not
1430 // Delete if changing from redirect to non-redirect
1431 $isRedirect = !is_null( $redirectTitle );
1433 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1437 if ( $isRedirect ) {
1438 $this->insertRedirectEntry( $redirectTitle );
1440 // This is not a redirect, remove row from redirect table
1441 $where = [ 'rd_from' => $this->getId() ];
1442 $dbw->delete( 'redirect', $where, __METHOD__
);
1445 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1446 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1449 return ( $dbw->affectedRows() != 0 );
1453 * If the given revision is newer than the currently set page_latest,
1454 * update the page record. Otherwise, do nothing.
1456 * @deprecated since 1.24, use updateRevisionOn instead
1458 * @param IDatabase $dbw
1459 * @param Revision $revision
1462 public function updateIfNewerOn( $dbw, $revision ) {
1463 $row = $dbw->selectRow(
1464 [ 'revision', 'page' ],
1465 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1467 'page_id' => $this->getId(),
1468 'page_latest=rev_id' ],
1472 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1475 $prev = $row->rev_id
;
1476 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1478 // No or missing previous revision; mark the page as new
1480 $lastRevIsRedirect = null;
1483 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1489 * Helper method for checking whether two revisions have differences that go
1490 * beyond the main slot.
1492 * MCR migration note: this method should go away!
1494 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1496 * @param Revision $a
1497 * @param Revision $b
1500 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1501 $aSlots = $a->getRevisionRecord()->getSlots();
1502 $bSlots = $b->getRevisionRecord()->getSlots();
1503 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1505 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1509 * Get the content that needs to be saved in order to undo all revisions
1510 * between $undo and $undoafter. Revisions must belong to the same page,
1511 * must exist and must not be deleted
1513 * @param Revision $undo
1514 * @param Revision $undoafter Must be an earlier revision than $undo
1515 * @return Content|bool Content on success, false on failure
1517 * Before we had the Content object, this was done in getUndoText
1519 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1520 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1522 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1523 // Cannot yet undo edits that involve anything other the main slot.
1527 $handler = $undo->getContentHandler();
1528 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1532 * Returns true if this page's content model supports sections.
1536 * @todo The skin should check this and not offer section functionality if
1537 * sections are not supported.
1538 * @todo The EditPage should check this and not offer section functionality
1539 * if sections are not supported.
1541 public function supportsSections() {
1542 return $this->getContentHandler()->supportsSections();
1546 * @param string|int|null|bool $sectionId Section identifier as a number or string
1547 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1548 * or 'new' for a new section.
1549 * @param Content $sectionContent New content of the section.
1550 * @param string $sectionTitle New section's subject, only if $section is "new".
1551 * @param string $edittime Revision timestamp or null to use the current revision.
1553 * @throws MWException
1554 * @return Content|null New complete article content, or null if error.
1557 * @deprecated since 1.24, use replaceSectionAtRev instead
1559 public function replaceSectionContent(
1560 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1563 if ( $edittime && $sectionId !== 'new' ) {
1564 $lb = $this->getDBLoadBalancer();
1565 $dbr = $lb->getConnection( DB_REPLICA
);
1566 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1567 // Try the master if this thread may have just added it.
1568 // This could be abstracted into a Revision method, but we don't want
1569 // to encourage loading of revisions by timestamp.
1571 && $lb->getServerCount() > 1
1572 && $lb->hasOrMadeRecentMasterChanges()
1574 $dbw = $lb->getConnection( DB_MASTER
);
1575 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1578 $baseRevId = $rev->getId();
1582 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1586 * @param string|int|null|bool $sectionId Section identifier as a number or string
1587 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1588 * or 'new' for a new section.
1589 * @param Content $sectionContent New content of the section.
1590 * @param string $sectionTitle New section's subject, only if $section is "new".
1591 * @param int|null $baseRevId
1593 * @throws MWException
1594 * @return Content|null New complete article content, or null if error.
1598 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1599 $sectionTitle = '', $baseRevId = null
1601 if ( strval( $sectionId ) === '' ) {
1602 // Whole-page edit; let the whole text through
1603 $newContent = $sectionContent;
1605 if ( !$this->supportsSections() ) {
1606 throw new MWException( "sections not supported for content model " .
1607 $this->getContentHandler()->getModelID() );
1610 // T32711: always use current version when adding a new section
1611 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1612 $oldContent = $this->getContent();
1614 $rev = Revision
::newFromId( $baseRevId );
1616 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1617 $this->getId() . "; section: $sectionId)\n" );
1621 $oldContent = $rev->getContent();
1624 if ( !$oldContent ) {
1625 wfDebug( __METHOD__
. ": no page text\n" );
1629 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1636 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1638 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1639 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1642 * @return int Updated $flags
1644 public function checkFlags( $flags ) {
1645 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1646 if ( $this->exists() ) {
1647 $flags |
= EDIT_UPDATE
;
1657 * @return DerivedPageDataUpdater
1659 private function newDerivedDataUpdater() {
1660 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1662 $derivedDataUpdater = new DerivedPageDataUpdater(
1663 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1664 $this->getRevisionStore(),
1665 $this->getRevisionRenderer(),
1666 $this->getParserCache(),
1667 JobQueueGroup
::singleton(),
1668 MessageCache
::singleton(),
1669 MediaWikiServices
::getInstance()->getContentLanguage(),
1670 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1673 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1674 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1676 return $derivedDataUpdater;
1680 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1681 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1682 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1683 * returned matches that caller's expectations, allowing an existing instance to be re-used
1684 * if the given parameters match that instance's internal state according to
1685 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1686 * match the existign one.
1688 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1689 * created, replacing any DerivedPageDataUpdater currently cached.
1691 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1695 * @param User|null $forUser The user that will be used for, or was used for, PST.
1696 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1697 * to perform updates, if the edit was already saved.
1698 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1699 * if the edit was not yet saved.
1700 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1701 * revision as the edit's parent revision. This ensures that the same
1702 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1704 * @return DerivedPageDataUpdater
1706 private function getDerivedDataUpdater(
1707 User
$forUser = null,
1708 RevisionRecord
$forRevision = null,
1709 RevisionSlotsUpdate
$forUpdate = null,
1712 if ( !$forRevision && !$forUpdate ) {
1713 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1714 // going to use it with.
1715 $this->derivedDataUpdater
= null;
1718 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1719 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1720 // to it did not yet initialize it, because we don't know what data it will be
1721 // initialized with.
1722 $this->derivedDataUpdater
= null;
1725 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1726 // However, there is no good way to construct a cache key. We'd need to check against all
1727 // cached instances.
1729 if ( $this->derivedDataUpdater
1730 && !$this->derivedDataUpdater
->isReusableFor(
1734 $forEdit ?
$this->getLatest() : null
1737 $this->derivedDataUpdater
= null;
1740 if ( !$this->derivedDataUpdater
) {
1741 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1744 return $this->derivedDataUpdater
;
1748 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1750 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1751 * and to protected such conflict resolution from concurrent edits using a check-and-set
1757 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1758 * that may already have been returned via getDerivedDataUpdater to be re-used.
1760 * @return PageUpdater
1762 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1763 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1765 $pageUpdater = new PageUpdater(
1767 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1768 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1769 $this->getDBLoadBalancer(),
1770 $this->getRevisionStore()
1773 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1774 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1775 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1777 return $pageUpdater;
1781 * Change an existing article or create a new article. Updates RC and all necessary caches,
1782 * optionally via the deferred update array.
1784 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1785 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1786 * apply the autopatrol right as appropriate.
1788 * @param Content $content New content
1789 * @param string|CommentStoreComment $summary Edit summary
1790 * @param int $flags Bitfield:
1792 * Article is known or assumed to be non-existent, create a new one
1794 * Article is known or assumed to be pre-existing, update it
1796 * Mark this edit minor, if the user is allowed to do so
1798 * Do not log the change in recentchanges
1800 * Mark the edit a "bot" edit regardless of user rights
1802 * Fill in blank summaries with generated text where possible
1804 * Signal that the page retrieve/save cycle happened entirely in this request.
1806 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1807 * article will be detected. If EDIT_UPDATE is specified and the article
1808 * doesn't exist, the function will return an edit-gone-missing error. If
1809 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1810 * error will be returned. These two conditions are also possible with
1811 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1813 * @param bool|int $originalRevId: The ID of an original revision that the edit
1814 * restores or repeats. The new revision is expected to have the exact same content as
1815 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1816 * which are created to record things like page moves.
1817 * @param User|null $user The user doing the edit
1818 * @param string|null $serialFormat IGNORED.
1819 * @param array|null $tags Change tags to apply to this edit
1820 * Callers are responsible for permission checks
1821 * (with ChangeTags::canAddTagsAccompanyingChange)
1822 * @param Int $undidRevId Id of revision that was undone or 0
1824 * @throws MWException
1825 * @return Status Possible errors:
1826 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1827 * set the fatal flag of $status.
1828 * edit-gone-missing: In update mode, but the article didn't exist.
1829 * edit-conflict: In update mode, the article changed unexpectedly.
1830 * edit-no-change: Warning that the text was the same as before.
1831 * edit-already-exists: In creation mode, but the article already exists.
1833 * Extensions may define additional errors.
1835 * $return->value will contain an associative array with members as follows:
1836 * new: Boolean indicating if the function attempted to create a new article.
1837 * revision: The revision object for the inserted revision, or null.
1840 * @throws MWException
1842 public function doEditContent(
1843 Content
$content, $summary, $flags = 0, $originalRevId = false,
1844 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1846 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1848 if ( !( $summary instanceof CommentStoreComment
) ) {
1849 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1856 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1857 // Checking the minoredit right should be done in the same place the 'bot' right is
1858 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1859 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1860 $flags = ( $flags & ~EDIT_MINOR
);
1863 $slotsUpdate = new RevisionSlotsUpdate();
1864 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1866 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1867 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1868 // used by this PageUpdater. However, there is no guarantee for this.
1869 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1870 $updater->setContent( SlotRecord
::MAIN
, $content );
1871 $updater->setOriginalRevisionId( $originalRevId );
1872 $updater->setUndidRevisionId( $undidRevId );
1874 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1876 // TODO: this logic should not be in the storage layer, it's here for compatibility
1877 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1878 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1879 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1880 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1883 $updater->addTags( $tags );
1885 $revRec = $updater->saveRevision(
1890 // $revRec will be null if the edit failed, or if no new revision was created because
1891 // the content did not change.
1893 // update cached fields
1894 // TODO: this is currently redundant to what is done in updateRevisionOn.
1895 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1896 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1897 $this->mLatest
= $revRec->getId();
1900 return $updater->getStatus();
1904 * Get parser options suitable for rendering the primary article wikitext
1906 * @see ParserOptions::newCanonical
1908 * @param IContextSource|User|string $context One of the following:
1909 * - IContextSource: Use the User and the Language of the provided
1911 * - User: Use the provided User object and $wgLang for the language,
1912 * so use an IContextSource object if possible.
1913 * - 'canonical': Canonical options (anonymous user with default
1914 * preferences and content language).
1915 * @return ParserOptions
1917 public function makeParserOptions( $context ) {
1918 $options = ParserOptions
::newCanonical( $context );
1920 if ( $this->getTitle()->isConversionTable() ) {
1921 // @todo ConversionTable should become a separate content model, so
1922 // we don't need special cases like this one.
1923 $options->disableContentConversion();
1930 * Prepare content which is about to be saved.
1932 * Prior to 1.30, this returned a stdClass.
1934 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1936 * @param Content $content
1937 * @param Revision|RevisionRecord|int|null $revision Revision object.
1938 * For backwards compatibility, a revision ID is also accepted,
1939 * but this is deprecated.
1940 * Used with vary-revision or vary-revision-id.
1941 * @param User|null $user
1942 * @param string|null $serialFormat IGNORED
1943 * @param bool $useCache Check shared prepared edit cache
1945 * @return PreparedEdit
1949 public function prepareContentForEdit(
1953 $serialFormat = null,
1962 if ( !is_object( $revision ) ) {
1964 // This code path is deprecated, and nothing is known to
1965 // use it, so performance here shouldn't be a worry.
1966 if ( $revid !== null ) {
1967 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1968 $store = $this->getRevisionStore();
1969 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1973 } elseif ( $revision instanceof Revision
) {
1974 $revision = $revision->getRevisionRecord();
1977 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
1978 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1980 if ( !$updater->isUpdatePrepared() ) {
1981 $updater->prepareContent( $user, $slots, $useCache );
1984 $updater->prepareUpdate(
1987 'causeAction' => 'prepare-edit',
1988 'causeAgent' => $user->getName(),
1994 return $updater->getPreparedEdit();
1998 * Do standard deferred updates after page edit.
1999 * Update links tables, site stats, search index and message cache.
2000 * Purges pages that include this page if the text was changed here.
2001 * Every 100th edit, prune the recent changes table.
2003 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2005 * @param Revision $revision
2006 * @param User $user User object that did the revision
2007 * @param array $options Array of options, following indexes are used:
2008 * - changed: bool, whether the revision changed the content (default true)
2009 * - created: bool, whether the revision created the page (default false)
2010 * - moved: bool, whether the page was moved (default false)
2011 * - restored: bool, whether the page was undeleted (default false)
2012 * - oldrevision: Revision object for the pre-update revision (default null)
2013 * - oldcountable: bool, null, or string 'no-change' (default null):
2014 * - bool: whether the page was counted as an article before that
2015 * revision, only used in changed is true and created is false
2016 * - null: if created is false, don't update the article count; if created
2017 * is true, do update the article count
2018 * - 'no-change': don't update the article count, ever
2019 * - causeAction: an arbitrary string identifying the reason for the update.
2020 * See DataUpdate::getCauseAction(). (default 'edit-page')
2021 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2022 * (string, defaults to the passed user)
2024 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2026 'causeAction' => 'edit-page',
2027 'causeAgent' => $user->getName(),
2030 $revision = $revision->getRevisionRecord();
2032 $updater = $this->getDerivedDataUpdater( $user, $revision );
2034 $updater->prepareUpdate( $revision, $options );
2036 $updater->doUpdates();
2040 * Update the parser cache.
2042 * @note This is a temporary workaround until there is a proper data updater class.
2043 * It will become deprecated soon.
2045 * @param array $options
2046 * - causeAction: an arbitrary string identifying the reason for the update.
2047 * See DataUpdate::getCauseAction(). (default 'edit-page')
2048 * - causeAgent: name of the user who caused the update (string, defaults to the
2049 * user who created the revision)
2052 public function updateParserCache( array $options = [] ) {
2053 $revision = $this->getRevisionRecord();
2054 if ( !$revision ||
!$revision->getId() ) {
2055 LoggerFactory
::getInstance( 'wikipage' )->info(
2056 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2060 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2062 $updater = $this->getDerivedDataUpdater( $user, $revision );
2063 $updater->prepareUpdate( $revision, $options );
2064 $updater->doParserCacheUpdate();
2068 * Do secondary data updates (such as updating link tables).
2069 * Secondary data updates are only a small part of the updates needed after saving
2070 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2071 * secondary data updates). This method is provided for partial purges.
2073 * @note This is a temporary workaround until there is a proper data updater class.
2074 * It will become deprecated soon.
2076 * @param array $options
2077 * - recursive (bool, default true): whether to do a recursive update (update pages that
2078 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2079 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2080 * was something that did not really change the page, such as a null edit.
2081 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2082 * user who created the revision)
2083 * - causeAction: an arbitrary string identifying the reason for the update.
2084 * See DataUpdate::getCauseAction(). (default 'unknown')
2085 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2086 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2087 * Note that even when this is set to false, some updates might still get deferred (as
2088 * some update might directly add child updates to DeferredUpdates).
2089 * - transactionTicket: a transaction ticket from LBFactory::getEmptyTransactionTicket(),
2090 * only when defer is false (default: null)
2093 public function doSecondaryDataUpdates( array $options = [] ) {
2094 $options['recursive'] = $options['recursive'] ??
true;
2095 $revision = $this->getRevisionRecord();
2096 if ( !$revision ||
!$revision->getId() ) {
2097 LoggerFactory
::getInstance( 'wikipage' )->info(
2098 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2102 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2104 $updater = $this->getDerivedDataUpdater( $user, $revision );
2105 $updater->prepareUpdate( $revision, $options );
2106 $updater->doSecondaryDataUpdates( $options );
2110 * Update the article's restriction field, and leave a log entry.
2111 * This works for protection both existing and non-existing pages.
2113 * @param array $limit Set of restriction keys
2114 * @param array $expiry Per restriction type expiration
2115 * @param int &$cascade Set to false if cascading protection isn't allowed.
2116 * @param string $reason
2117 * @param User $user The user updating the restrictions
2118 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2119 * ($user should be able to add the specified tags before this is called)
2120 * @return Status Status object; if action is taken, $status->value is the log_id of the
2121 * protection log entry.
2123 public function doUpdateRestrictions( array $limit, array $expiry,
2124 &$cascade, $reason, User
$user, $tags = null
2126 global $wgCascadingRestrictionLevels;
2128 if ( wfReadOnly() ) {
2129 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2132 $this->loadPageData( 'fromdbmaster' );
2133 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2134 $id = $this->getId();
2140 // Take this opportunity to purge out expired restrictions
2141 Title
::purgeExpiredRestrictions();
2143 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2144 // we expect a single selection, but the schema allows otherwise.
2145 $isProtected = false;
2149 $dbw = wfGetDB( DB_MASTER
);
2151 foreach ( $restrictionTypes as $action ) {
2152 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2153 $expiry[$action] = 'infinity';
2155 if ( !isset( $limit[$action] ) ) {
2156 $limit[$action] = '';
2157 } elseif ( $limit[$action] != '' ) {
2161 // Get current restrictions on $action
2162 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2163 if ( $current != '' ) {
2164 $isProtected = true;
2167 if ( $limit[$action] != $current ) {
2169 } elseif ( $limit[$action] != '' ) {
2170 // Only check expiry change if the action is actually being
2171 // protected, since expiry does nothing on an not-protected
2173 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2179 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2183 // If nothing has changed, do nothing
2185 return Status
::newGood();
2188 if ( !$protect ) { // No protection at all means unprotection
2189 $revCommentMsg = 'unprotectedarticle-comment';
2190 $logAction = 'unprotect';
2191 } elseif ( $isProtected ) {
2192 $revCommentMsg = 'modifiedarticleprotection-comment';
2193 $logAction = 'modify';
2195 $revCommentMsg = 'protectedarticle-comment';
2196 $logAction = 'protect';
2199 $logRelationsValues = [];
2200 $logRelationsField = null;
2201 $logParamsDetails = [];
2203 // Null revision (used for change tag insertion)
2204 $nullRevision = null;
2206 if ( $id ) { // Protection of existing page
2207 // Avoid PHP 7.1 warning of passing $this by reference
2210 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2211 return Status
::newGood();
2214 // Only certain restrictions can cascade...
2215 $editrestriction = isset( $limit['edit'] )
2216 ?
[ $limit['edit'] ]
2217 : $this->mTitle
->getRestrictions( 'edit' );
2218 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2219 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2221 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2222 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2225 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2226 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2227 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2229 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2230 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2233 // The schema allows multiple restrictions
2234 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2238 // insert null revision to identify the page protection change as edit summary
2239 $latest = $this->getLatest();
2240 $nullRevision = $this->insertProtectNullRevision(
2249 if ( $nullRevision === null ) {
2250 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2253 $logRelationsField = 'pr_id';
2255 // Update restrictions table
2256 foreach ( $limit as $action => $restrictions ) {
2258 'page_restrictions',
2261 'pr_type' => $action
2265 if ( $restrictions != '' ) {
2266 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2268 'page_restrictions',
2271 'pr_type' => $action,
2272 'pr_level' => $restrictions,
2273 'pr_cascade' => $cascadeValue,
2274 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2278 $logRelationsValues[] = $dbw->insertId();
2279 $logParamsDetails[] = [
2281 'level' => $restrictions,
2282 'expiry' => $expiry[$action],
2283 'cascade' => (bool)$cascadeValue,
2288 // Clear out legacy restriction fields
2291 [ 'page_restrictions' => '' ],
2292 [ 'page_id' => $id ],
2296 // Avoid PHP 7.1 warning of passing $this by reference
2299 Hooks
::run( 'NewRevisionFromEditComplete',
2300 [ $this, $nullRevision, $latest, $user ] );
2301 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2302 } else { // Protection of non-existing page (also known as "title protection")
2303 // Cascade protection is meaningless in this case
2306 if ( $limit['create'] != '' ) {
2307 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2308 $dbw->replace( 'protected_titles',
2309 [ [ 'pt_namespace', 'pt_title' ] ],
2311 'pt_namespace' => $this->mTitle
->getNamespace(),
2312 'pt_title' => $this->mTitle
->getDBkey(),
2313 'pt_create_perm' => $limit['create'],
2314 'pt_timestamp' => $dbw->timestamp(),
2315 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2316 'pt_user' => $user->getId(),
2317 ] +
$commentFields, __METHOD__
2319 $logParamsDetails[] = [
2321 'level' => $limit['create'],
2322 'expiry' => $expiry['create'],
2325 $dbw->delete( 'protected_titles',
2327 'pt_namespace' => $this->mTitle
->getNamespace(),
2328 'pt_title' => $this->mTitle
->getDBkey()
2334 $this->mTitle
->flushRestrictions();
2335 InfoAction
::invalidateCache( $this->mTitle
);
2337 if ( $logAction == 'unprotect' ) {
2340 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2342 '4::description' => $protectDescriptionLog, // parameter for IRC
2343 '5:bool:cascade' => $cascade,
2344 'details' => $logParamsDetails, // parameter for localize and api
2348 // Update the protection log
2349 $logEntry = new ManualLogEntry( 'protect', $logAction );
2350 $logEntry->setTarget( $this->mTitle
);
2351 $logEntry->setComment( $reason );
2352 $logEntry->setPerformer( $user );
2353 $logEntry->setParameters( $params );
2354 if ( !is_null( $nullRevision ) ) {
2355 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2357 $logEntry->setTags( $tags );
2358 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2359 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2361 $logId = $logEntry->insert();
2362 $logEntry->publish( $logId );
2364 return Status
::newGood( $logId );
2368 * Insert a new null revision for this page.
2370 * @param string $revCommentMsg Comment message key for the revision
2371 * @param array $limit Set of restriction keys
2372 * @param array $expiry Per restriction type expiration
2373 * @param int $cascade Set to false if cascading protection isn't allowed.
2374 * @param string $reason
2375 * @param User|null $user
2376 * @return Revision|null Null on error
2378 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2379 array $expiry, $cascade, $reason, $user = null
2381 $dbw = wfGetDB( DB_MASTER
);
2383 // Prepare a null revision to be added to the history
2384 $editComment = wfMessage(
2386 $this->mTitle
->getPrefixedText(),
2387 $user ?
$user->getName() : ''
2388 )->inContentLanguage()->text();
2390 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2392 $protectDescription = $this->protectDescription( $limit, $expiry );
2393 if ( $protectDescription ) {
2394 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2395 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2396 ->inContentLanguage()->text();
2399 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2400 $editComment .= wfMessage( 'brackets' )->params(
2401 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2402 )->inContentLanguage()->text();
2405 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2407 $nullRev->insertOn( $dbw );
2409 // Update page record and touch page
2410 $oldLatest = $nullRev->getParentId();
2411 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2418 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2421 protected function formatExpiry( $expiry ) {
2422 if ( $expiry != 'infinity' ) {
2423 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2426 $contLang->timeanddate( $expiry, false, false ),
2427 $contLang->date( $expiry, false, false ),
2428 $contLang->time( $expiry, false, false )
2429 )->inContentLanguage()->text();
2431 return wfMessage( 'protect-expiry-indefinite' )
2432 ->inContentLanguage()->text();
2437 * Builds the description to serve as comment for the edit.
2439 * @param array $limit Set of restriction keys
2440 * @param array $expiry Per restriction type expiration
2443 public function protectDescription( array $limit, array $expiry ) {
2444 $protectDescription = '';
2446 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2447 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2448 # All possible message keys are listed here for easier grepping:
2449 # * restriction-create
2450 # * restriction-edit
2451 # * restriction-move
2452 # * restriction-upload
2453 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2454 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2455 # with '' filtered out. All possible message keys are listed below:
2456 # * protect-level-autoconfirmed
2457 # * protect-level-sysop
2458 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2459 ->inContentLanguage()->text();
2461 $expiryText = $this->formatExpiry( $expiry[$action] );
2463 if ( $protectDescription !== '' ) {
2464 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2466 $protectDescription .= wfMessage( 'protect-summary-desc' )
2467 ->params( $actionText, $restrictionsText, $expiryText )
2468 ->inContentLanguage()->text();
2471 return $protectDescription;
2475 * Builds the description to serve as comment for the log entry.
2477 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2478 * protect description text. Keep them in old format to avoid breaking compatibility.
2479 * TODO: Fix protection log to store structured description and format it on-the-fly.
2481 * @param array $limit Set of restriction keys
2482 * @param array $expiry Per restriction type expiration
2485 public function protectDescriptionLog( array $limit, array $expiry ) {
2486 $protectDescriptionLog = '';
2488 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2489 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2490 $expiryText = $this->formatExpiry( $expiry[$action] );
2491 $protectDescriptionLog .=
2493 "[$action=$restrictions] ($expiryText)";
2496 return trim( $protectDescriptionLog );
2500 * Take an array of page restrictions and flatten it to a string
2501 * suitable for insertion into the page_restrictions field.
2503 * @param string[] $limit
2505 * @throws MWException
2508 protected static function flattenRestrictions( $limit ) {
2509 if ( !is_array( $limit ) ) {
2510 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2516 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2517 $bits[] = "$action=$restrictions";
2520 return implode( ':', $bits );
2524 * Determines if deletion of this page would be batched (executed over time by the job queue)
2525 * or not (completed in the same request as the delete call).
2527 * It is unlikely but possible that an edit from another request could push the page over the
2528 * batching threshold after this function is called, but before the caller acts upon the
2529 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2530 * is provided as an unreliable but situationally useful help for some common cases.
2532 * @param int $safetyMargin Added to the revision count when checking for batching
2533 * @return bool True if deletion would be batched, false otherwise
2535 public function isBatchedDelete( $safetyMargin = 0 ) {
2536 global $wgDeleteRevisionsBatchSize;
2538 $dbr = wfGetDB( DB_REPLICA
);
2539 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2540 $revCount +
= $safetyMargin;
2542 return $revCount >= $wgDeleteRevisionsBatchSize;
2546 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2547 * backwards compatibility, if you care about error reporting you should use
2548 * doDeleteArticleReal() instead.
2550 * Deletes the article with database consistency, writes logs, purges caches
2552 * @param string $reason Delete reason for deletion log
2553 * @param bool $suppress Suppress all revisions and log the deletion in
2554 * the suppression log instead of the deletion log
2555 * @param int|null $u1 Unused
2556 * @param bool|null $u2 Unused
2557 * @param array|string &$error Array of errors to append to
2558 * @param User|null $user The deleting user
2559 * @param bool $immediate false allows deleting over time via the job queue
2560 * @return bool True if successful
2561 * @throws FatalError
2562 * @throws MWException
2564 public function doDeleteArticle(
2565 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2568 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2569 [], 'delete', $immediate );
2571 // Returns true if the page was actually deleted, or is scheduled for deletion
2572 return $status->isOK();
2576 * Back-end article deletion
2577 * Deletes the article with database consistency, writes logs, purges caches
2581 * @param string $reason Delete reason for deletion log
2582 * @param bool $suppress Suppress all revisions and log the deletion in
2583 * the suppression log instead of the deletion log
2584 * @param int|null $u1 Unused
2585 * @param bool|null $u2 Unused
2586 * @param array|string &$error Array of errors to append to
2587 * @param User|null $deleter The deleting user
2588 * @param array $tags Tags to apply to the deletion action
2589 * @param string $logsubtype
2590 * @param bool $immediate false allows deleting over time via the job queue
2591 * @return Status Status object; if successful, $status->value is the log_id of the
2592 * deletion log entry. If the page couldn't be deleted because it wasn't
2593 * found, $status is a non-fatal 'cannotdelete' error
2594 * @throws FatalError
2595 * @throws MWException
2597 public function doDeleteArticleReal(
2598 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2599 $tags = [], $logsubtype = 'delete', $immediate = false
2603 wfDebug( __METHOD__
. "\n" );
2605 $status = Status
::newGood();
2607 // Avoid PHP 7.1 warning of passing $this by reference
2610 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2611 if ( !Hooks
::run( 'ArticleDelete',
2612 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2614 if ( $status->isOK() ) {
2615 // Hook aborted but didn't set a fatal status
2616 $status->fatal( 'delete-hook-aborted' );
2621 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2622 $logsubtype, $immediate );
2626 * Back-end article deletion
2628 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2629 * Deletions can often be completed inline without involving the job queue.
2631 * Potentially called many times per deletion operation for pages with many revisions.
2633 public function doDeleteArticleBatched(
2634 $reason, $suppress, User
$deleter, $tags,
2635 $logsubtype, $immediate = false, $webRequestId = null
2637 wfDebug( __METHOD__
. "\n" );
2639 $status = Status
::newGood();
2641 $dbw = wfGetDB( DB_MASTER
);
2642 $dbw->startAtomic( __METHOD__
);
2644 $this->loadPageData( self
::READ_LATEST
);
2645 $id = $this->getId();
2646 // T98706: lock the page from various other updates but avoid using
2647 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2648 // the revisions queries (which also JOIN on user). Only lock the page
2649 // row and CAS check on page_latest to see if the trx snapshot matches.
2650 $lockedLatest = $this->lockAndGetLatest();
2651 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2652 $dbw->endAtomic( __METHOD__
);
2653 // Page not there or trx snapshot is stale
2654 $status->error( 'cannotdelete',
2655 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2659 // At this point we are now committed to returning an OK
2660 // status unless some DB query error or other exception comes up.
2661 // This way callers don't have to call rollback() if $status is bad
2662 // unless they actually try to catch exceptions (which is rare).
2664 // we need to remember the old content so we can use it to generate all deletion updates.
2665 $revision = $this->getRevision();
2667 $content = $this->getContent( Revision
::RAW
);
2668 } catch ( Exception
$ex ) {
2669 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2670 . $ex->getMessage() );
2675 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2676 // one batch of revisions and defer archival of any others to the job queue.
2677 $explictTrxLogged = false;
2679 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2680 if ( $done ||
!$immediate ) {
2683 $dbw->endAtomic( __METHOD__
);
2684 if ( $dbw->explicitTrxActive() ) {
2685 // Explict transactions may never happen here in practice. Log to be sure.
2686 if ( !$explictTrxLogged ) {
2687 $explictTrxLogged = true;
2688 LoggerFactory
::getInstance( 'wfDebug' )->debug(
2689 'explicit transaction active in ' . __METHOD__
. ' while deleting {title}', [
2690 'title' => $this->getTitle()->getText(),
2695 if ( $dbw->trxLevel() ) {
2698 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
2699 $lbFactory->waitForReplication();
2700 $dbw->startAtomic( __METHOD__
);
2703 // If done archiving, also delete the article.
2705 $dbw->endAtomic( __METHOD__
);
2708 'wikiPageId' => $id,
2709 'requestId' => $webRequestId ?? WebRequest
::getRequestId(),
2710 'reason' => $reason,
2711 'suppress' => $suppress,
2712 'userId' => $deleter->getId(),
2713 'tags' => json_encode( $tags ),
2714 'logsubtype' => $logsubtype,
2717 $job = new DeletePageJob( $this->getTitle(), $jobParams );
2718 JobQueueGroup
::singleton()->push( $job );
2720 $status->warning( 'delete-scheduled',
2721 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2723 // Get archivedRevisionCount by db query, because there's no better alternative.
2724 // Jobs cannot pass a count of archived revisions to the next job, because additional
2725 // deletion operations can be started while the first is running. Jobs from each
2726 // gracefully interleave, but would not know about each other's count. Deduplication
2727 // in the job queue to avoid simultaneous deletion operations would add overhead.
2728 // Number of archived revisions cannot be known beforehand, because edits can be made
2729 // while deletion operations are being processed, changing the number of archivals.
2730 $archivedRevisionCount = $dbw->selectField(
2731 'archive', 'COUNT(*)',
2733 'ar_namespace' => $this->getTitle()->getNamespace(),
2734 'ar_title' => $this->getTitle()->getDBkey(),
2739 // Clone the title and wikiPage, so we have the information we need when
2740 // we log and run the ArticleDeleteComplete hook.
2741 $logTitle = clone $this->mTitle
;
2742 $wikiPageBeforeDelete = clone $this;
2744 // Now that it's safely backed up, delete it
2745 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2747 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2748 $logtype = $suppress ?
'suppress' : 'delete';
2750 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2751 $logEntry->setPerformer( $deleter );
2752 $logEntry->setTarget( $logTitle );
2753 $logEntry->setComment( $reason );
2754 $logEntry->setTags( $tags );
2755 $logid = $logEntry->insert();
2757 $dbw->onTransactionPreCommitOrIdle(
2758 function () use ( $logEntry, $logid ) {
2759 // T58776: avoid deadlocks (especially from FileDeleteForm)
2760 $logEntry->publish( $logid );
2765 $dbw->endAtomic( __METHOD__
);
2767 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2769 Hooks
::run( 'ArticleDeleteComplete', [
2770 &$wikiPageBeforeDelete,
2776 $archivedRevisionCount
2778 $status->value
= $logid;
2780 // Show log excerpt on 404 pages rather than just a link
2781 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2782 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2783 $cache->set( $key, 1, $cache::TTL_DAY
);
2790 * Archives revisions as part of page deletion.
2792 * @param IDatabase $dbw
2794 * @param bool $suppress Suppress all revisions and log the deletion in
2795 * the suppression log instead of the deletion log
2798 protected function archiveRevisions( $dbw, $id, $suppress ) {
2799 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2800 $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage,
2801 $wgDeleteRevisionsBatchSize;
2803 // Given the lock above, we can be confident in the title and page ID values
2804 $namespace = $this->getTitle()->getNamespace();
2805 $dbKey = $this->getTitle()->getDBkey();
2807 $commentStore = CommentStore
::getStore();
2808 $actorMigration = ActorMigration
::newMigration();
2810 $revQuery = Revision
::getQueryInfo();
2813 // Bitfields to further suppress the content
2815 $bitfield = Revision
::SUPPRESSED_ALL
;
2816 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2819 // For now, shunt the revision data into the archive table.
2820 // Text is *not* removed from the text table; bulk storage
2821 // is left intact to avoid breaking block-compression or
2822 // immutable storage schemes.
2823 // In the future, we may keep revisions and mark them with
2824 // the rev_deleted field, which is reserved for this purpose.
2826 // Lock rows in `revision` and its temp tables, but not any others.
2827 // Note array_intersect() preserves keys from the first arg, and we're
2828 // assuming $revQuery has `revision` primary and isn't using subtables
2829 // for anything we care about.
2830 $dbw->lockForUpdate(
2832 $revQuery['tables'],
2833 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2835 [ 'rev_page' => $id ],
2841 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2842 // so we can copy it to the archive table.
2843 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2844 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2845 $revQuery['fields'][] = 'rev_text_id';
2847 if ( $wgContentHandlerUseDB ) {
2848 $revQuery['fields'][] = 'rev_content_model';
2849 $revQuery['fields'][] = 'rev_content_format';
2853 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2854 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2855 $res = $dbw->select(
2856 $revQuery['tables'],
2857 $revQuery['fields'],
2858 [ 'rev_page' => $id ],
2860 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize +
1 ],
2864 // Build their equivalent archive rows
2868 /** @var int[] Revision IDs of edits that were made by IPs */
2872 foreach ( $res as $row ) {
2873 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2878 $comment = $commentStore->getComment( 'rev_comment', $row );
2879 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2881 'ar_namespace' => $namespace,
2882 'ar_title' => $dbKey,
2883 'ar_timestamp' => $row->rev_timestamp
,
2884 'ar_minor_edit' => $row->rev_minor_edit
,
2885 'ar_rev_id' => $row->rev_id
,
2886 'ar_parent_id' => $row->rev_parent_id
,
2888 * ar_text_id should probably not be written to when the multi content schema has
2889 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2890 * default for the field in WMF production currently so we must keep writing
2891 * writing until a default of 0 is set.
2892 * Task: https://phabricator.wikimedia.org/T190148
2893 * Copying the value from the revision table should not lead to any issues for now.
2895 'ar_len' => $row->rev_len
,
2896 'ar_page_id' => $id,
2897 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2898 'ar_sha1' => $row->rev_sha1
,
2899 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2900 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2902 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2903 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2905 if ( $wgContentHandlerUseDB ) {
2906 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2907 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2911 $rowsInsert[] = $rowInsert;
2912 $revids[] = $row->rev_id
;
2914 // Keep track of IP edits, so that the corresponding rows can
2915 // be deleted in the ip_changes table.
2916 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2917 $ipRevIds[] = $row->rev_id
;
2921 // This conditional is just a sanity check
2922 if ( count( $revids ) > 0 ) {
2923 // Copy them into the archive table
2924 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2926 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__
);
2927 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2928 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2930 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2931 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2934 // Also delete records from ip_changes as applicable.
2935 if ( count( $ipRevIds ) > 0 ) {
2936 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2944 * Lock the page row for this title+id and return page_latest (or 0)
2946 * @return int Returns 0 if no row was found with this title+id
2949 public function lockAndGetLatest() {
2950 return (int)wfGetDB( DB_MASTER
)->selectField(
2954 'page_id' => $this->getId(),
2955 // Typically page_id is enough, but some code might try to do
2956 // updates assuming the title is the same, so verify that
2957 'page_namespace' => $this->getTitle()->getNamespace(),
2958 'page_title' => $this->getTitle()->getDBkey()
2966 * Do some database updates after deletion
2968 * @param int $id The page_id value of the page being deleted
2969 * @param Content|null $content Page content to be used when determining
2970 * the required updates. This may be needed because $this->getContent()
2971 * may already return null when the page proper was deleted.
2972 * @param RevisionRecord|Revision|null $revision The current page revision at the time of
2973 * deletion, used when determining the required updates. This may be needed because
2974 * $this->getRevision() may already return null when the page proper was deleted.
2975 * @param User|null $user The user that caused the deletion
2977 public function doDeleteUpdates(
2978 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2980 if ( $id !== $this->getId() ) {
2981 throw new InvalidArgumentException( 'Mismatching page ID' );
2985 $countable = $this->isCountable();
2986 } catch ( Exception
$ex ) {
2987 // fallback for deleting broken pages for which we cannot load the content for
2988 // some reason. Note that doDeleteArticleReal() already logged this problem.
2992 // Update site status
2993 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2994 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2997 // Delete pagelinks, update secondary indexes, etc
2998 $updates = $this->getDeletionUpdates(
2999 $revision ?
$revision->getRevisionRecord() : $content
3001 foreach ( $updates as $update ) {
3002 DeferredUpdates
::addUpdate( $update );
3005 $causeAgent = $user ?
$user->getName() : 'unknown';
3006 // Reparse any pages transcluding this page
3007 LinksUpdate
::queueRecursiveJobsForTable(
3008 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3009 // Reparse any pages including this image
3010 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3011 LinksUpdate
::queueRecursiveJobsForTable(
3012 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3016 self
::onArticleDelete( $this->mTitle
);
3017 ResourceLoaderWikiModule
::invalidateModuleCache(
3018 $this->mTitle
, $revision, null, wfWikiID()
3021 // Reset this object and the Title object
3022 $this->loadFromRow( false, self
::READ_LATEST
);
3025 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3029 * Roll back the most recent consecutive set of edits to a page
3030 * from the same user; fails if there are no eligible edits to
3031 * roll back to, e.g. user is the sole contributor. This function
3032 * performs permissions checks on $user, then calls commitRollback()
3033 * to do the dirty work
3035 * @todo Separate the business/permission stuff out from backend code
3036 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3038 * @param string $fromP Name of the user whose edits to rollback.
3039 * @param string $summary Custom summary. Set to default summary if empty.
3040 * @param string $token Rollback token.
3041 * @param bool $bot If true, mark all reverted edits as bot.
3043 * @param array &$resultDetails Array contains result-specific array of additional values
3044 * 'alreadyrolled' : 'current' (rev)
3045 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3047 * @param User $user The user performing the rollback
3048 * @param array|null $tags Change tags to apply to the rollback
3049 * Callers are responsible for permission checks
3050 * (with ChangeTags::canAddTagsAccompanyingChange)
3052 * @return array Array of errors, each error formatted as
3053 * array(messagekey, param1, param2, ...).
3054 * On success, the array is empty. This array can also be passed to
3055 * OutputPage::showPermissionsErrorPage().
3057 public function doRollback(
3058 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3060 $resultDetails = null;
3062 // Check permissions
3063 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3064 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3065 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3067 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3068 $errors[] = [ 'sessionfailure' ];
3071 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3072 $errors[] = [ 'actionthrottledtext' ];
3075 // If there were errors, bail out now
3076 if ( !empty( $errors ) ) {
3080 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3084 * Backend implementation of doRollback(), please refer there for parameter
3085 * and return value documentation
3087 * NOTE: This function does NOT check ANY permissions, it just commits the
3088 * rollback to the DB. Therefore, you should only call this function direct-
3089 * ly if you want to use custom permissions checks. If you don't, use
3090 * doRollback() instead.
3091 * @param string $fromP Name of the user whose edits to rollback.
3092 * @param string $summary Custom summary. Set to default summary if empty.
3093 * @param bool $bot If true, mark all reverted edits as bot.
3095 * @param array &$resultDetails Contains result-specific array of additional values
3096 * @param User $guser The user performing the rollback
3097 * @param array|null $tags Change tags to apply to the rollback
3098 * Callers are responsible for permission checks
3099 * (with ChangeTags::canAddTagsAccompanyingChange)
3101 * @return array An array of error messages, as returned by Status::getErrorsArray()
3103 public function commitRollback( $fromP, $summary, $bot,
3104 &$resultDetails, User
$guser, $tags = null
3106 global $wgUseRCPatrol;
3108 $dbw = wfGetDB( DB_MASTER
);
3110 if ( wfReadOnly() ) {
3111 return [ [ 'readonlytext' ] ];
3114 // Begin revision creation cycle by creating a PageUpdater.
3115 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3116 $updater = $this->newPageUpdater( $guser );
3117 $current = $updater->grabParentRevision();
3119 if ( is_null( $current ) ) {
3120 // Something wrong... no page?
3121 return [ [ 'notanarticle' ] ];
3124 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
3125 $legacyCurrent = new Revision( $current );
3126 $from = str_replace( '_', ' ', $fromP );
3128 // User name given should match up with the top revision.
3129 // If the revision's user is not visible, then $from should be empty.
3130 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
3131 $resultDetails = [ 'current' => $legacyCurrent ];
3132 return [ [ 'alreadyrolled',
3133 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3134 htmlspecialchars( $fromP ),
3135 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3139 // Get the last edit not by this person...
3140 // Note: these may not be public values
3141 $actorWhere = ActorMigration
::newMigration()->getWhere(
3144 $current->getUser( RevisionRecord
::RAW
)
3147 $s = $dbw->selectRow(
3148 [ 'revision' ] +
$actorWhere['tables'],
3149 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3151 'rev_page' => $current->getPageId(),
3152 'NOT(' . $actorWhere['conds'] . ')',
3156 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3157 'ORDER BY' => 'rev_timestamp DESC'
3159 $actorWhere['joins']
3161 if ( $s === false ) {
3162 // No one else ever edited this page
3163 return [ [ 'cantrollback' ] ];
3164 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3165 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3167 // Only admins can see this text
3168 return [ [ 'notvisiblerev' ] ];
3171 // Generate the edit summary if necessary
3172 $target = $this->getRevisionStore()->getRevisionById(
3174 RevisionStore
::READ_LATEST
3176 if ( empty( $summary ) ) {
3177 if ( !$currentEditorForPublic ) { // no public user name
3178 $summary = wfMessage( 'revertpage-nouser' );
3180 $summary = wfMessage( 'revertpage' );
3183 $legacyTarget = new Revision( $target );
3184 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3186 // Allow the custom summary to use the same args as the default message
3187 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3189 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3190 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3192 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3194 $contLang->timeanddate( $current->getTimestamp() )
3196 if ( $summary instanceof Message
) {
3197 $summary = $summary->params( $args )->inContentLanguage()->text();
3199 $summary = wfMsgReplaceArgs( $summary, $args );
3202 // Trim spaces on user supplied text
3203 $summary = trim( $summary );
3206 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3208 if ( $guser->isAllowed( 'minoredit' ) ) {
3209 $flags |
= EDIT_MINOR
;
3212 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3213 $flags |
= EDIT_FORCE_BOT
;
3216 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3217 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3218 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3219 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3221 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3222 $tags[] = 'mw-rollback';
3225 // Build rollback revision:
3226 // Restore old content
3227 // TODO: MCR: test this once we can store multiple slots
3228 foreach ( $target->getSlots()->getSlots() as $slot ) {
3229 $updater->inheritSlot( $slot );
3232 // Remove extra slots
3233 // TODO: MCR: test this once we can store multiple slots
3234 foreach ( $current->getSlotRoles() as $role ) {
3235 if ( !$target->hasSlot( $role ) ) {
3236 $updater->removeSlot( $role );
3240 $updater->setOriginalRevisionId( $target->getId() );
3241 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3242 $updater->addTags( $tags );
3244 // TODO: this logic should not be in the storage layer, it's here for compatibility
3245 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3246 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3247 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
3248 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3251 // Actually store the rollback
3252 $rev = $updater->saveRevision(
3253 CommentStoreComment
::newUnsavedComment( $summary ),
3257 // Set patrolling and bot flag on the edits, which gets rollbacked.
3258 // This is done even on edit failure to have patrolling in that case (T64157).
3260 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3261 // Mark all reverted edits as bot
3265 if ( $wgUseRCPatrol ) {
3266 // Mark all reverted edits as patrolled
3267 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3270 if ( count( $set ) ) {
3271 $actorWhere = ActorMigration
::newMigration()->getWhere(
3274 $current->getUser( RevisionRecord
::RAW
),
3277 $dbw->update( 'recentchanges', $set,
3279 'rc_cur_id' => $current->getPageId(),
3280 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3281 $actorWhere['conds'], // No tables/joins are needed for rc_user
3287 if ( !$updater->wasSuccessful() ) {
3288 return $updater->getStatus()->getErrorsArray();
3291 // Report if the edit was not created because it did not change the content.
3292 if ( $updater->isUnchanged() ) {
3293 $resultDetails = [ 'current' => $legacyCurrent ];
3294 return [ [ 'alreadyrolled',
3295 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3296 htmlspecialchars( $fromP ),
3297 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3301 if ( $changingContentModel ) {
3302 // If the content model changed during the rollback,
3303 // make sure it gets logged to Special:Log/contentmodel
3304 $log = new ManualLogEntry( 'contentmodel', 'change' );
3305 $log->setPerformer( $guser );
3306 $log->setTarget( $this->mTitle
);
3307 $log->setComment( $summary );
3308 $log->setParameters( [
3309 '4::oldmodel' => $currentContent->getModel(),
3310 '5::newmodel' => $targetContent->getModel(),
3313 $logId = $log->insert( $dbw );
3314 $log->publish( $logId );
3317 $revId = $rev->getId();
3319 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3322 'summary' => $summary,
3323 'current' => $legacyCurrent,
3324 'target' => $legacyTarget,
3329 // TODO: make this return a Status object and wrap $resultDetails in that.
3334 * The onArticle*() functions are supposed to be a kind of hooks
3335 * which should be called whenever any of the specified actions
3338 * This is a good place to put code to clear caches, for instance.
3340 * This is called on page move and undelete, as well as edit
3342 * @param Title $title
3344 public static function onArticleCreate( Title
$title ) {
3345 // TODO: move this into a PageEventEmitter service
3347 // Update existence markers on article/talk tabs...
3348 $other = $title->getOtherPage();
3350 $other->purgeSquid();
3352 $title->touchLinks();
3353 $title->purgeSquid();
3354 $title->deleteTitleProtection();
3356 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3358 // Invalidate caches of articles which include this page
3359 DeferredUpdates
::addUpdate(
3360 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3363 if ( $title->getNamespace() == NS_CATEGORY
) {
3364 // Load the Category object, which will schedule a job to create
3365 // the category table row if necessary. Checking a replica DB is ok
3366 // here, in the worst case it'll run an unnecessary recount job on
3367 // a category that probably doesn't have many members.
3368 Category
::newFromTitle( $title )->getID();
3373 * Clears caches when article is deleted
3375 * @param Title $title
3377 public static function onArticleDelete( Title
$title ) {
3378 // TODO: move this into a PageEventEmitter service
3380 // Update existence markers on article/talk tabs...
3381 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3382 BacklinkCache
::get( $title )->clear();
3383 $other = $title->getOtherPage();
3385 $other->purgeSquid();
3387 $title->touchLinks();
3388 $title->purgeSquid();
3390 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3393 HTMLFileCache
::clearFileCache( $title );
3394 InfoAction
::invalidateCache( $title );
3397 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3398 MessageCache
::singleton()->updateMessageOverride( $title, null );
3402 if ( $title->getNamespace() == NS_FILE
) {
3403 DeferredUpdates
::addUpdate(
3404 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3409 if ( $title->getNamespace() == NS_USER_TALK
) {
3410 $user = User
::newFromName( $title->getText(), false );
3412 $user->setNewtalk( false );
3417 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3419 // Purge cross-wiki cache entities referencing this page
3420 self
::purgeInterwikiCheckKey( $title );
3424 * Purge caches on page update etc
3426 * @param Title $title
3427 * @param Revision|null $revision Revision that was just saved, may be null
3428 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3429 * If not given, all slots are assumed to have changed.
3431 public static function onArticleEdit(
3433 Revision
$revision = null,
3434 $slotsChanged = null
3436 // TODO: move this into a PageEventEmitter service
3438 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3439 // Invalidate caches of articles which include this page.
3440 // Only for the main slot, because only the main slot is transcluded.
3441 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3442 DeferredUpdates
::addUpdate(
3443 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3447 // Invalidate the caches of all pages which redirect here
3448 DeferredUpdates
::addUpdate(
3449 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3452 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3454 // Purge CDN for this page only
3455 $title->purgeSquid();
3456 // Clear file cache for this page only
3457 HTMLFileCache
::clearFileCache( $title );
3459 // Purge ?action=info cache
3460 $revid = $revision ?
$revision->getId() : null;
3461 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3462 InfoAction
::invalidateCache( $title, $revid );
3465 // Purge cross-wiki cache entities referencing this page
3466 self
::purgeInterwikiCheckKey( $title );
3472 * Purge the check key for cross-wiki cache entries referencing this page
3474 * @param Title $title
3476 private static function purgeInterwikiCheckKey( Title
$title ) {
3477 global $wgEnableScaryTranscluding;
3479 if ( !$wgEnableScaryTranscluding ) {
3480 return; // @todo: perhaps this wiki is only used as a *source* for content?
3483 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3484 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3485 $cache->resetCheckKey(
3486 // Do not include the namespace since there can be multiple aliases to it
3487 // due to different namespace text definitions on different wikis. This only
3488 // means that some cache invalidations happen that are not strictly needed.
3489 $cache->makeGlobalKey( 'interwiki-page', wfWikiID(), $title->getDBkey() )
3495 * Returns a list of categories this page is a member of.
3496 * Results will include hidden categories
3498 * @return TitleArray
3500 public function getCategories() {
3501 $id = $this->getId();
3503 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3506 $dbr = wfGetDB( DB_REPLICA
);
3507 $res = $dbr->select( 'categorylinks',
3508 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3509 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3510 // as not being aliases, and NS_CATEGORY is numeric
3511 [ 'cl_from' => $id ],
3514 return TitleArray
::newFromResult( $res );
3518 * Returns a list of hidden categories this page is a member of.
3519 * Uses the page_props and categorylinks tables.
3521 * @return array Array of Title objects
3523 public function getHiddenCategories() {
3525 $id = $this->getId();
3531 $dbr = wfGetDB( DB_REPLICA
);
3532 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3534 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3535 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3538 if ( $res !== false ) {
3539 foreach ( $res as $row ) {
3540 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3548 * Auto-generates a deletion reason
3550 * @param bool &$hasHistory Whether the page has a history
3551 * @return string|bool String containing deletion reason or empty string, or boolean false
3552 * if no revision occurred
3554 public function getAutoDeleteReason( &$hasHistory ) {
3555 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3559 * Update all the appropriate counts in the category table, given that
3560 * we've added the categories $added and deleted the categories $deleted.
3562 * This should only be called from deferred updates or jobs to avoid contention.
3564 * @param array $added The names of categories that were added
3565 * @param array $deleted The names of categories that were deleted
3566 * @param int $id Page ID (this should be the original deleted page ID)
3568 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3569 $id = $id ?
: $this->getId();
3570 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3572 $addFields = [ 'cat_pages = cat_pages + 1' ];
3573 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3574 if ( $type !== 'page' ) {
3575 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3576 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3579 $dbw = wfGetDB( DB_MASTER
);
3581 if ( count( $added ) ) {
3582 $existingAdded = $dbw->selectFieldValues(
3585 [ 'cat_title' => $added ],
3589 // For category rows that already exist, do a plain
3590 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3591 // to avoid creating gaps in the cat_id sequence.
3592 if ( count( $existingAdded ) ) {
3596 [ 'cat_title' => $existingAdded ],
3601 $missingAdded = array_diff( $added, $existingAdded );
3602 if ( count( $missingAdded ) ) {
3604 foreach ( $missingAdded as $cat ) {
3606 'cat_title' => $cat,
3608 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3609 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3622 if ( count( $deleted ) ) {
3626 [ 'cat_title' => $deleted ],
3631 foreach ( $added as $catName ) {
3632 $cat = Category
::newFromName( $catName );
3633 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3636 foreach ( $deleted as $catName ) {
3637 $cat = Category
::newFromName( $catName );
3638 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3639 // Refresh counts on categories that should be empty now (after commit, T166757)
3640 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3641 $cat->refreshCountsIfEmpty();
3647 * Opportunistically enqueue link update jobs given fresh parser output if useful
3649 * @param ParserOutput $parserOutput Current version page output
3652 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3653 if ( wfReadOnly() ) {
3657 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3658 [ $this, $this->mTitle
, $parserOutput ]
3663 $config = RequestContext
::getMain()->getConfig();
3666 'isOpportunistic' => true,
3667 'rootJobTimestamp' => $parserOutput->getCacheTime()
3670 if ( $this->mTitle
->areRestrictionsCascading() ) {
3671 // If the page is cascade protecting, the links should really be up-to-date
3672 JobQueueGroup
::singleton()->lazyPush(
3673 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3675 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3676 // Assume the output contains "dynamic" time/random based magic words.
3677 // Only update pages that expired due to dynamic content and NOT due to edits
3678 // to referenced templates/files. When the cache expires due to dynamic content,
3679 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3680 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3681 // template/file edit already triggered recursive RefreshLinksJob jobs.
3682 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3683 // If a page is uncacheable, do not keep spamming a job for it.
3684 // Although it would be de-duplicated, it would still waste I/O.
3685 $cache = ObjectCache
::getLocalClusterInstance();
3686 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3687 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3688 if ( $cache->add( $key, time(), $ttl ) ) {
3689 JobQueueGroup
::singleton()->lazyPush(
3690 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3698 * Returns a list of updates to be performed when this page is deleted. The
3699 * updates should remove any information about this page from secondary data
3700 * stores such as links tables.
3702 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3703 * object for backwards compatibility.
3704 * @return DeferrableUpdate[]
3706 public function getDeletionUpdates( $rev = null ) {
3708 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3711 $rev = $this->getRevisionRecord();
3712 } catch ( Exception
$ex ) {
3713 // If we can't load the content, something is wrong. Perhaps that's why
3714 // the user is trying to delete the page, so let's not fail in that case.
3715 // Note that doDeleteArticleReal() will already have logged an issue with
3716 // loading the content.
3717 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3723 } elseif ( $rev instanceof Content
) {
3724 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3726 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3728 $slotContent = array_map( function ( SlotRecord
$slot ) {
3729 return $slot->getContent( Revision
::RAW
);
3730 }, $rev->getSlots()->getSlots() );
3733 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3735 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3736 // model here, not the content object!
3737 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3738 /** @var Content $content */
3739 foreach ( $slotContent as $role => $content ) {
3740 $handler = $content->getContentHandler();
3742 $updates = $handler->getDeletionUpdates(
3746 $allUpdates = array_merge( $allUpdates, $updates );
3748 // TODO: remove B/C hack in 1.32!
3749 $legacyUpdates = $content->getDeletionUpdates( $this );
3751 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3752 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3753 return !( $update instanceof LinksDeletionUpdate
);
3756 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3759 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3761 // TODO: hard deprecate old hook in 1.33
3762 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3767 * Whether this content displayed on this page
3768 * comes from the local database
3773 public function isLocal() {
3778 * The display name for the site this content
3779 * come from. If a subclass overrides isLocal(),
3780 * this could return something other than the
3786 public function getWikiDisplayName() {
3792 * Get the source URL for the content on this page,
3793 * typically the canonical URL, but may be a remote
3794 * link if the content comes from another site
3799 public function getSourceURL() {
3800 return $this->getTitle()->getCanonicalURL();
3804 * @param WANObjectCache $cache
3808 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3809 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3811 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );