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\RevisionRenderer
;
27 use MediaWiki\Storage\DerivedPageDataUpdater
;
28 use MediaWiki\Storage\PageUpdater
;
29 use MediaWiki\Storage\RevisionRecord
;
30 use MediaWiki\Storage\RevisionSlotsUpdate
;
31 use MediaWiki\Storage\RevisionStore
;
32 use MediaWiki\Storage\SlotRecord
;
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 $this->mRedirectTarget
= Title
::makeTitle(
991 $row->rd_namespace
, $row->rd_title
,
992 $row->rd_fragment
, $row->rd_interwiki
994 return $this->mRedirectTarget
;
997 // This page doesn't have an entry in the redirect table
998 $this->mRedirectTarget
= $this->insertRedirect();
999 return $this->mRedirectTarget
;
1003 * Insert an entry for this page into the redirect table if the content is a redirect
1005 * The database update will be deferred via DeferredUpdates
1007 * Don't call this function directly unless you know what you're doing.
1008 * @return Title|null Title object or null if not a redirect
1010 public function insertRedirect() {
1011 $content = $this->getContent();
1012 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1017 // Update the DB post-send if the page has not cached since now
1018 $latest = $this->getLatest();
1019 DeferredUpdates
::addCallableUpdate(
1020 function () use ( $retval, $latest ) {
1021 $this->insertRedirectEntry( $retval, $latest );
1023 DeferredUpdates
::POSTSEND
,
1024 wfGetDB( DB_MASTER
)
1031 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1032 * @param Title $rt Redirect target
1033 * @param int|null $oldLatest Prior page_latest for check and set
1035 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1036 $dbw = wfGetDB( DB_MASTER
);
1037 $dbw->startAtomic( __METHOD__
);
1039 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1043 'rd_from' => $this->getId(),
1044 'rd_namespace' => $rt->getNamespace(),
1045 'rd_title' => $rt->getDBkey(),
1046 'rd_fragment' => $rt->getFragment(),
1047 'rd_interwiki' => $rt->getInterwiki(),
1051 'rd_namespace' => $rt->getNamespace(),
1052 'rd_title' => $rt->getDBkey(),
1053 'rd_fragment' => $rt->getFragment(),
1054 'rd_interwiki' => $rt->getInterwiki(),
1060 $dbw->endAtomic( __METHOD__
);
1064 * Get the Title object or URL this page redirects to
1066 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1068 public function followRedirect() {
1069 return $this->getRedirectURL( $this->getRedirectTarget() );
1073 * Get the Title object or URL to use for a redirect. We use Title
1074 * objects for same-wiki, non-special redirects and URLs for everything
1076 * @param Title $rt Redirect target
1077 * @return bool|Title|string False, Title object of local target, or string with URL
1079 public function getRedirectURL( $rt ) {
1084 if ( $rt->isExternal() ) {
1085 if ( $rt->isLocal() ) {
1086 // Offsite wikis need an HTTP redirect.
1087 // This can be hard to reverse and may produce loops,
1088 // so they may be disabled in the site configuration.
1089 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1090 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1092 // External pages without "local" bit set are not valid
1098 if ( $rt->isSpecialPage() ) {
1099 // Gotta handle redirects to special pages differently:
1100 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1101 // Some pages are not valid targets.
1102 if ( $rt->isValidRedirectTarget() ) {
1103 return $rt->getFullURL();
1113 * Get a list of users who have edited this article, not including the user who made
1114 * the most recent revision, which you can get from $article->getUser() if you want it
1115 * @return UserArrayFromResult
1117 public function getContributors() {
1118 // @todo: This is expensive; cache this info somewhere.
1120 $dbr = wfGetDB( DB_REPLICA
);
1122 $actorMigration = ActorMigration
::newMigration();
1123 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1125 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1128 'user_id' => $actorQuery['fields']['rev_user'],
1129 'user_name' => $actorQuery['fields']['rev_user_text'],
1130 'actor_id' => $actorQuery['fields']['rev_actor'],
1131 'user_real_name' => 'MIN(user_real_name)',
1132 'timestamp' => 'MAX(rev_timestamp)',
1135 $conds = [ 'rev_page' => $this->getId() ];
1137 // The user who made the top revision gets credited as "this page was last edited by
1138 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1139 $user = $this->getUser()
1140 ? User
::newFromId( $this->getUser() )
1141 : User
::newFromName( $this->getUserText(), false );
1142 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1145 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1148 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1149 ] +
$actorQuery['joins'];
1152 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1153 'ORDER BY' => 'timestamp DESC',
1156 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1157 return new UserArrayFromResult( $res );
1161 * Should the parser cache be used?
1163 * @param ParserOptions $parserOptions ParserOptions to check
1167 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1168 return $parserOptions->getStubThreshold() == 0
1170 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1171 && $this->getContentHandler()->isParserCacheSupported();
1175 * Get a ParserOutput for the given ParserOptions and revision ID.
1177 * The parser cache will be used if possible. Cache misses that result
1178 * in parser runs are debounced with PoolCounter.
1180 * XXX merge this with updateParserCache()?
1183 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1184 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1185 * get the current revision (default value)
1186 * @param bool $forceParse Force reindexing, regardless of cache settings
1187 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1189 public function getParserOutput(
1190 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1193 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1195 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1196 throw new InvalidArgumentException(
1197 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1201 wfDebug( __METHOD__
.
1202 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1203 if ( $parserOptions->getStubThreshold() ) {
1204 wfIncrStats( 'pcache.miss.stub' );
1207 if ( $useParserCache ) {
1208 $parserOutput = $this->getParserCache()
1209 ->get( $this, $parserOptions );
1210 if ( $parserOutput !== false ) {
1211 return $parserOutput;
1215 if ( $oldid === null ||
$oldid === 0 ) {
1216 $oldid = $this->getLatest();
1219 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1222 return $pool->getParserOutput();
1226 * Do standard deferred updates after page view (existing or missing page)
1227 * @param User $user The relevant user
1228 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1230 public function doViewUpdates( User
$user, $oldid = 0 ) {
1231 if ( wfReadOnly() ) {
1235 // Update newtalk / watchlist notification status;
1236 // Avoid outage if the master is not reachable by using a deferred updated
1237 DeferredUpdates
::addCallableUpdate(
1238 function () use ( $user, $oldid ) {
1239 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1241 $user->clearNotification( $this->mTitle
, $oldid );
1243 DeferredUpdates
::PRESEND
1248 * Perform the actions of a page purging
1250 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1251 * controlled how much purging was done.
1253 public function doPurge() {
1254 // Avoid PHP 7.1 warning of passing $this by reference
1257 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1261 $this->mTitle
->invalidateCache();
1264 HTMLFileCache
::clearFileCache( $this->getTitle() );
1265 // Send purge after above page_touched update was committed
1266 DeferredUpdates
::addUpdate(
1267 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1268 DeferredUpdates
::PRESEND
1271 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1272 $messageCache = MessageCache
::singleton();
1273 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1280 * Insert a new empty page record for this article.
1281 * This *must* be followed up by creating a revision
1282 * and running $this->updateRevisionOn( ... );
1283 * or else the record will be left in a funky state.
1284 * Best if all done inside a transaction.
1286 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1288 * @param IDatabase $dbw
1289 * @param int|null $pageId Custom page ID that will be used for the insert statement
1291 * @return bool|int The newly created page_id key; false if the row was not
1292 * inserted, e.g. because the title already existed or because the specified
1293 * page ID is already in use.
1295 public function insertOn( $dbw, $pageId = null ) {
1296 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1300 'page_namespace' => $this->mTitle
->getNamespace(),
1301 'page_title' => $this->mTitle
->getDBkey(),
1302 'page_restrictions' => '',
1303 'page_is_redirect' => 0, // Will set this shortly...
1305 'page_random' => wfRandom(),
1306 'page_touched' => $dbw->timestamp(),
1307 'page_latest' => 0, // Fill this in shortly...
1308 'page_len' => 0, // Fill this in shortly...
1309 ] +
$pageIdForInsert,
1314 if ( $dbw->affectedRows() > 0 ) {
1315 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1316 $this->mId
= $newid;
1317 $this->mTitle
->resetArticleID( $newid );
1321 return false; // nothing changed
1326 * Update the page record to point to a newly saved revision.
1328 * @todo Factor out into a PageStore service, or move into PageUpdater.
1330 * @param IDatabase $dbw
1331 * @param Revision $revision For ID number, and text used to set
1332 * length and redirect status fields
1333 * @param int|null $lastRevision If given, will not overwrite the page field
1334 * when different from the currently set value.
1335 * Giving 0 indicates the new page flag should be set on.
1336 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1337 * removing rows in redirect table.
1338 * @return bool Success; false if the page row was missing or page_latest changed
1340 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1341 $lastRevIsRedirect = null
1343 global $wgContentHandlerUseDB;
1345 // TODO: move into PageUpdater or PageStore
1346 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1347 // and in the compat stub!
1349 // Assertion to try to catch T92046
1350 if ( (int)$revision->getId() === 0 ) {
1351 throw new InvalidArgumentException(
1352 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1356 $content = $revision->getContent();
1357 $len = $content ?
$content->getSize() : 0;
1358 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1360 $conditions = [ 'page_id' => $this->getId() ];
1362 if ( !is_null( $lastRevision ) ) {
1363 // An extra check against threads stepping on each other
1364 $conditions['page_latest'] = $lastRevision;
1367 $revId = $revision->getId();
1368 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1371 'page_latest' => $revId,
1372 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1373 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1374 'page_is_redirect' => $rt !== null ?
1 : 0,
1378 if ( $wgContentHandlerUseDB ) {
1379 $row['page_content_model'] = $revision->getContentModel();
1382 $dbw->update( 'page',
1387 $result = $dbw->affectedRows() > 0;
1389 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1390 $this->setLastEdit( $revision );
1391 $this->mLatest
= $revision->getId();
1392 $this->mIsRedirect
= (bool)$rt;
1393 // Update the LinkCache.
1394 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1395 $linkCache->addGoodLinkObj(
1401 $revision->getContentModel()
1409 * Add row to the redirect table if this is a redirect, remove otherwise.
1411 * @param IDatabase $dbw
1412 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1413 * or NULL if this is not a redirect
1414 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1415 * removing rows in redirect table.
1416 * @return bool True on success, false on failure
1419 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1420 // Always update redirects (target link might have changed)
1421 // Update/Insert if we don't know if the last revision was a redirect or not
1422 // Delete if changing from redirect to non-redirect
1423 $isRedirect = !is_null( $redirectTitle );
1425 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1429 if ( $isRedirect ) {
1430 $this->insertRedirectEntry( $redirectTitle );
1432 // This is not a redirect, remove row from redirect table
1433 $where = [ 'rd_from' => $this->getId() ];
1434 $dbw->delete( 'redirect', $where, __METHOD__
);
1437 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1438 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1441 return ( $dbw->affectedRows() != 0 );
1445 * If the given revision is newer than the currently set page_latest,
1446 * update the page record. Otherwise, do nothing.
1448 * @deprecated since 1.24, use updateRevisionOn instead
1450 * @param IDatabase $dbw
1451 * @param Revision $revision
1454 public function updateIfNewerOn( $dbw, $revision ) {
1455 $row = $dbw->selectRow(
1456 [ 'revision', 'page' ],
1457 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1459 'page_id' => $this->getId(),
1460 'page_latest=rev_id' ],
1464 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1467 $prev = $row->rev_id
;
1468 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1470 // No or missing previous revision; mark the page as new
1472 $lastRevIsRedirect = null;
1475 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1481 * Helper method for checking whether two revisions have differences that go
1482 * beyond the main slot.
1484 * MCR migration note: this method should go away!
1486 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1488 * @param Revision $a
1489 * @param Revision $b
1492 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1493 $aSlots = $a->getRevisionRecord()->getSlots();
1494 $bSlots = $b->getRevisionRecord()->getSlots();
1495 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1497 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1501 * Get the content that needs to be saved in order to undo all revisions
1502 * between $undo and $undoafter. Revisions must belong to the same page,
1503 * must exist and must not be deleted
1505 * @param Revision $undo
1506 * @param Revision $undoafter Must be an earlier revision than $undo
1507 * @return Content|bool Content on success, false on failure
1509 * Before we had the Content object, this was done in getUndoText
1511 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1512 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1514 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1515 // Cannot yet undo edits that involve anything other the main slot.
1519 $handler = $undo->getContentHandler();
1520 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1524 * Returns true if this page's content model supports sections.
1528 * @todo The skin should check this and not offer section functionality if
1529 * sections are not supported.
1530 * @todo The EditPage should check this and not offer section functionality
1531 * if sections are not supported.
1533 public function supportsSections() {
1534 return $this->getContentHandler()->supportsSections();
1538 * @param string|int|null|bool $sectionId Section identifier as a number or string
1539 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1540 * or 'new' for a new section.
1541 * @param Content $sectionContent New content of the section.
1542 * @param string $sectionTitle New section's subject, only if $section is "new".
1543 * @param string $edittime Revision timestamp or null to use the current revision.
1545 * @throws MWException
1546 * @return Content|null New complete article content, or null if error.
1549 * @deprecated since 1.24, use replaceSectionAtRev instead
1551 public function replaceSectionContent(
1552 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1555 if ( $edittime && $sectionId !== 'new' ) {
1556 $lb = $this->getDBLoadBalancer();
1557 $dbr = $lb->getConnection( DB_REPLICA
);
1558 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1559 // Try the master if this thread may have just added it.
1560 // This could be abstracted into a Revision method, but we don't want
1561 // to encourage loading of revisions by timestamp.
1563 && $lb->getServerCount() > 1
1564 && $lb->hasOrMadeRecentMasterChanges()
1566 $dbw = $lb->getConnection( DB_MASTER
);
1567 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1570 $baseRevId = $rev->getId();
1574 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1578 * @param string|int|null|bool $sectionId Section identifier as a number or string
1579 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1580 * or 'new' for a new section.
1581 * @param Content $sectionContent New content of the section.
1582 * @param string $sectionTitle New section's subject, only if $section is "new".
1583 * @param int|null $baseRevId
1585 * @throws MWException
1586 * @return Content|null New complete article content, or null if error.
1590 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1591 $sectionTitle = '', $baseRevId = null
1593 if ( strval( $sectionId ) === '' ) {
1594 // Whole-page edit; let the whole text through
1595 $newContent = $sectionContent;
1597 if ( !$this->supportsSections() ) {
1598 throw new MWException( "sections not supported for content model " .
1599 $this->getContentHandler()->getModelID() );
1602 // T32711: always use current version when adding a new section
1603 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1604 $oldContent = $this->getContent();
1606 $rev = Revision
::newFromId( $baseRevId );
1608 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1609 $this->getId() . "; section: $sectionId)\n" );
1613 $oldContent = $rev->getContent();
1616 if ( !$oldContent ) {
1617 wfDebug( __METHOD__
. ": no page text\n" );
1621 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1628 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1630 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1631 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1634 * @return int Updated $flags
1636 public function checkFlags( $flags ) {
1637 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1638 if ( $this->exists() ) {
1639 $flags |
= EDIT_UPDATE
;
1649 * @return DerivedPageDataUpdater
1651 private function newDerivedDataUpdater() {
1652 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1654 $derivedDataUpdater = new DerivedPageDataUpdater(
1655 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1656 $this->getRevisionStore(),
1657 $this->getRevisionRenderer(),
1658 $this->getParserCache(),
1659 JobQueueGroup
::singleton(),
1660 MessageCache
::singleton(),
1661 MediaWikiServices
::getInstance()->getContentLanguage(),
1662 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1665 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1666 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1668 return $derivedDataUpdater;
1672 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1673 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1674 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1675 * returned matches that caller's expectations, allowing an existing instance to be re-used
1676 * if the given parameters match that instance's internal state according to
1677 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1678 * match the existign one.
1680 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1681 * created, replacing any DerivedPageDataUpdater currently cached.
1683 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1687 * @param User|null $forUser The user that will be used for, or was used for, PST.
1688 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1689 * to perform updates, if the edit was already saved.
1690 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1691 * if the edit was not yet saved.
1692 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1693 * revision as the edit's parent revision. This ensures that the same
1694 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1696 * @return DerivedPageDataUpdater
1698 private function getDerivedDataUpdater(
1699 User
$forUser = null,
1700 RevisionRecord
$forRevision = null,
1701 RevisionSlotsUpdate
$forUpdate = null,
1704 if ( !$forRevision && !$forUpdate ) {
1705 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1706 // going to use it with.
1707 $this->derivedDataUpdater
= null;
1710 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1711 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1712 // to it did not yet initialize it, because we don't know what data it will be
1713 // initialized with.
1714 $this->derivedDataUpdater
= null;
1717 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1718 // However, there is no good way to construct a cache key. We'd need to check against all
1719 // cached instances.
1721 if ( $this->derivedDataUpdater
1722 && !$this->derivedDataUpdater
->isReusableFor(
1726 $forEdit ?
$this->getLatest() : null
1729 $this->derivedDataUpdater
= null;
1732 if ( !$this->derivedDataUpdater
) {
1733 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1736 return $this->derivedDataUpdater
;
1740 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1742 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1743 * and to protected such conflict resolution from concurrent edits using a check-and-set
1749 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1750 * that may already have been returned via getDerivedDataUpdater to be re-used.
1752 * @return PageUpdater
1754 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1755 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1757 $pageUpdater = new PageUpdater(
1759 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1760 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1761 $this->getDBLoadBalancer(),
1762 $this->getRevisionStore()
1765 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1766 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1767 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1769 return $pageUpdater;
1773 * Change an existing article or create a new article. Updates RC and all necessary caches,
1774 * optionally via the deferred update array.
1776 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1777 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1778 * apply the autopatrol right as appropriate.
1780 * @param Content $content New content
1781 * @param string|CommentStoreComment $summary Edit summary
1782 * @param int $flags Bitfield:
1784 * Article is known or assumed to be non-existent, create a new one
1786 * Article is known or assumed to be pre-existing, update it
1788 * Mark this edit minor, if the user is allowed to do so
1790 * Do not log the change in recentchanges
1792 * Mark the edit a "bot" edit regardless of user rights
1794 * Fill in blank summaries with generated text where possible
1796 * Signal that the page retrieve/save cycle happened entirely in this request.
1798 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1799 * article will be detected. If EDIT_UPDATE is specified and the article
1800 * doesn't exist, the function will return an edit-gone-missing error. If
1801 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1802 * error will be returned. These two conditions are also possible with
1803 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1805 * @param bool|int $originalRevId: The ID of an original revision that the edit
1806 * restores or repeats. The new revision is expected to have the exact same content as
1807 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1808 * which are created to record things like page moves.
1809 * @param User|null $user The user doing the edit
1810 * @param string|null $serialFormat IGNORED.
1811 * @param array|null $tags Change tags to apply to this edit
1812 * Callers are responsible for permission checks
1813 * (with ChangeTags::canAddTagsAccompanyingChange)
1814 * @param Int $undidRevId Id of revision that was undone or 0
1816 * @throws MWException
1817 * @return Status Possible errors:
1818 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1819 * set the fatal flag of $status.
1820 * edit-gone-missing: In update mode, but the article didn't exist.
1821 * edit-conflict: In update mode, the article changed unexpectedly.
1822 * edit-no-change: Warning that the text was the same as before.
1823 * edit-already-exists: In creation mode, but the article already exists.
1825 * Extensions may define additional errors.
1827 * $return->value will contain an associative array with members as follows:
1828 * new: Boolean indicating if the function attempted to create a new article.
1829 * revision: The revision object for the inserted revision, or null.
1832 * @throws MWException
1834 public function doEditContent(
1835 Content
$content, $summary, $flags = 0, $originalRevId = false,
1836 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1838 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1840 if ( !( $summary instanceof CommentStoreComment
) ) {
1841 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1848 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1849 // Checking the minoredit right should be done in the same place the 'bot' right is
1850 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1851 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1852 $flags = ( $flags & ~EDIT_MINOR
);
1855 $slotsUpdate = new RevisionSlotsUpdate();
1856 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1858 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1859 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1860 // used by this PageUpdater. However, there is no guarantee for this.
1861 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1862 $updater->setContent( SlotRecord
::MAIN
, $content );
1863 $updater->setOriginalRevisionId( $originalRevId );
1864 $updater->setUndidRevisionId( $undidRevId );
1866 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1868 // TODO: this logic should not be in the storage layer, it's here for compatibility
1869 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1870 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1871 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1872 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1875 $updater->addTags( $tags );
1877 $revRec = $updater->saveRevision(
1882 // $revRec will be null if the edit failed, or if no new revision was created because
1883 // the content did not change.
1885 // update cached fields
1886 // TODO: this is currently redundant to what is done in updateRevisionOn.
1887 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1888 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1889 $this->mLatest
= $revRec->getId();
1892 return $updater->getStatus();
1896 * Get parser options suitable for rendering the primary article wikitext
1898 * @see ParserOptions::newCanonical
1900 * @param IContextSource|User|string $context One of the following:
1901 * - IContextSource: Use the User and the Language of the provided
1903 * - User: Use the provided User object and $wgLang for the language,
1904 * so use an IContextSource object if possible.
1905 * - 'canonical': Canonical options (anonymous user with default
1906 * preferences and content language).
1907 * @return ParserOptions
1909 public function makeParserOptions( $context ) {
1910 $options = ParserOptions
::newCanonical( $context );
1912 if ( $this->getTitle()->isConversionTable() ) {
1913 // @todo ConversionTable should become a separate content model, so
1914 // we don't need special cases like this one.
1915 $options->disableContentConversion();
1922 * Prepare content which is about to be saved.
1924 * Prior to 1.30, this returned a stdClass.
1926 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1928 * @param Content $content
1929 * @param Revision|RevisionRecord|int|null $revision Revision object.
1930 * For backwards compatibility, a revision ID is also accepted,
1931 * but this is deprecated.
1932 * Used with vary-revision or vary-revision-id.
1933 * @param User|null $user
1934 * @param string|null $serialFormat IGNORED
1935 * @param bool $useCache Check shared prepared edit cache
1937 * @return PreparedEdit
1941 public function prepareContentForEdit(
1945 $serialFormat = null,
1954 if ( !is_object( $revision ) ) {
1956 // This code path is deprecated, and nothing is known to
1957 // use it, so performance here shouldn't be a worry.
1958 if ( $revid !== null ) {
1959 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1960 $store = $this->getRevisionStore();
1961 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1965 } elseif ( $revision instanceof Revision
) {
1966 $revision = $revision->getRevisionRecord();
1969 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
1970 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1972 if ( !$updater->isUpdatePrepared() ) {
1973 $updater->prepareContent( $user, $slots, $useCache );
1976 $updater->prepareUpdate(
1979 'causeAction' => 'prepare-edit',
1980 'causeAgent' => $user->getName(),
1986 return $updater->getPreparedEdit();
1990 * Do standard deferred updates after page edit.
1991 * Update links tables, site stats, search index and message cache.
1992 * Purges pages that include this page if the text was changed here.
1993 * Every 100th edit, prune the recent changes table.
1995 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
1997 * @param Revision $revision
1998 * @param User $user User object that did the revision
1999 * @param array $options Array of options, following indexes are used:
2000 * - changed: bool, whether the revision changed the content (default true)
2001 * - created: bool, whether the revision created the page (default false)
2002 * - moved: bool, whether the page was moved (default false)
2003 * - restored: bool, whether the page was undeleted (default false)
2004 * - oldrevision: Revision object for the pre-update revision (default null)
2005 * - oldcountable: bool, null, or string 'no-change' (default null):
2006 * - bool: whether the page was counted as an article before that
2007 * revision, only used in changed is true and created is false
2008 * - null: if created is false, don't update the article count; if created
2009 * is true, do update the article count
2010 * - 'no-change': don't update the article count, ever
2011 * - causeAction: an arbitrary string identifying the reason for the update.
2012 * See DataUpdate::getCauseAction(). (default 'edit-page')
2013 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2014 * (string, defaults to the passed user)
2016 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2018 'causeAction' => 'edit-page',
2019 'causeAgent' => $user->getName(),
2022 $revision = $revision->getRevisionRecord();
2024 $updater = $this->getDerivedDataUpdater( $user, $revision );
2026 $updater->prepareUpdate( $revision, $options );
2028 $updater->doUpdates();
2032 * Update the parser cache.
2034 * @note This is a temporary workaround until there is a proper data updater class.
2035 * It will become deprecated soon.
2037 * @param array $options
2038 * - causeAction: an arbitrary string identifying the reason for the update.
2039 * See DataUpdate::getCauseAction(). (default 'edit-page')
2040 * - causeAgent: name of the user who caused the update (string, defaults to the
2041 * user who created the revision)
2044 public function updateParserCache( array $options = [] ) {
2045 $revision = $this->getRevisionRecord();
2046 if ( !$revision ||
!$revision->getId() ) {
2047 LoggerFactory
::getInstance( 'wikipage' )->info(
2048 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2052 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2054 $updater = $this->getDerivedDataUpdater( $user, $revision );
2055 $updater->prepareUpdate( $revision, $options );
2056 $updater->doParserCacheUpdate();
2060 * Do secondary data updates (such as updating link tables).
2061 * Secondary data updates are only a small part of the updates needed after saving
2062 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2063 * secondary data updates). This method is provided for partial purges.
2065 * @note This is a temporary workaround until there is a proper data updater class.
2066 * It will become deprecated soon.
2068 * @param array $options
2069 * - recursive (bool, default true): whether to do a recursive update (update pages that
2070 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2071 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2072 * was something that did not really change the page, such as a null edit.
2073 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2074 * user who created the revision)
2075 * - causeAction: an arbitrary string identifying the reason for the update.
2076 * See DataUpdate::getCauseAction(). (default 'unknown')
2077 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2078 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2079 * Note that even when this is set to false, some updates might still get deferred (as
2080 * some update might directly add child updates to DeferredUpdates).
2081 * - transactionTicket: a transaction ticket from LBFactory::getEmptyTransactionTicket(),
2082 * only when defer is false (default: null)
2085 public function doSecondaryDataUpdates( array $options = [] ) {
2086 $options['recursive'] = $options['recursive'] ??
true;
2087 $revision = $this->getRevisionRecord();
2088 if ( !$revision ||
!$revision->getId() ) {
2089 LoggerFactory
::getInstance( 'wikipage' )->info(
2090 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2094 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2096 $updater = $this->getDerivedDataUpdater( $user, $revision );
2097 $updater->prepareUpdate( $revision, $options );
2098 $updater->doSecondaryDataUpdates( $options );
2102 * Update the article's restriction field, and leave a log entry.
2103 * This works for protection both existing and non-existing pages.
2105 * @param array $limit Set of restriction keys
2106 * @param array $expiry Per restriction type expiration
2107 * @param int &$cascade Set to false if cascading protection isn't allowed.
2108 * @param string $reason
2109 * @param User $user The user updating the restrictions
2110 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2111 * ($user should be able to add the specified tags before this is called)
2112 * @return Status Status object; if action is taken, $status->value is the log_id of the
2113 * protection log entry.
2115 public function doUpdateRestrictions( array $limit, array $expiry,
2116 &$cascade, $reason, User
$user, $tags = null
2118 global $wgCascadingRestrictionLevels;
2120 if ( wfReadOnly() ) {
2121 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2124 $this->loadPageData( 'fromdbmaster' );
2125 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2126 $id = $this->getId();
2132 // Take this opportunity to purge out expired restrictions
2133 Title
::purgeExpiredRestrictions();
2135 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2136 // we expect a single selection, but the schema allows otherwise.
2137 $isProtected = false;
2141 $dbw = wfGetDB( DB_MASTER
);
2143 foreach ( $restrictionTypes as $action ) {
2144 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2145 $expiry[$action] = 'infinity';
2147 if ( !isset( $limit[$action] ) ) {
2148 $limit[$action] = '';
2149 } elseif ( $limit[$action] != '' ) {
2153 // Get current restrictions on $action
2154 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2155 if ( $current != '' ) {
2156 $isProtected = true;
2159 if ( $limit[$action] != $current ) {
2161 } elseif ( $limit[$action] != '' ) {
2162 // Only check expiry change if the action is actually being
2163 // protected, since expiry does nothing on an not-protected
2165 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2171 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2175 // If nothing has changed, do nothing
2177 return Status
::newGood();
2180 if ( !$protect ) { // No protection at all means unprotection
2181 $revCommentMsg = 'unprotectedarticle-comment';
2182 $logAction = 'unprotect';
2183 } elseif ( $isProtected ) {
2184 $revCommentMsg = 'modifiedarticleprotection-comment';
2185 $logAction = 'modify';
2187 $revCommentMsg = 'protectedarticle-comment';
2188 $logAction = 'protect';
2191 $logRelationsValues = [];
2192 $logRelationsField = null;
2193 $logParamsDetails = [];
2195 // Null revision (used for change tag insertion)
2196 $nullRevision = null;
2198 if ( $id ) { // Protection of existing page
2199 // Avoid PHP 7.1 warning of passing $this by reference
2202 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2203 return Status
::newGood();
2206 // Only certain restrictions can cascade...
2207 $editrestriction = isset( $limit['edit'] )
2208 ?
[ $limit['edit'] ]
2209 : $this->mTitle
->getRestrictions( 'edit' );
2210 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2211 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2213 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2214 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2217 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2218 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2219 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2221 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2222 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2225 // The schema allows multiple restrictions
2226 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2230 // insert null revision to identify the page protection change as edit summary
2231 $latest = $this->getLatest();
2232 $nullRevision = $this->insertProtectNullRevision(
2241 if ( $nullRevision === null ) {
2242 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2245 $logRelationsField = 'pr_id';
2247 // Update restrictions table
2248 foreach ( $limit as $action => $restrictions ) {
2250 'page_restrictions',
2253 'pr_type' => $action
2257 if ( $restrictions != '' ) {
2258 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2260 'page_restrictions',
2263 'pr_type' => $action,
2264 'pr_level' => $restrictions,
2265 'pr_cascade' => $cascadeValue,
2266 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2270 $logRelationsValues[] = $dbw->insertId();
2271 $logParamsDetails[] = [
2273 'level' => $restrictions,
2274 'expiry' => $expiry[$action],
2275 'cascade' => (bool)$cascadeValue,
2280 // Clear out legacy restriction fields
2283 [ 'page_restrictions' => '' ],
2284 [ 'page_id' => $id ],
2288 // Avoid PHP 7.1 warning of passing $this by reference
2291 Hooks
::run( 'NewRevisionFromEditComplete',
2292 [ $this, $nullRevision, $latest, $user ] );
2293 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2294 } else { // Protection of non-existing page (also known as "title protection")
2295 // Cascade protection is meaningless in this case
2298 if ( $limit['create'] != '' ) {
2299 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2300 $dbw->replace( 'protected_titles',
2301 [ [ 'pt_namespace', 'pt_title' ] ],
2303 'pt_namespace' => $this->mTitle
->getNamespace(),
2304 'pt_title' => $this->mTitle
->getDBkey(),
2305 'pt_create_perm' => $limit['create'],
2306 'pt_timestamp' => $dbw->timestamp(),
2307 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2308 'pt_user' => $user->getId(),
2309 ] +
$commentFields, __METHOD__
2311 $logParamsDetails[] = [
2313 'level' => $limit['create'],
2314 'expiry' => $expiry['create'],
2317 $dbw->delete( 'protected_titles',
2319 'pt_namespace' => $this->mTitle
->getNamespace(),
2320 'pt_title' => $this->mTitle
->getDBkey()
2326 $this->mTitle
->flushRestrictions();
2327 InfoAction
::invalidateCache( $this->mTitle
);
2329 if ( $logAction == 'unprotect' ) {
2332 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2334 '4::description' => $protectDescriptionLog, // parameter for IRC
2335 '5:bool:cascade' => $cascade,
2336 'details' => $logParamsDetails, // parameter for localize and api
2340 // Update the protection log
2341 $logEntry = new ManualLogEntry( 'protect', $logAction );
2342 $logEntry->setTarget( $this->mTitle
);
2343 $logEntry->setComment( $reason );
2344 $logEntry->setPerformer( $user );
2345 $logEntry->setParameters( $params );
2346 if ( !is_null( $nullRevision ) ) {
2347 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2349 $logEntry->setTags( $tags );
2350 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2351 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2353 $logId = $logEntry->insert();
2354 $logEntry->publish( $logId );
2356 return Status
::newGood( $logId );
2360 * Insert a new null revision for this page.
2362 * @param string $revCommentMsg Comment message key for the revision
2363 * @param array $limit Set of restriction keys
2364 * @param array $expiry Per restriction type expiration
2365 * @param int $cascade Set to false if cascading protection isn't allowed.
2366 * @param string $reason
2367 * @param User|null $user
2368 * @return Revision|null Null on error
2370 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2371 array $expiry, $cascade, $reason, $user = null
2373 $dbw = wfGetDB( DB_MASTER
);
2375 // Prepare a null revision to be added to the history
2376 $editComment = wfMessage(
2378 $this->mTitle
->getPrefixedText(),
2379 $user ?
$user->getName() : ''
2380 )->inContentLanguage()->text();
2382 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2384 $protectDescription = $this->protectDescription( $limit, $expiry );
2385 if ( $protectDescription ) {
2386 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2387 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2388 ->inContentLanguage()->text();
2391 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2392 $editComment .= wfMessage( 'brackets' )->params(
2393 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2394 )->inContentLanguage()->text();
2397 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2399 $nullRev->insertOn( $dbw );
2401 // Update page record and touch page
2402 $oldLatest = $nullRev->getParentId();
2403 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2410 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2413 protected function formatExpiry( $expiry ) {
2414 if ( $expiry != 'infinity' ) {
2415 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2418 $contLang->timeanddate( $expiry, false, false ),
2419 $contLang->date( $expiry, false, false ),
2420 $contLang->time( $expiry, false, false )
2421 )->inContentLanguage()->text();
2423 return wfMessage( 'protect-expiry-indefinite' )
2424 ->inContentLanguage()->text();
2429 * Builds the description to serve as comment for the edit.
2431 * @param array $limit Set of restriction keys
2432 * @param array $expiry Per restriction type expiration
2435 public function protectDescription( array $limit, array $expiry ) {
2436 $protectDescription = '';
2438 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2439 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2440 # All possible message keys are listed here for easier grepping:
2441 # * restriction-create
2442 # * restriction-edit
2443 # * restriction-move
2444 # * restriction-upload
2445 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2446 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2447 # with '' filtered out. All possible message keys are listed below:
2448 # * protect-level-autoconfirmed
2449 # * protect-level-sysop
2450 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2451 ->inContentLanguage()->text();
2453 $expiryText = $this->formatExpiry( $expiry[$action] );
2455 if ( $protectDescription !== '' ) {
2456 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2458 $protectDescription .= wfMessage( 'protect-summary-desc' )
2459 ->params( $actionText, $restrictionsText, $expiryText )
2460 ->inContentLanguage()->text();
2463 return $protectDescription;
2467 * Builds the description to serve as comment for the log entry.
2469 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2470 * protect description text. Keep them in old format to avoid breaking compatibility.
2471 * TODO: Fix protection log to store structured description and format it on-the-fly.
2473 * @param array $limit Set of restriction keys
2474 * @param array $expiry Per restriction type expiration
2477 public function protectDescriptionLog( array $limit, array $expiry ) {
2478 $protectDescriptionLog = '';
2480 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2481 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2482 $expiryText = $this->formatExpiry( $expiry[$action] );
2483 $protectDescriptionLog .=
2485 "[$action=$restrictions] ($expiryText)";
2488 return trim( $protectDescriptionLog );
2492 * Take an array of page restrictions and flatten it to a string
2493 * suitable for insertion into the page_restrictions field.
2495 * @param string[] $limit
2497 * @throws MWException
2500 protected static function flattenRestrictions( $limit ) {
2501 if ( !is_array( $limit ) ) {
2502 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2508 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2509 $bits[] = "$action=$restrictions";
2512 return implode( ':', $bits );
2516 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2517 * backwards compatibility, if you care about error reporting you should use
2518 * doDeleteArticleReal() instead.
2520 * Deletes the article with database consistency, writes logs, purges caches
2522 * @param string $reason Delete reason for deletion log
2523 * @param bool $suppress Suppress all revisions and log the deletion in
2524 * the suppression log instead of the deletion log
2525 * @param int|null $u1 Unused
2526 * @param bool|null $u2 Unused
2527 * @param array|string &$error Array of errors to append to
2528 * @param User|null $user The deleting user
2529 * @return bool True if successful
2531 public function doDeleteArticle(
2532 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2534 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2535 return $status->isGood();
2539 * Back-end article deletion
2540 * Deletes the article with database consistency, writes logs, purges caches
2544 * @param string $reason Delete reason for deletion log
2545 * @param bool $suppress Suppress all revisions and log the deletion in
2546 * the suppression log instead of the deletion log
2547 * @param int|null $u1 Unused
2548 * @param bool|null $u2 Unused
2549 * @param array|string &$error Array of errors to append to
2550 * @param User|null $deleter The deleting user
2551 * @param array $tags Tags to apply to the deletion action
2552 * @param string $logsubtype
2553 * @return Status Status object; if successful, $status->value is the log_id of the
2554 * deletion log entry. If the page couldn't be deleted because it wasn't
2555 * found, $status is a non-fatal 'cannotdelete' error
2557 public function doDeleteArticleReal(
2558 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2559 $tags = [], $logsubtype = 'delete'
2561 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage,
2562 $wgActorTableSchemaMigrationStage, $wgMultiContentRevisionSchemaMigrationStage;
2564 wfDebug( __METHOD__
. "\n" );
2566 $status = Status
::newGood();
2568 if ( $this->mTitle
->getDBkey() === '' ) {
2569 $status->error( 'cannotdelete',
2570 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2574 // Avoid PHP 7.1 warning of passing $this by reference
2577 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2578 if ( !Hooks
::run( 'ArticleDelete',
2579 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2581 if ( $status->isOK() ) {
2582 // Hook aborted but didn't set a fatal status
2583 $status->fatal( 'delete-hook-aborted' );
2588 $dbw = wfGetDB( DB_MASTER
);
2589 $dbw->startAtomic( __METHOD__
);
2591 $this->loadPageData( self
::READ_LATEST
);
2592 $id = $this->getId();
2593 // T98706: lock the page from various other updates but avoid using
2594 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2595 // the revisions queries (which also JOIN on user). Only lock the page
2596 // row and CAS check on page_latest to see if the trx snapshot matches.
2597 $lockedLatest = $this->lockAndGetLatest();
2598 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2599 $dbw->endAtomic( __METHOD__
);
2600 // Page not there or trx snapshot is stale
2601 $status->error( 'cannotdelete',
2602 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2606 // Given the lock above, we can be confident in the title and page ID values
2607 $namespace = $this->getTitle()->getNamespace();
2608 $dbKey = $this->getTitle()->getDBkey();
2610 // At this point we are now comitted to returning an OK
2611 // status unless some DB query error or other exception comes up.
2612 // This way callers don't have to call rollback() if $status is bad
2613 // unless they actually try to catch exceptions (which is rare).
2615 // we need to remember the old content so we can use it to generate all deletion updates.
2616 $revision = $this->getRevision();
2618 $content = $this->getContent( Revision
::RAW
);
2619 } catch ( Exception
$ex ) {
2620 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2621 . $ex->getMessage() );
2626 $commentStore = CommentStore
::getStore();
2627 $actorMigration = ActorMigration
::newMigration();
2629 $revQuery = Revision
::getQueryInfo();
2632 // Bitfields to further suppress the content
2634 $bitfield = Revision
::SUPPRESSED_ALL
;
2635 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2638 // For now, shunt the revision data into the archive table.
2639 // Text is *not* removed from the text table; bulk storage
2640 // is left intact to avoid breaking block-compression or
2641 // immutable storage schemes.
2642 // In the future, we may keep revisions and mark them with
2643 // the rev_deleted field, which is reserved for this purpose.
2645 // Lock rows in `revision` and its temp tables, but not any others.
2646 // Note array_intersect() preserves keys from the first arg, and we're
2647 // assuming $revQuery has `revision` primary and isn't using subtables
2648 // for anything we care about.
2649 $dbw->lockForUpdate(
2651 $revQuery['tables'],
2652 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2654 [ 'rev_page' => $id ],
2660 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2661 // so we can copy it to the archive table.
2662 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2663 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2664 $revQuery['fields'][] = 'rev_text_id';
2666 if ( $wgContentHandlerUseDB ) {
2667 $revQuery['fields'][] = 'rev_content_model';
2668 $revQuery['fields'][] = 'rev_content_format';
2672 // Get all of the page revisions
2673 $res = $dbw->select(
2674 $revQuery['tables'],
2675 $revQuery['fields'],
2676 [ 'rev_page' => $id ],
2682 // Build their equivalent archive rows
2686 /** @var int[] Revision IDs of edits that were made by IPs */
2689 foreach ( $res as $row ) {
2690 $comment = $commentStore->getComment( 'rev_comment', $row );
2691 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2693 'ar_namespace' => $namespace,
2694 'ar_title' => $dbKey,
2695 'ar_timestamp' => $row->rev_timestamp
,
2696 'ar_minor_edit' => $row->rev_minor_edit
,
2697 'ar_rev_id' => $row->rev_id
,
2698 'ar_parent_id' => $row->rev_parent_id
,
2700 * ar_text_id should probably not be written to when the multi content schema has
2701 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2702 * default for the field in WMF production currently so we must keep writing
2703 * writing until a default of 0 is set.
2704 * Task: https://phabricator.wikimedia.org/T190148
2705 * Copying the value from the revision table should not lead to any issues for now.
2707 'ar_len' => $row->rev_len
,
2708 'ar_page_id' => $id,
2709 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2710 'ar_sha1' => $row->rev_sha1
,
2711 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2712 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2714 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2715 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2717 if ( $wgContentHandlerUseDB ) {
2718 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2719 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2723 $rowsInsert[] = $rowInsert;
2724 $revids[] = $row->rev_id
;
2726 // Keep track of IP edits, so that the corresponding rows can
2727 // be deleted in the ip_changes table.
2728 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2729 $ipRevIds[] = $row->rev_id
;
2732 // Copy them into the archive table
2733 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2734 // Save this so we can pass it to the ArticleDeleteComplete hook.
2735 $archivedRevisionCount = $dbw->affectedRows();
2737 // Clone the title and wikiPage, so we have the information we need when
2738 // we log and run the ArticleDeleteComplete hook.
2739 $logTitle = clone $this->mTitle
;
2740 $wikiPageBeforeDelete = clone $this;
2742 // Now that it's safely backed up, delete it
2743 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2744 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2745 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2746 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2748 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
2749 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2752 // Also delete records from ip_changes as applicable.
2753 if ( count( $ipRevIds ) > 0 ) {
2754 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2757 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2758 $logtype = $suppress ?
'suppress' : 'delete';
2760 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2761 $logEntry->setPerformer( $deleter );
2762 $logEntry->setTarget( $logTitle );
2763 $logEntry->setComment( $reason );
2764 $logEntry->setTags( $tags );
2765 $logid = $logEntry->insert();
2767 $dbw->onTransactionPreCommitOrIdle(
2768 function () use ( $logEntry, $logid ) {
2769 // T58776: avoid deadlocks (especially from FileDeleteForm)
2770 $logEntry->publish( $logid );
2775 $dbw->endAtomic( __METHOD__
);
2777 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2779 Hooks
::run( 'ArticleDeleteComplete', [
2780 &$wikiPageBeforeDelete,
2786 $archivedRevisionCount
2788 $status->value
= $logid;
2790 // Show log excerpt on 404 pages rather than just a link
2791 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2792 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2793 $cache->set( $key, 1, $cache::TTL_DAY
);
2799 * Lock the page row for this title+id and return page_latest (or 0)
2801 * @return int Returns 0 if no row was found with this title+id
2804 public function lockAndGetLatest() {
2805 return (int)wfGetDB( DB_MASTER
)->selectField(
2809 'page_id' => $this->getId(),
2810 // Typically page_id is enough, but some code might try to do
2811 // updates assuming the title is the same, so verify that
2812 'page_namespace' => $this->getTitle()->getNamespace(),
2813 'page_title' => $this->getTitle()->getDBkey()
2821 * Do some database updates after deletion
2823 * @param int $id The page_id value of the page being deleted
2824 * @param Content|null $content Page content to be used when determining
2825 * the required updates. This may be needed because $this->getContent()
2826 * may already return null when the page proper was deleted.
2827 * @param RevisionRecord|Revision|null $revision The current page revision at the time of
2828 * deletion, used when determining the required updates. This may be needed because
2829 * $this->getRevision() may already return null when the page proper was deleted.
2830 * @param User|null $user The user that caused the deletion
2832 public function doDeleteUpdates(
2833 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2835 if ( $id !== $this->getId() ) {
2836 throw new InvalidArgumentException( 'Mismatching page ID' );
2840 $countable = $this->isCountable();
2841 } catch ( Exception
$ex ) {
2842 // fallback for deleting broken pages for which we cannot load the content for
2843 // some reason. Note that doDeleteArticleReal() already logged this problem.
2847 // Update site status
2848 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2849 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2852 // Delete pagelinks, update secondary indexes, etc
2853 $updates = $this->getDeletionUpdates(
2854 $revision ?
$revision->getRevisionRecord() : $content
2856 foreach ( $updates as $update ) {
2857 DeferredUpdates
::addUpdate( $update );
2860 $causeAgent = $user ?
$user->getName() : 'unknown';
2861 // Reparse any pages transcluding this page
2862 LinksUpdate
::queueRecursiveJobsForTable(
2863 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
2864 // Reparse any pages including this image
2865 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2866 LinksUpdate
::queueRecursiveJobsForTable(
2867 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
2871 self
::onArticleDelete( $this->mTitle
);
2872 ResourceLoaderWikiModule
::invalidateModuleCache(
2873 $this->mTitle
, $revision, null, wfWikiID()
2876 // Reset this object and the Title object
2877 $this->loadFromRow( false, self
::READ_LATEST
);
2880 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2884 * Roll back the most recent consecutive set of edits to a page
2885 * from the same user; fails if there are no eligible edits to
2886 * roll back to, e.g. user is the sole contributor. This function
2887 * performs permissions checks on $user, then calls commitRollback()
2888 * to do the dirty work
2890 * @todo Separate the business/permission stuff out from backend code
2891 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2893 * @param string $fromP Name of the user whose edits to rollback.
2894 * @param string $summary Custom summary. Set to default summary if empty.
2895 * @param string $token Rollback token.
2896 * @param bool $bot If true, mark all reverted edits as bot.
2898 * @param array &$resultDetails Array contains result-specific array of additional values
2899 * 'alreadyrolled' : 'current' (rev)
2900 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2902 * @param User $user The user performing the rollback
2903 * @param array|null $tags Change tags to apply to the rollback
2904 * Callers are responsible for permission checks
2905 * (with ChangeTags::canAddTagsAccompanyingChange)
2907 * @return array Array of errors, each error formatted as
2908 * array(messagekey, param1, param2, ...).
2909 * On success, the array is empty. This array can also be passed to
2910 * OutputPage::showPermissionsErrorPage().
2912 public function doRollback(
2913 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
2915 $resultDetails = null;
2917 // Check permissions
2918 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2919 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2920 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2922 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
2923 $errors[] = [ 'sessionfailure' ];
2926 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2927 $errors[] = [ 'actionthrottledtext' ];
2930 // If there were errors, bail out now
2931 if ( !empty( $errors ) ) {
2935 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
2939 * Backend implementation of doRollback(), please refer there for parameter
2940 * and return value documentation
2942 * NOTE: This function does NOT check ANY permissions, it just commits the
2943 * rollback to the DB. Therefore, you should only call this function direct-
2944 * ly if you want to use custom permissions checks. If you don't, use
2945 * doRollback() instead.
2946 * @param string $fromP Name of the user whose edits to rollback.
2947 * @param string $summary Custom summary. Set to default summary if empty.
2948 * @param bool $bot If true, mark all reverted edits as bot.
2950 * @param array &$resultDetails Contains result-specific array of additional values
2951 * @param User $guser The user performing the rollback
2952 * @param array|null $tags Change tags to apply to the rollback
2953 * Callers are responsible for permission checks
2954 * (with ChangeTags::canAddTagsAccompanyingChange)
2956 * @return array An array of error messages, as returned by Status::getErrorsArray()
2958 public function commitRollback( $fromP, $summary, $bot,
2959 &$resultDetails, User
$guser, $tags = null
2961 global $wgUseRCPatrol;
2963 $dbw = wfGetDB( DB_MASTER
);
2965 if ( wfReadOnly() ) {
2966 return [ [ 'readonlytext' ] ];
2969 // Begin revision creation cycle by creating a PageUpdater.
2970 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
2971 $updater = $this->newPageUpdater( $guser );
2972 $current = $updater->grabParentRevision();
2974 if ( is_null( $current ) ) {
2975 // Something wrong... no page?
2976 return [ [ 'notanarticle' ] ];
2979 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
2980 $legacyCurrent = new Revision( $current );
2981 $from = str_replace( '_', ' ', $fromP );
2983 // User name given should match up with the top revision.
2984 // If the revision's user is not visible, then $from should be empty.
2985 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
2986 $resultDetails = [ 'current' => $legacyCurrent ];
2987 return [ [ 'alreadyrolled',
2988 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2989 htmlspecialchars( $fromP ),
2990 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
2994 // Get the last edit not by this person...
2995 // Note: these may not be public values
2996 $actorWhere = ActorMigration
::newMigration()->getWhere(
2999 $current->getUser( RevisionRecord
::RAW
)
3002 $s = $dbw->selectRow(
3003 [ 'revision' ] +
$actorWhere['tables'],
3004 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3006 'rev_page' => $current->getPageId(),
3007 'NOT(' . $actorWhere['conds'] . ')',
3011 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3012 'ORDER BY' => 'rev_timestamp DESC'
3014 $actorWhere['joins']
3016 if ( $s === false ) {
3017 // No one else ever edited this page
3018 return [ [ 'cantrollback' ] ];
3019 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3020 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3022 // Only admins can see this text
3023 return [ [ 'notvisiblerev' ] ];
3026 // Generate the edit summary if necessary
3027 $target = $this->getRevisionStore()->getRevisionById(
3029 RevisionStore
::READ_LATEST
3031 if ( empty( $summary ) ) {
3032 if ( !$currentEditorForPublic ) { // no public user name
3033 $summary = wfMessage( 'revertpage-nouser' );
3035 $summary = wfMessage( 'revertpage' );
3038 $legacyTarget = new Revision( $target );
3039 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3041 // Allow the custom summary to use the same args as the default message
3042 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3044 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3045 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3047 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3049 $contLang->timeanddate( $current->getTimestamp() )
3051 if ( $summary instanceof Message
) {
3052 $summary = $summary->params( $args )->inContentLanguage()->text();
3054 $summary = wfMsgReplaceArgs( $summary, $args );
3057 // Trim spaces on user supplied text
3058 $summary = trim( $summary );
3061 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3063 if ( $guser->isAllowed( 'minoredit' ) ) {
3064 $flags |
= EDIT_MINOR
;
3067 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3068 $flags |
= EDIT_FORCE_BOT
;
3071 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3072 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3073 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3074 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3076 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3077 $tags[] = 'mw-rollback';
3080 // Build rollback revision:
3081 // Restore old content
3082 // TODO: MCR: test this once we can store multiple slots
3083 foreach ( $target->getSlots()->getSlots() as $slot ) {
3084 $updater->inheritSlot( $slot );
3087 // Remove extra slots
3088 // TODO: MCR: test this once we can store multiple slots
3089 foreach ( $current->getSlotRoles() as $role ) {
3090 if ( !$target->hasSlot( $role ) ) {
3091 $updater->removeSlot( $role );
3095 $updater->setOriginalRevisionId( $target->getId() );
3096 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3097 $updater->addTags( $tags );
3099 // TODO: this logic should not be in the storage layer, it's here for compatibility
3100 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3101 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3102 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
3103 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3106 // Actually store the rollback
3107 $rev = $updater->saveRevision(
3108 CommentStoreComment
::newUnsavedComment( $summary ),
3112 // Set patrolling and bot flag on the edits, which gets rollbacked.
3113 // This is done even on edit failure to have patrolling in that case (T64157).
3115 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3116 // Mark all reverted edits as bot
3120 if ( $wgUseRCPatrol ) {
3121 // Mark all reverted edits as patrolled
3122 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3125 if ( count( $set ) ) {
3126 $actorWhere = ActorMigration
::newMigration()->getWhere(
3129 $current->getUser( RevisionRecord
::RAW
),
3132 $dbw->update( 'recentchanges', $set,
3134 'rc_cur_id' => $current->getPageId(),
3135 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3136 $actorWhere['conds'], // No tables/joins are needed for rc_user
3142 if ( !$updater->wasSuccessful() ) {
3143 return $updater->getStatus()->getErrorsArray();
3146 // Report if the edit was not created because it did not change the content.
3147 if ( $updater->isUnchanged() ) {
3148 $resultDetails = [ 'current' => $legacyCurrent ];
3149 return [ [ 'alreadyrolled',
3150 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3151 htmlspecialchars( $fromP ),
3152 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3156 if ( $changingContentModel ) {
3157 // If the content model changed during the rollback,
3158 // make sure it gets logged to Special:Log/contentmodel
3159 $log = new ManualLogEntry( 'contentmodel', 'change' );
3160 $log->setPerformer( $guser );
3161 $log->setTarget( $this->mTitle
);
3162 $log->setComment( $summary );
3163 $log->setParameters( [
3164 '4::oldmodel' => $currentContent->getModel(),
3165 '5::newmodel' => $targetContent->getModel(),
3168 $logId = $log->insert( $dbw );
3169 $log->publish( $logId );
3172 $revId = $rev->getId();
3174 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3177 'summary' => $summary,
3178 'current' => $legacyCurrent,
3179 'target' => $legacyTarget,
3184 // TODO: make this return a Status object and wrap $resultDetails in that.
3189 * The onArticle*() functions are supposed to be a kind of hooks
3190 * which should be called whenever any of the specified actions
3193 * This is a good place to put code to clear caches, for instance.
3195 * This is called on page move and undelete, as well as edit
3197 * @param Title $title
3199 public static function onArticleCreate( Title
$title ) {
3200 // TODO: move this into a PageEventEmitter service
3202 // Update existence markers on article/talk tabs...
3203 $other = $title->getOtherPage();
3205 $other->purgeSquid();
3207 $title->touchLinks();
3208 $title->purgeSquid();
3209 $title->deleteTitleProtection();
3211 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3213 // Invalidate caches of articles which include this page
3214 DeferredUpdates
::addUpdate(
3215 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3218 if ( $title->getNamespace() == NS_CATEGORY
) {
3219 // Load the Category object, which will schedule a job to create
3220 // the category table row if necessary. Checking a replica DB is ok
3221 // here, in the worst case it'll run an unnecessary recount job on
3222 // a category that probably doesn't have many members.
3223 Category
::newFromTitle( $title )->getID();
3228 * Clears caches when article is deleted
3230 * @param Title $title
3232 public static function onArticleDelete( Title
$title ) {
3233 // TODO: move this into a PageEventEmitter service
3235 // Update existence markers on article/talk tabs...
3236 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3237 BacklinkCache
::get( $title )->clear();
3238 $other = $title->getOtherPage();
3240 $other->purgeSquid();
3242 $title->touchLinks();
3243 $title->purgeSquid();
3245 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3248 HTMLFileCache
::clearFileCache( $title );
3249 InfoAction
::invalidateCache( $title );
3252 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3253 MessageCache
::singleton()->updateMessageOverride( $title, null );
3257 if ( $title->getNamespace() == NS_FILE
) {
3258 DeferredUpdates
::addUpdate(
3259 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3264 if ( $title->getNamespace() == NS_USER_TALK
) {
3265 $user = User
::newFromName( $title->getText(), false );
3267 $user->setNewtalk( false );
3272 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3274 // Purge cross-wiki cache entities referencing this page
3275 self
::purgeInterwikiCheckKey( $title );
3279 * Purge caches on page update etc
3281 * @param Title $title
3282 * @param Revision|null $revision Revision that was just saved, may be null
3283 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3284 * If not given, all slots are assumed to have changed.
3286 public static function onArticleEdit(
3288 Revision
$revision = null,
3289 $slotsChanged = null
3291 // TODO: move this into a PageEventEmitter service
3293 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3294 // Invalidate caches of articles which include this page.
3295 // Only for the main slot, because only the main slot is transcluded.
3296 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3297 DeferredUpdates
::addUpdate(
3298 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3302 // Invalidate the caches of all pages which redirect here
3303 DeferredUpdates
::addUpdate(
3304 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3307 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3309 // Purge CDN for this page only
3310 $title->purgeSquid();
3311 // Clear file cache for this page only
3312 HTMLFileCache
::clearFileCache( $title );
3314 // Purge ?action=info cache
3315 $revid = $revision ?
$revision->getId() : null;
3316 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3317 InfoAction
::invalidateCache( $title, $revid );
3320 // Purge cross-wiki cache entities referencing this page
3321 self
::purgeInterwikiCheckKey( $title );
3327 * Purge the check key for cross-wiki cache entries referencing this page
3329 * @param Title $title
3331 private static function purgeInterwikiCheckKey( Title
$title ) {
3332 global $wgEnableScaryTranscluding;
3334 if ( !$wgEnableScaryTranscluding ) {
3335 return; // @todo: perhaps this wiki is only used as a *source* for content?
3338 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3339 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3340 $cache->resetCheckKey(
3341 // Do not include the namespace since there can be multiple aliases to it
3342 // due to different namespace text definitions on different wikis. This only
3343 // means that some cache invalidations happen that are not strictly needed.
3344 $cache->makeGlobalKey( 'interwiki-page', wfWikiID(), $title->getDBkey() )
3350 * Returns a list of categories this page is a member of.
3351 * Results will include hidden categories
3353 * @return TitleArray
3355 public function getCategories() {
3356 $id = $this->getId();
3358 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3361 $dbr = wfGetDB( DB_REPLICA
);
3362 $res = $dbr->select( 'categorylinks',
3363 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3364 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3365 // as not being aliases, and NS_CATEGORY is numeric
3366 [ 'cl_from' => $id ],
3369 return TitleArray
::newFromResult( $res );
3373 * Returns a list of hidden categories this page is a member of.
3374 * Uses the page_props and categorylinks tables.
3376 * @return array Array of Title objects
3378 public function getHiddenCategories() {
3380 $id = $this->getId();
3386 $dbr = wfGetDB( DB_REPLICA
);
3387 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3389 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3390 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3393 if ( $res !== false ) {
3394 foreach ( $res as $row ) {
3395 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3403 * Auto-generates a deletion reason
3405 * @param bool &$hasHistory Whether the page has a history
3406 * @return string|bool String containing deletion reason or empty string, or boolean false
3407 * if no revision occurred
3409 public function getAutoDeleteReason( &$hasHistory ) {
3410 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3414 * Update all the appropriate counts in the category table, given that
3415 * we've added the categories $added and deleted the categories $deleted.
3417 * This should only be called from deferred updates or jobs to avoid contention.
3419 * @param array $added The names of categories that were added
3420 * @param array $deleted The names of categories that were deleted
3421 * @param int $id Page ID (this should be the original deleted page ID)
3423 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3424 $id = $id ?
: $this->getId();
3425 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3427 $addFields = [ 'cat_pages = cat_pages + 1' ];
3428 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3429 if ( $type !== 'page' ) {
3430 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3431 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3434 $dbw = wfGetDB( DB_MASTER
);
3436 if ( count( $added ) ) {
3437 $existingAdded = $dbw->selectFieldValues(
3440 [ 'cat_title' => $added ],
3444 // For category rows that already exist, do a plain
3445 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3446 // to avoid creating gaps in the cat_id sequence.
3447 if ( count( $existingAdded ) ) {
3451 [ 'cat_title' => $existingAdded ],
3456 $missingAdded = array_diff( $added, $existingAdded );
3457 if ( count( $missingAdded ) ) {
3459 foreach ( $missingAdded as $cat ) {
3461 'cat_title' => $cat,
3463 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3464 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3477 if ( count( $deleted ) ) {
3481 [ 'cat_title' => $deleted ],
3486 foreach ( $added as $catName ) {
3487 $cat = Category
::newFromName( $catName );
3488 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3491 foreach ( $deleted as $catName ) {
3492 $cat = Category
::newFromName( $catName );
3493 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3494 // Refresh counts on categories that should be empty now (after commit, T166757)
3495 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3496 $cat->refreshCountsIfEmpty();
3502 * Opportunistically enqueue link update jobs given fresh parser output if useful
3504 * @param ParserOutput $parserOutput Current version page output
3507 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3508 if ( wfReadOnly() ) {
3512 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3513 [ $this, $this->mTitle
, $parserOutput ]
3518 $config = RequestContext
::getMain()->getConfig();
3521 'isOpportunistic' => true,
3522 'rootJobTimestamp' => $parserOutput->getCacheTime()
3525 if ( $this->mTitle
->areRestrictionsCascading() ) {
3526 // If the page is cascade protecting, the links should really be up-to-date
3527 JobQueueGroup
::singleton()->lazyPush(
3528 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3530 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3531 // Assume the output contains "dynamic" time/random based magic words.
3532 // Only update pages that expired due to dynamic content and NOT due to edits
3533 // to referenced templates/files. When the cache expires due to dynamic content,
3534 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3535 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3536 // template/file edit already triggered recursive RefreshLinksJob jobs.
3537 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3538 // If a page is uncacheable, do not keep spamming a job for it.
3539 // Although it would be de-duplicated, it would still waste I/O.
3540 $cache = ObjectCache
::getLocalClusterInstance();
3541 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3542 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3543 if ( $cache->add( $key, time(), $ttl ) ) {
3544 JobQueueGroup
::singleton()->lazyPush(
3545 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3553 * Returns a list of updates to be performed when this page is deleted. The
3554 * updates should remove any information about this page from secondary data
3555 * stores such as links tables.
3557 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3558 * object for backwards compatibility.
3559 * @return DeferrableUpdate[]
3561 public function getDeletionUpdates( $rev = null ) {
3563 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3566 $rev = $this->getRevisionRecord();
3567 } catch ( Exception
$ex ) {
3568 // If we can't load the content, something is wrong. Perhaps that's why
3569 // the user is trying to delete the page, so let's not fail in that case.
3570 // Note that doDeleteArticleReal() will already have logged an issue with
3571 // loading the content.
3572 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3578 } elseif ( $rev instanceof Content
) {
3579 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3581 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3583 $slotContent = array_map( function ( SlotRecord
$slot ) {
3584 return $slot->getContent( Revision
::RAW
);
3585 }, $rev->getSlots()->getSlots() );
3588 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3590 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3591 // model here, not the content object!
3592 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3593 /** @var Content $content */
3594 foreach ( $slotContent as $role => $content ) {
3595 $handler = $content->getContentHandler();
3597 $updates = $handler->getDeletionUpdates(
3601 $allUpdates = array_merge( $allUpdates, $updates );
3603 // TODO: remove B/C hack in 1.32!
3604 $legacyUpdates = $content->getDeletionUpdates( $this );
3606 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3607 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3608 return !( $update instanceof LinksDeletionUpdate
);
3611 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3614 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3616 // TODO: hard deprecate old hook in 1.33
3617 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3622 * Whether this content displayed on this page
3623 * comes from the local database
3628 public function isLocal() {
3633 * The display name for the site this content
3634 * come from. If a subclass overrides isLocal(),
3635 * this could return something other than the
3641 public function getWikiDisplayName() {
3647 * Get the source URL for the content on this page,
3648 * typically the canonical URL, but may be a remote
3649 * link if the content comes from another site
3654 public function getSourceURL() {
3655 return $this->getTitle()->getCanonicalURL();
3659 * @param WANObjectCache $cache
3663 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3664 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3666 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );