3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\RevisionRenderer
;
28 use MediaWiki\Revision\RevisionStore
;
29 use MediaWiki\Revision\SlotRoleRegistry
;
30 use MediaWiki\Revision\SlotRecord
;
31 use MediaWiki\Storage\DerivedPageDataUpdater
;
32 use MediaWiki\Storage\PageUpdater
;
33 use MediaWiki\Storage\RevisionSlotsUpdate
;
34 use Wikimedia\Assert\Assert
;
35 use Wikimedia\Rdbms\FakeResultWrapper
;
36 use Wikimedia\Rdbms\IDatabase
;
37 use Wikimedia\Rdbms\LoadBalancer
;
40 * Class representing a MediaWiki article and history.
42 * Some fields are public only for backwards-compatibility. Use accessors.
43 * In the past, this class was part of Article.php and everything was public.
45 * @phan-file-suppress PhanAccessMethodInternal Due to the use of DerivedPageDataUpdater
47 class WikiPage
implements Page
, IDBAccessObject
{
48 // Constants for $mDataLoadedFrom and related
53 public $mTitle = null;
59 public $mDataLoaded = false;
65 public $mIsRedirect = false;
68 * @var int|false False means "not loaded"
71 public $mLatest = false;
74 * @var PreparedEdit|false Map of cache fields (text, parser output, ect) for a proposed/new edit
76 public $mPreparedEdit = false;
81 protected $mId = null;
84 * @var int One of the READ_* constants
86 protected $mDataLoadedFrom = self
::READ_NONE
;
91 protected $mRedirectTarget = null;
96 protected $mLastRevision = null;
99 * @var string Timestamp of the current revision or empty string if not loaded
101 protected $mTimestamp = '';
106 protected $mTouched = '19700101000000';
111 protected $mLinksUpdated = '19700101000000';
114 * @var DerivedPageDataUpdater|null
116 private $derivedDataUpdater = null;
119 * Constructor and clear the article
120 * @param Title $title Reference to a Title object.
122 public function __construct( Title
$title ) {
123 $this->mTitle
= $title;
127 * Makes sure that the mTitle object is cloned
128 * to the newly cloned WikiPage.
130 public function __clone() {
131 $this->mTitle
= clone $this->mTitle
;
135 * Create a WikiPage object of the appropriate class for the given title.
137 * @param Title $title
139 * @throws MWException
140 * @return WikiPage|WikiCategoryPage|WikiFilePage
142 public static function factory( Title
$title ) {
143 $ns = $title->getNamespace();
145 if ( $ns == NS_MEDIA
) {
146 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
147 } elseif ( $ns < 0 ) {
148 throw new MWException( "Invalid or virtual namespace $ns given." );
152 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
158 $page = new WikiFilePage( $title );
161 $page = new WikiCategoryPage( $title );
164 $page = new WikiPage( $title );
171 * Constructor from a page id
173 * @param int $id Article ID to load
174 * @param string|int $from One of the following values:
175 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
176 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
178 * @return WikiPage|null
180 public static function newFromID( $id, $from = 'fromdb' ) {
181 // page ids are never 0 or negative, see T63166
186 $from = self
::convertSelectType( $from );
187 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
188 $pageQuery = self
::getQueryInfo();
189 $row = $db->selectRow(
190 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
191 [], $pageQuery['joins']
196 return self
::newFromRow( $row, $from );
200 * Constructor from a database row
203 * @param object $row Database row containing at least fields returned by selectFields().
204 * @param string|int $from Source of $data:
205 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
206 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
207 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
210 public static function newFromRow( $row, $from = 'fromdb' ) {
211 $page = self
::factory( Title
::newFromRow( $row ) );
212 $page->loadFromRow( $row, $from );
217 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
219 * @param object|string|int $type
222 protected static function convertSelectType( $type ) {
225 return self
::READ_NORMAL
;
227 return self
::READ_LATEST
;
229 return self
::READ_LOCKING
;
231 // It may already be an integer or whatever else
237 * @return RevisionStore
239 private function getRevisionStore() {
240 return MediaWikiServices
::getInstance()->getRevisionStore();
244 * @return RevisionRenderer
246 private function getRevisionRenderer() {
247 return MediaWikiServices
::getInstance()->getRevisionRenderer();
251 * @return SlotRoleRegistry
253 private function getSlotRoleRegistry() {
254 return MediaWikiServices
::getInstance()->getSlotRoleRegistry();
258 * @return ParserCache
260 private function getParserCache() {
261 return MediaWikiServices
::getInstance()->getParserCache();
265 * @return LoadBalancer
267 private function getDBLoadBalancer() {
268 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
272 * @todo Move this UI stuff somewhere else
274 * @see ContentHandler::getActionOverrides
277 public function getActionOverrides() {
278 return $this->getContentHandler()->getActionOverrides();
282 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
284 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
286 * @return ContentHandler
290 public function getContentHandler() {
291 return ContentHandler
::getForModelID( $this->getContentModel() );
295 * Get the title object of the article
296 * @return Title Title object of this page
298 public function getTitle() {
299 return $this->mTitle
;
306 public function clear() {
307 $this->mDataLoaded
= false;
308 $this->mDataLoadedFrom
= self
::READ_NONE
;
310 $this->clearCacheFields();
314 * Clear the object cache fields
317 protected function clearCacheFields() {
319 $this->mRedirectTarget
= null; // Title object if set
320 $this->mLastRevision
= null; // Latest revision
321 $this->mTouched
= '19700101000000';
322 $this->mLinksUpdated
= '19700101000000';
323 $this->mTimestamp
= '';
324 $this->mIsRedirect
= false;
325 $this->mLatest
= false;
326 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
327 // checks the requested rev ID and content against the cached one. For most
328 // content types, the output should not change during the lifetime of this cache.
329 // Clearing it can cause extra parses on edit for no reason.
333 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
337 public function clearPreparedEdit() {
338 $this->mPreparedEdit
= false;
342 * Return the list of revision fields that should be selected to create
345 * @deprecated since 1.31, use self::getQueryInfo() instead.
348 public static function selectFields() {
349 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
351 wfDeprecated( __METHOD__
, '1.31' );
362 'page_links_updated',
367 if ( $wgContentHandlerUseDB ) {
368 $fields[] = 'page_content_model';
371 if ( $wgPageLanguageUseDB ) {
372 $fields[] = 'page_lang';
379 * Return the tables, fields, and join conditions to be selected to create
382 * @return array With three keys:
383 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
384 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
385 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
387 public static function getQueryInfo() {
388 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
391 'tables' => [ 'page' ],
401 'page_links_updated',
408 if ( $wgContentHandlerUseDB ) {
409 $ret['fields'][] = 'page_content_model';
412 if ( $wgPageLanguageUseDB ) {
413 $ret['fields'][] = 'page_lang';
420 * Fetch a page record with the given conditions
421 * @param IDatabase $dbr
422 * @param array $conditions
423 * @param array $options
424 * @return object|bool Database result resource, or false on failure
426 protected function pageData( $dbr, $conditions, $options = [] ) {
427 $pageQuery = self
::getQueryInfo();
429 // Avoid PHP 7.1 warning of passing $this by reference
432 Hooks
::run( 'ArticlePageDataBefore', [
433 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
436 $row = $dbr->selectRow(
437 $pageQuery['tables'],
438 $pageQuery['fields'],
445 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
451 * Fetch a page record matching the Title object's namespace and title
452 * using a sanitized title string
454 * @param IDatabase $dbr
455 * @param Title $title
456 * @param array $options
457 * @return object|bool Database result resource, or false on failure
459 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
460 return $this->pageData( $dbr, [
461 'page_namespace' => $title->getNamespace(),
462 'page_title' => $title->getDBkey() ], $options );
466 * Fetch a page record matching the requested ID
468 * @param IDatabase $dbr
470 * @param array $options
471 * @return object|bool Database result resource, or false on failure
473 public function pageDataFromId( $dbr, $id, $options = [] ) {
474 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
478 * Load the object from a given source by title
480 * @param object|string|int $from One of the following:
481 * - A DB query result object.
482 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
483 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
484 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
485 * using SELECT FOR UPDATE.
489 public function loadPageData( $from = 'fromdb' ) {
490 $from = self
::convertSelectType( $from );
491 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
492 // We already have the data from the correct location, no need to load it twice.
496 if ( is_int( $from ) ) {
497 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
498 $loadBalancer = $this->getDBLoadBalancer();
499 $db = $loadBalancer->getConnection( $index );
500 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
503 && $index == DB_REPLICA
504 && $loadBalancer->getServerCount() > 1
505 && $loadBalancer->hasOrMadeRecentMasterChanges()
507 $from = self
::READ_LATEST
;
508 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
509 $db = $loadBalancer->getConnection( $index );
510 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
513 // No idea from where the caller got this data, assume replica DB.
515 $from = self
::READ_NORMAL
;
518 $this->loadFromRow( $data, $from );
522 * Checks whether the page data was loaded using the given database access mode (or better).
526 * @param string|int $from One of the following:
527 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
528 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
529 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
530 * using SELECT FOR UPDATE.
534 public function wasLoadedFrom( $from ) {
535 $from = self
::convertSelectType( $from );
537 if ( !is_int( $from ) ) {
538 // No idea from where the caller got this data, assume replica DB.
539 $from = self
::READ_NORMAL
;
542 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
550 * Load the object from a database row
553 * @param object|bool $data DB row containing fields returned by selectFields() or false
554 * @param string|int $from One of the following:
555 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
556 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
557 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
558 * the master DB using SELECT FOR UPDATE
560 public function loadFromRow( $data, $from ) {
561 $lc = MediaWikiServices
::getInstance()->getLinkCache();
562 $lc->clearLink( $this->mTitle
);
565 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
567 $this->mTitle
->loadFromRow( $data );
569 // Old-fashioned restrictions
570 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
572 $this->mId
= intval( $data->page_id
);
573 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
574 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
575 $this->mIsRedirect
= intval( $data->page_is_redirect
);
576 $this->mLatest
= intval( $data->page_latest
);
577 // T39225: $latest may no longer match the cached latest Revision object.
578 // Double-check the ID of any cached latest Revision object for consistency.
579 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
580 $this->mLastRevision
= null;
581 $this->mTimestamp
= '';
584 $lc->addBadLinkObj( $this->mTitle
);
586 $this->mTitle
->loadFromRow( false );
588 $this->clearCacheFields();
593 $this->mDataLoaded
= true;
594 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
598 * @return int Page ID
600 public function getId() {
601 if ( !$this->mDataLoaded
) {
602 $this->loadPageData();
608 * @return bool Whether or not the page exists in the database
610 public function exists() {
611 if ( !$this->mDataLoaded
) {
612 $this->loadPageData();
614 return $this->mId
> 0;
618 * Check if this page is something we're going to be showing
619 * some sort of sensible content for. If we return false, page
620 * views (plain action=view) will return an HTTP 404 response,
621 * so spiders and robots can know they're following a bad link.
625 public function hasViewableContent() {
626 return $this->mTitle
->isKnown();
630 * Tests if the article content represents a redirect
634 public function isRedirect() {
635 if ( !$this->mDataLoaded
) {
636 $this->loadPageData();
639 return (bool)$this->mIsRedirect
;
643 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
645 * Will use the revisions actual content model if the page exists,
646 * and the page's default if the page doesn't exist yet.
652 public function getContentModel() {
653 if ( $this->exists() ) {
654 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
656 return $cache->getWithSetCallback(
657 $cache->makeKey( 'page-content-model', $this->getLatest() ),
660 $rev = $this->getRevision();
662 // Look at the revision's actual content model
663 return $rev->getContentModel();
665 $title = $this->mTitle
->getPrefixedDBkey();
666 wfWarn( "Page $title exists but has no (visible) revisions!" );
667 return $this->mTitle
->getContentModel();
673 // use the default model for this page
674 return $this->mTitle
->getContentModel();
678 * Loads page_touched and returns a value indicating if it should be used
679 * @return bool True if this page exists and is not a redirect
681 public function checkTouched() {
682 if ( !$this->mDataLoaded
) {
683 $this->loadPageData();
685 return ( $this->mId
&& !$this->mIsRedirect
);
689 * Get the page_touched field
690 * @return string Containing GMT timestamp
692 public function getTouched() {
693 if ( !$this->mDataLoaded
) {
694 $this->loadPageData();
696 return $this->mTouched
;
700 * Get the page_links_updated field
701 * @return string|null Containing GMT timestamp
703 public function getLinksTimestamp() {
704 if ( !$this->mDataLoaded
) {
705 $this->loadPageData();
707 return $this->mLinksUpdated
;
711 * Get the page_latest field
712 * @return int The rev_id of current revision
714 public function getLatest() {
715 if ( !$this->mDataLoaded
) {
716 $this->loadPageData();
718 return (int)$this->mLatest
;
722 * Get the Revision object of the oldest revision
723 * @return Revision|null
725 public function getOldestRevision() {
726 // Try using the replica DB first, then try the master
727 $rev = $this->mTitle
->getFirstRevision();
729 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
735 * Loads everything except the text
736 * This isn't necessary for all uses, so it's only done if needed.
738 protected function loadLastEdit() {
739 if ( $this->mLastRevision
!== null ) {
740 return; // already loaded
743 $latest = $this->getLatest();
745 return; // page doesn't exist or is missing page_latest info
748 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
749 // T39225: if session S1 loads the page row FOR UPDATE, the result always
750 // includes the latest changes committed. This is true even within REPEATABLE-READ
751 // transactions, where S1 normally only sees changes committed before the first S1
752 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
753 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
754 // happened after the first S1 SELECT.
755 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
756 $flags = Revision
::READ_LOCKING
;
757 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
758 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
759 // Bug T93976: if page_latest was loaded from the master, fetch the
760 // revision from there as well, as it may not exist yet on a replica DB.
761 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
762 $flags = Revision
::READ_LATEST
;
763 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
765 $dbr = wfGetDB( DB_REPLICA
);
766 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
769 if ( $revision ) { // sanity
770 $this->setLastEdit( $revision );
775 * Set the latest revision
776 * @param Revision $revision
778 protected function setLastEdit( Revision
$revision ) {
779 $this->mLastRevision
= $revision;
780 $this->mTimestamp
= $revision->getTimestamp();
784 * Get the latest revision
785 * @return Revision|null
787 public function getRevision() {
788 $this->loadLastEdit();
789 if ( $this->mLastRevision
) {
790 return $this->mLastRevision
;
796 * Get the latest revision
797 * @return RevisionRecord|null
799 public function getRevisionRecord() {
800 $this->loadLastEdit();
801 if ( $this->mLastRevision
) {
802 return $this->mLastRevision
->getRevisionRecord();
808 * Get the content of the current revision. No side-effects...
810 * @param int $audience One of:
811 * Revision::FOR_PUBLIC to be displayed to all users
812 * Revision::FOR_THIS_USER to be displayed to $wgUser
813 * Revision::RAW get the text regardless of permissions
814 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
815 * to the $audience parameter
816 * @return Content|null The content of the current revision
820 public function getContent( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
821 $this->loadLastEdit();
822 if ( $this->mLastRevision
) {
823 return $this->mLastRevision
->getContent( $audience, $user );
829 * @return string MW timestamp of last article revision
831 public function getTimestamp() {
832 // Check if the field has been filled by WikiPage::setTimestamp()
833 if ( !$this->mTimestamp
) {
834 $this->loadLastEdit();
837 return wfTimestamp( TS_MW
, $this->mTimestamp
);
841 * Set the page timestamp (use only to avoid DB queries)
842 * @param string $ts MW timestamp of last article revision
845 public function setTimestamp( $ts ) {
846 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
850 * @param int $audience One of:
851 * Revision::FOR_PUBLIC to be displayed to all users
852 * Revision::FOR_THIS_USER to be displayed to the given user
853 * Revision::RAW get the text regardless of permissions
854 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
855 * to the $audience parameter
856 * @return int User ID for the user that made the last article revision
858 public function getUser( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
859 $this->loadLastEdit();
860 if ( $this->mLastRevision
) {
861 return $this->mLastRevision
->getUser( $audience, $user );
868 * Get the User object of the user who created the page
869 * @param int $audience One of:
870 * Revision::FOR_PUBLIC to be displayed to all users
871 * Revision::FOR_THIS_USER to be displayed to the given user
872 * Revision::RAW get the text regardless of permissions
873 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
874 * to the $audience parameter
877 public function getCreator( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
878 $revision = $this->getOldestRevision();
880 $userName = $revision->getUserText( $audience, $user );
881 return User
::newFromName( $userName, false );
888 * @param int $audience One of:
889 * Revision::FOR_PUBLIC to be displayed to all users
890 * Revision::FOR_THIS_USER to be displayed to the given user
891 * Revision::RAW get the text regardless of permissions
892 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
893 * to the $audience parameter
894 * @return string Username of the user that made the last article revision
896 public function getUserText( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
897 $this->loadLastEdit();
898 if ( $this->mLastRevision
) {
899 return $this->mLastRevision
->getUserText( $audience, $user );
906 * @param int $audience One of:
907 * Revision::FOR_PUBLIC to be displayed to all users
908 * Revision::FOR_THIS_USER to be displayed to the given user
909 * Revision::RAW get the text regardless of permissions
910 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
911 * to the $audience parameter
912 * @return string|null Comment stored for the last article revision, or null if the specified
913 * audience does not have access to the comment.
915 public function getComment( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
916 $this->loadLastEdit();
917 if ( $this->mLastRevision
) {
918 return $this->mLastRevision
->getComment( $audience, $user );
925 * Returns true if last revision was marked as "minor edit"
927 * @return bool Minor edit indicator for the last article revision.
929 public function getMinorEdit() {
930 $this->loadLastEdit();
931 if ( $this->mLastRevision
) {
932 return $this->mLastRevision
->isMinor();
939 * Determine whether a page would be suitable for being counted as an
940 * article in the site_stats table based on the title & its content
942 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
943 * if false, the current database state will be used
946 public function isCountable( $editInfo = false ) {
947 global $wgArticleCountMethod;
949 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
951 if ( !$this->mTitle
->isContentPage() ) {
956 // NOTE: only the main slot can make a page a redirect
957 $content = $editInfo->pstContent
;
959 $content = $this->getContent();
962 if ( !$content ||
$content->isRedirect() ) {
968 if ( $wgArticleCountMethod === 'link' ) {
969 // nasty special case to avoid re-parsing to detect links
972 // ParserOutput::getLinks() is a 2D array of page links, so
973 // to be really correct we would need to recurse in the array
974 // but the main array should only have items in it if there are
976 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
978 // NOTE: keep in sync with RevisionRenderer::getLinkCount
979 // NOTE: keep in sync with DerivedPageDataUpdater::isCountable
980 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
981 [ 'pl_from' => $this->getId() ], __METHOD__
);
985 // TODO: MCR: determine $hasLinks for each slot, and use that info
986 // with that slot's Content's isCountable method. That requires per-
987 // slot ParserOutput in the ParserCache, or per-slot info in the
989 return $content->isCountable( $hasLinks );
993 * If this page is a redirect, get its target
995 * The target will be fetched from the redirect table if possible.
996 * If this page doesn't have an entry there, call insertRedirect()
997 * @return Title|null Title object, or null if this page is not a redirect
999 public function getRedirectTarget() {
1000 if ( !$this->mTitle
->isRedirect() ) {
1004 if ( $this->mRedirectTarget
!== null ) {
1005 return $this->mRedirectTarget
;
1008 // Query the redirect table
1009 $dbr = wfGetDB( DB_REPLICA
);
1010 $row = $dbr->selectRow( 'redirect',
1011 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1012 [ 'rd_from' => $this->getId() ],
1016 // rd_fragment and rd_interwiki were added later, populate them if empty
1017 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
1018 // (T203942) We can't redirect to Media namespace because it's virtual.
1019 // We don't want to modify Title objects farther down the
1020 // line. So, let's fix this here by changing to File namespace.
1021 if ( $row->rd_namespace
== NS_MEDIA
) {
1022 $namespace = NS_FILE
;
1024 $namespace = $row->rd_namespace
;
1026 $this->mRedirectTarget
= Title
::makeTitle(
1027 $namespace, $row->rd_title
,
1028 $row->rd_fragment
, $row->rd_interwiki
1030 return $this->mRedirectTarget
;
1033 // This page doesn't have an entry in the redirect table
1034 $this->mRedirectTarget
= $this->insertRedirect();
1035 return $this->mRedirectTarget
;
1039 * Insert an entry for this page into the redirect table if the content is a redirect
1041 * The database update will be deferred via DeferredUpdates
1043 * Don't call this function directly unless you know what you're doing.
1044 * @return Title|null Title object or null if not a redirect
1046 public function insertRedirect() {
1047 $content = $this->getContent();
1048 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1053 // Update the DB post-send if the page has not cached since now
1054 $latest = $this->getLatest();
1055 DeferredUpdates
::addCallableUpdate(
1056 function () use ( $retval, $latest ) {
1057 $this->insertRedirectEntry( $retval, $latest );
1059 DeferredUpdates
::POSTSEND
,
1060 wfGetDB( DB_MASTER
)
1067 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1068 * @param Title $rt Redirect target
1069 * @param int|null $oldLatest Prior page_latest for check and set
1070 * @return bool Success
1072 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1073 $dbw = wfGetDB( DB_MASTER
);
1074 $dbw->startAtomic( __METHOD__
);
1076 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1077 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1078 $truncatedFragment = $contLang->truncateForDatabase( $rt->getFragment(), 255 );
1082 'rd_from' => $this->getId(),
1083 'rd_namespace' => $rt->getNamespace(),
1084 'rd_title' => $rt->getDBkey(),
1085 'rd_fragment' => $truncatedFragment,
1086 'rd_interwiki' => $rt->getInterwiki(),
1090 'rd_namespace' => $rt->getNamespace(),
1091 'rd_title' => $rt->getDBkey(),
1092 'rd_fragment' => $truncatedFragment,
1093 'rd_interwiki' => $rt->getInterwiki(),
1102 $dbw->endAtomic( __METHOD__
);
1108 * Get the Title object or URL this page redirects to
1110 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1112 public function followRedirect() {
1113 return $this->getRedirectURL( $this->getRedirectTarget() );
1117 * Get the Title object or URL to use for a redirect. We use Title
1118 * objects for same-wiki, non-special redirects and URLs for everything
1120 * @param Title $rt Redirect target
1121 * @return bool|Title|string False, Title object of local target, or string with URL
1123 public function getRedirectURL( $rt ) {
1128 if ( $rt->isExternal() ) {
1129 if ( $rt->isLocal() ) {
1130 // Offsite wikis need an HTTP redirect.
1131 // This can be hard to reverse and may produce loops,
1132 // so they may be disabled in the site configuration.
1133 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1134 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1136 // External pages without "local" bit set are not valid
1142 if ( $rt->isSpecialPage() ) {
1143 // Gotta handle redirects to special pages differently:
1144 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1145 // Some pages are not valid targets.
1146 if ( $rt->isValidRedirectTarget() ) {
1147 return $rt->getFullURL();
1157 * Get a list of users who have edited this article, not including the user who made
1158 * the most recent revision, which you can get from $article->getUser() if you want it
1159 * @return UserArrayFromResult
1161 public function getContributors() {
1162 // @todo: This is expensive; cache this info somewhere.
1164 $dbr = wfGetDB( DB_REPLICA
);
1166 $actorMigration = ActorMigration
::newMigration();
1167 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1169 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1172 'user_id' => $actorQuery['fields']['rev_user'],
1173 'user_name' => $actorQuery['fields']['rev_user_text'],
1174 'actor_id' => $actorQuery['fields']['rev_actor'],
1175 'user_real_name' => 'MIN(user_real_name)',
1176 'timestamp' => 'MAX(rev_timestamp)',
1179 $conds = [ 'rev_page' => $this->getId() ];
1181 // The user who made the top revision gets credited as "this page was last edited by
1182 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1183 $user = $this->getUser()
1184 ? User
::newFromId( $this->getUser() )
1185 : User
::newFromName( $this->getUserText(), false );
1186 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1189 $conds[] = "{$dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER )} = 0";
1192 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1193 ] +
$actorQuery['joins'];
1196 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1197 'ORDER BY' => 'timestamp DESC',
1200 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1201 return new UserArrayFromResult( $res );
1205 * Should the parser cache be used?
1207 * @param ParserOptions $parserOptions ParserOptions to check
1211 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1212 return $parserOptions->getStubThreshold() == 0
1214 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1215 && $this->getContentHandler()->isParserCacheSupported();
1219 * Get a ParserOutput for the given ParserOptions and revision ID.
1221 * The parser cache will be used if possible. Cache misses that result
1222 * in parser runs are debounced with PoolCounter.
1224 * XXX merge this with updateParserCache()?
1227 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1228 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1229 * get the current revision (default value)
1230 * @param bool $forceParse Force reindexing, regardless of cache settings
1231 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1233 public function getParserOutput(
1234 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1237 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1239 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1240 throw new InvalidArgumentException(
1241 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1245 wfDebug( __METHOD__
.
1246 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1247 if ( $parserOptions->getStubThreshold() ) {
1248 wfIncrStats( 'pcache.miss.stub' );
1251 if ( $useParserCache ) {
1252 $parserOutput = $this->getParserCache()
1253 ->get( $this, $parserOptions );
1254 if ( $parserOutput !== false ) {
1255 return $parserOutput;
1259 if ( $oldid === null ||
$oldid === 0 ) {
1260 $oldid = $this->getLatest();
1263 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1266 return $pool->getParserOutput();
1270 * Do standard deferred updates after page view (existing or missing page)
1271 * @param User $user The relevant user
1272 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1274 public function doViewUpdates( User
$user, $oldid = 0 ) {
1275 if ( wfReadOnly() ) {
1279 // Update newtalk / watchlist notification status;
1280 // Avoid outage if the master is not reachable by using a deferred updated
1281 DeferredUpdates
::addCallableUpdate(
1282 function () use ( $user, $oldid ) {
1283 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1285 $user->clearNotification( $this->mTitle
, $oldid );
1287 DeferredUpdates
::PRESEND
1292 * Perform the actions of a page purging
1294 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1295 * controlled how much purging was done.
1297 public function doPurge() {
1298 // Avoid PHP 7.1 warning of passing $this by reference
1301 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1305 $this->mTitle
->invalidateCache();
1308 HTMLFileCache
::clearFileCache( $this->getTitle() );
1309 // Send purge after above page_touched update was committed
1310 DeferredUpdates
::addUpdate(
1311 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1312 DeferredUpdates
::PRESEND
1315 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1316 $messageCache = MessageCache
::singleton();
1317 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1324 * Insert a new empty page record for this article.
1325 * This *must* be followed up by creating a revision
1326 * and running $this->updateRevisionOn( ... );
1327 * or else the record will be left in a funky state.
1328 * Best if all done inside a transaction.
1330 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1332 * @param IDatabase $dbw
1333 * @param int|null $pageId Custom page ID that will be used for the insert statement
1335 * @return bool|int The newly created page_id key; false if the row was not
1336 * inserted, e.g. because the title already existed or because the specified
1337 * page ID is already in use.
1339 public function insertOn( $dbw, $pageId = null ) {
1340 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1344 'page_namespace' => $this->mTitle
->getNamespace(),
1345 'page_title' => $this->mTitle
->getDBkey(),
1346 'page_restrictions' => '',
1347 'page_is_redirect' => 0, // Will set this shortly...
1349 'page_random' => wfRandom(),
1350 'page_touched' => $dbw->timestamp(),
1351 'page_latest' => 0, // Fill this in shortly...
1352 'page_len' => 0, // Fill this in shortly...
1353 ] +
$pageIdForInsert,
1358 if ( $dbw->affectedRows() > 0 ) {
1359 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1360 $this->mId
= $newid;
1361 $this->mTitle
->resetArticleID( $newid );
1365 return false; // nothing changed
1370 * Update the page record to point to a newly saved revision.
1372 * @todo Factor out into a PageStore service, or move into PageUpdater.
1374 * @param IDatabase $dbw
1375 * @param Revision $revision For ID number, and text used to set
1376 * length and redirect status fields
1377 * @param int|null $lastRevision If given, will not overwrite the page field
1378 * when different from the currently set value.
1379 * Giving 0 indicates the new page flag should be set on.
1380 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1381 * removing rows in redirect table.
1382 * @return bool Success; false if the page row was missing or page_latest changed
1384 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1385 $lastRevIsRedirect = null
1387 global $wgContentHandlerUseDB;
1389 // TODO: move into PageUpdater or PageStore
1390 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1391 // and in the compat stub!
1393 // Assertion to try to catch T92046
1394 if ( (int)$revision->getId() === 0 ) {
1395 throw new InvalidArgumentException(
1396 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1400 $content = $revision->getContent();
1401 $len = $content ?
$content->getSize() : 0;
1402 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1404 $conditions = [ 'page_id' => $this->getId() ];
1406 if ( !is_null( $lastRevision ) ) {
1407 // An extra check against threads stepping on each other
1408 $conditions['page_latest'] = $lastRevision;
1411 $revId = $revision->getId();
1412 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1415 'page_latest' => $revId,
1416 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1417 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1418 'page_is_redirect' => $rt !== null ?
1 : 0,
1422 if ( $wgContentHandlerUseDB ) {
1423 $row['page_content_model'] = $revision->getContentModel();
1426 $dbw->update( 'page',
1431 $result = $dbw->affectedRows() > 0;
1433 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1434 $this->setLastEdit( $revision );
1435 $this->mLatest
= $revision->getId();
1436 $this->mIsRedirect
= (bool)$rt;
1437 // Update the LinkCache.
1438 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1439 $linkCache->addGoodLinkObj(
1445 $revision->getContentModel()
1453 * Add row to the redirect table if this is a redirect, remove otherwise.
1455 * @param IDatabase $dbw
1456 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1457 * or NULL if this is not a redirect
1458 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1459 * removing rows in redirect table.
1460 * @return bool True on success, false on failure
1463 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1464 // Always update redirects (target link might have changed)
1465 // Update/Insert if we don't know if the last revision was a redirect or not
1466 // Delete if changing from redirect to non-redirect
1467 $isRedirect = !is_null( $redirectTitle );
1469 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1473 if ( $isRedirect ) {
1474 $success = $this->insertRedirectEntry( $redirectTitle );
1476 // This is not a redirect, remove row from redirect table
1477 $where = [ 'rd_from' => $this->getId() ];
1478 $dbw->delete( 'redirect', $where, __METHOD__
);
1482 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1483 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1490 * If the given revision is newer than the currently set page_latest,
1491 * update the page record. Otherwise, do nothing.
1493 * @deprecated since 1.24, use updateRevisionOn instead
1495 * @param IDatabase $dbw
1496 * @param Revision $revision
1499 public function updateIfNewerOn( $dbw, $revision ) {
1500 $row = $dbw->selectRow(
1501 [ 'revision', 'page' ],
1502 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1504 'page_id' => $this->getId(),
1505 'page_latest=rev_id' ],
1509 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1512 $prev = $row->rev_id
;
1513 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1515 // No or missing previous revision; mark the page as new
1517 $lastRevIsRedirect = null;
1520 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1526 * Helper method for checking whether two revisions have differences that go
1527 * beyond the main slot.
1529 * MCR migration note: this method should go away!
1531 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1533 * @param Revision $a
1534 * @param Revision $b
1537 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1538 $aSlots = $a->getRevisionRecord()->getSlots();
1539 $bSlots = $b->getRevisionRecord()->getSlots();
1540 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1542 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1546 * Get the content that needs to be saved in order to undo all revisions
1547 * between $undo and $undoafter. Revisions must belong to the same page,
1548 * must exist and must not be deleted
1550 * @param Revision $undo
1551 * @param Revision $undoafter Must be an earlier revision than $undo
1552 * @return Content|bool Content on success, false on failure
1554 * Before we had the Content object, this was done in getUndoText
1556 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1557 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1559 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1560 // Cannot yet undo edits that involve anything other the main slot.
1564 $handler = $undo->getContentHandler();
1565 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1569 * Returns true if this page's content model supports sections.
1573 * @todo The skin should check this and not offer section functionality if
1574 * sections are not supported.
1575 * @todo The EditPage should check this and not offer section functionality
1576 * if sections are not supported.
1578 public function supportsSections() {
1579 return $this->getContentHandler()->supportsSections();
1583 * @param string|int|null|bool $sectionId Section identifier as a number or string
1584 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1585 * or 'new' for a new section.
1586 * @param Content $sectionContent New content of the section.
1587 * @param string $sectionTitle New section's subject, only if $section is "new".
1588 * @param string $edittime Revision timestamp or null to use the current revision.
1590 * @throws MWException
1591 * @return Content|null New complete article content, or null if error.
1594 * @deprecated since 1.24, use replaceSectionAtRev instead
1596 public function replaceSectionContent(
1597 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1600 if ( $edittime && $sectionId !== 'new' ) {
1601 $lb = $this->getDBLoadBalancer();
1602 $dbr = $lb->getConnectionRef( DB_REPLICA
);
1603 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1604 // Try the master if this thread may have just added it.
1605 // This could be abstracted into a Revision method, but we don't want
1606 // to encourage loading of revisions by timestamp.
1608 && $lb->getServerCount() > 1
1609 && $lb->hasOrMadeRecentMasterChanges()
1611 $dbw = $lb->getConnectionRef( DB_MASTER
);
1612 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1615 $baseRevId = $rev->getId();
1619 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1623 * @param string|int|null|bool $sectionId Section identifier as a number or string
1624 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1625 * or 'new' for a new section.
1626 * @param Content $sectionContent New content of the section.
1627 * @param string $sectionTitle New section's subject, only if $section is "new".
1628 * @param int|null $baseRevId
1630 * @throws MWException
1631 * @return Content|null New complete article content, or null if error.
1635 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1636 $sectionTitle = '', $baseRevId = null
1638 if ( strval( $sectionId ) === '' ) {
1639 // Whole-page edit; let the whole text through
1640 $newContent = $sectionContent;
1642 if ( !$this->supportsSections() ) {
1643 throw new MWException( "sections not supported for content model " .
1644 $this->getContentHandler()->getModelID() );
1647 // T32711: always use current version when adding a new section
1648 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1649 $oldContent = $this->getContent();
1651 $rev = Revision
::newFromId( $baseRevId );
1653 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1654 $this->getId() . "; section: $sectionId)\n" );
1658 $oldContent = $rev->getContent();
1661 if ( !$oldContent ) {
1662 wfDebug( __METHOD__
. ": no page text\n" );
1666 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1673 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1675 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1676 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1679 * @return int Updated $flags
1681 public function checkFlags( $flags ) {
1682 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1683 if ( $this->exists() ) {
1684 $flags |
= EDIT_UPDATE
;
1694 * @return DerivedPageDataUpdater
1696 private function newDerivedDataUpdater() {
1697 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1699 $derivedDataUpdater = new DerivedPageDataUpdater(
1700 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1701 $this->getRevisionStore(),
1702 $this->getRevisionRenderer(),
1703 $this->getSlotRoleRegistry(),
1704 $this->getParserCache(),
1705 JobQueueGroup
::singleton(),
1706 MessageCache
::singleton(),
1707 MediaWikiServices
::getInstance()->getContentLanguage(),
1708 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1711 $derivedDataUpdater->setLogger( LoggerFactory
::getInstance( 'SaveParse' ) );
1712 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1713 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1715 return $derivedDataUpdater;
1719 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1720 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1721 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1722 * returned matches that caller's expectations, allowing an existing instance to be re-used
1723 * if the given parameters match that instance's internal state according to
1724 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1725 * match the existign one.
1727 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1728 * created, replacing any DerivedPageDataUpdater currently cached.
1730 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1734 * @param User|null $forUser The user that will be used for, or was used for, PST.
1735 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1736 * to perform updates, if the edit was already saved.
1737 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1738 * if the edit was not yet saved.
1739 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1740 * revision as the edit's parent revision. This ensures that the same
1741 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1743 * @return DerivedPageDataUpdater
1745 private function getDerivedDataUpdater(
1746 User
$forUser = null,
1747 RevisionRecord
$forRevision = null,
1748 RevisionSlotsUpdate
$forUpdate = null,
1751 if ( !$forRevision && !$forUpdate ) {
1752 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1753 // going to use it with.
1754 $this->derivedDataUpdater
= null;
1757 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1758 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1759 // to it did not yet initialize it, because we don't know what data it will be
1760 // initialized with.
1761 $this->derivedDataUpdater
= null;
1764 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1765 // However, there is no good way to construct a cache key. We'd need to check against all
1766 // cached instances.
1768 if ( $this->derivedDataUpdater
1769 && !$this->derivedDataUpdater
->isReusableFor(
1773 $forEdit ?
$this->getLatest() : null
1776 $this->derivedDataUpdater
= null;
1779 if ( !$this->derivedDataUpdater
) {
1780 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1783 return $this->derivedDataUpdater
;
1787 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1789 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1790 * and to protected such conflict resolution from concurrent edits using a check-and-set
1796 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1797 * that may already have been returned via getDerivedDataUpdater to be re-used.
1799 * @return PageUpdater
1801 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1802 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1804 $pageUpdater = new PageUpdater(
1806 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1807 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1808 $this->getDBLoadBalancer(),
1809 $this->getRevisionStore(),
1810 $this->getSlotRoleRegistry()
1813 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1814 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1815 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1817 return $pageUpdater;
1821 * Change an existing article or create a new article. Updates RC and all necessary caches,
1822 * optionally via the deferred update array.
1824 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1825 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1826 * apply the autopatrol right as appropriate.
1828 * @param Content $content New content
1829 * @param string|CommentStoreComment $summary Edit summary
1830 * @param int $flags Bitfield:
1832 * Article is known or assumed to be non-existent, create a new one
1834 * Article is known or assumed to be pre-existing, update it
1836 * Mark this edit minor, if the user is allowed to do so
1838 * Do not log the change in recentchanges
1840 * Mark the edit a "bot" edit regardless of user rights
1842 * Fill in blank summaries with generated text where possible
1844 * Signal that the page retrieve/save cycle happened entirely in this request.
1846 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1847 * article will be detected. If EDIT_UPDATE is specified and the article
1848 * doesn't exist, the function will return an edit-gone-missing error. If
1849 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1850 * error will be returned. These two conditions are also possible with
1851 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1853 * @param bool|int $originalRevId: The ID of an original revision that the edit
1854 * restores or repeats. The new revision is expected to have the exact same content as
1855 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1856 * which are created to record things like page moves.
1857 * @param User|null $user The user doing the edit
1858 * @param string|null $serialFormat IGNORED.
1859 * @param array|null $tags Change tags to apply to this edit
1860 * Callers are responsible for permission checks
1861 * (with ChangeTags::canAddTagsAccompanyingChange)
1862 * @param Int $undidRevId Id of revision that was undone or 0
1864 * @throws MWException
1865 * @return Status Possible errors:
1866 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1867 * set the fatal flag of $status.
1868 * edit-gone-missing: In update mode, but the article didn't exist.
1869 * edit-conflict: In update mode, the article changed unexpectedly.
1870 * edit-no-change: Warning that the text was the same as before.
1871 * edit-already-exists: In creation mode, but the article already exists.
1873 * Extensions may define additional errors.
1875 * $return->value will contain an associative array with members as follows:
1876 * new: Boolean indicating if the function attempted to create a new article.
1877 * revision: The revision object for the inserted revision, or null.
1880 * @throws MWException
1882 public function doEditContent(
1883 Content
$content, $summary, $flags = 0, $originalRevId = false,
1884 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1886 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1888 if ( !( $summary instanceof CommentStoreComment
) ) {
1889 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1896 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1897 // Checking the minoredit right should be done in the same place the 'bot' right is
1898 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1899 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1900 $flags = ( $flags & ~EDIT_MINOR
);
1903 $slotsUpdate = new RevisionSlotsUpdate();
1904 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1906 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1907 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1908 // used by this PageUpdater. However, there is no guarantee for this.
1909 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1910 $updater->setContent( SlotRecord
::MAIN
, $content );
1911 $updater->setOriginalRevisionId( $originalRevId );
1912 $updater->setUndidRevisionId( $undidRevId );
1914 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1916 // TODO: this logic should not be in the storage layer, it's here for compatibility
1917 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1918 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1919 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1921 if ( $needsPatrol && $permissionManager->userCan(
1922 'autopatrol', $user, $this->getTitle()
1924 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1927 $updater->addTags( $tags );
1929 $revRec = $updater->saveRevision(
1934 // $revRec will be null if the edit failed, or if no new revision was created because
1935 // the content did not change.
1937 // update cached fields
1938 // TODO: this is currently redundant to what is done in updateRevisionOn.
1939 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1940 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1941 $this->mLatest
= $revRec->getId();
1944 return $updater->getStatus();
1948 * Get parser options suitable for rendering the primary article wikitext
1950 * @see ParserOptions::newCanonical
1952 * @param IContextSource|User|string $context One of the following:
1953 * - IContextSource: Use the User and the Language of the provided
1955 * - User: Use the provided User object and $wgLang for the language,
1956 * so use an IContextSource object if possible.
1957 * - 'canonical': Canonical options (anonymous user with default
1958 * preferences and content language).
1959 * @return ParserOptions
1961 public function makeParserOptions( $context ) {
1962 $options = ParserOptions
::newCanonical( $context );
1964 if ( $this->getTitle()->isConversionTable() ) {
1965 // @todo ConversionTable should become a separate content model, so
1966 // we don't need special cases like this one.
1967 $options->disableContentConversion();
1974 * Prepare content which is about to be saved.
1976 * Prior to 1.30, this returned a stdClass.
1978 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1980 * @param Content $content
1981 * @param Revision|RevisionRecord|null $revision Revision object.
1982 * Used with vary-revision or vary-revision-id.
1983 * @param User|null $user
1984 * @param string|null $serialFormat IGNORED
1985 * @param bool $useCache Check shared prepared edit cache
1987 * @return PreparedEdit
1991 public function prepareContentForEdit(
1995 $serialFormat = null,
2004 if ( $revision !== null ) {
2005 if ( $revision instanceof Revision
) {
2006 $revision = $revision->getRevisionRecord();
2007 } elseif ( !( $revision instanceof RevisionRecord
) ) {
2008 throw new InvalidArgumentException(
2009 __METHOD__
. ': invalid $revision argument type ' . gettype( $revision ) );
2013 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
2014 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
2016 if ( !$updater->isUpdatePrepared() ) {
2017 $updater->prepareContent( $user, $slots, $useCache );
2020 $updater->prepareUpdate(
2023 'causeAction' => 'prepare-edit',
2024 'causeAgent' => $user->getName(),
2030 return $updater->getPreparedEdit();
2034 * Do standard deferred updates after page edit.
2035 * Update links tables, site stats, search index and message cache.
2036 * Purges pages that include this page if the text was changed here.
2037 * Every 100th edit, prune the recent changes table.
2039 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2041 * @param Revision $revision
2042 * @param User $user User object that did the revision
2043 * @param array $options Array of options, following indexes are used:
2044 * - changed: bool, whether the revision changed the content (default true)
2045 * - created: bool, whether the revision created the page (default false)
2046 * - moved: bool, whether the page was moved (default false)
2047 * - restored: bool, whether the page was undeleted (default false)
2048 * - oldrevision: Revision object for the pre-update revision (default null)
2049 * - oldcountable: bool, null, or string 'no-change' (default null):
2050 * - bool: whether the page was counted as an article before that
2051 * revision, only used in changed is true and created is false
2052 * - null: if created is false, don't update the article count; if created
2053 * is true, do update the article count
2054 * - 'no-change': don't update the article count, ever
2055 * - causeAction: an arbitrary string identifying the reason for the update.
2056 * See DataUpdate::getCauseAction(). (default 'edit-page')
2057 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2058 * (string, defaults to the passed user)
2060 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2062 'causeAction' => 'edit-page',
2063 'causeAgent' => $user->getName(),
2066 $revision = $revision->getRevisionRecord();
2068 $updater = $this->getDerivedDataUpdater( $user, $revision );
2070 $updater->prepareUpdate( $revision, $options );
2072 $updater->doUpdates();
2076 * Update the parser cache.
2078 * @note This is a temporary workaround until there is a proper data updater class.
2079 * It will become deprecated soon.
2081 * @param array $options
2082 * - causeAction: an arbitrary string identifying the reason for the update.
2083 * See DataUpdate::getCauseAction(). (default 'edit-page')
2084 * - causeAgent: name of the user who caused the update (string, defaults to the
2085 * user who created the revision)
2088 public function updateParserCache( array $options = [] ) {
2089 $revision = $this->getRevisionRecord();
2090 if ( !$revision ||
!$revision->getId() ) {
2091 LoggerFactory
::getInstance( 'wikipage' )->info(
2092 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2096 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2098 $updater = $this->getDerivedDataUpdater( $user, $revision );
2099 $updater->prepareUpdate( $revision, $options );
2100 $updater->doParserCacheUpdate();
2104 * Do secondary data updates (such as updating link tables).
2105 * Secondary data updates are only a small part of the updates needed after saving
2106 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2107 * secondary data updates). This method is provided for partial purges.
2109 * @note This is a temporary workaround until there is a proper data updater class.
2110 * It will become deprecated soon.
2112 * @param array $options
2113 * - recursive (bool, default true): whether to do a recursive update (update pages that
2114 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2115 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2116 * was something that did not really change the page, such as a null edit.
2117 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2118 * user who created the revision)
2119 * - causeAction: an arbitrary string identifying the reason for the update.
2120 * See DataUpdate::getCauseAction(). (default 'unknown')
2121 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2122 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2123 * Note that even when this is set to false, some updates might still get deferred (as
2124 * some update might directly add child updates to DeferredUpdates).
2125 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
2126 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
2127 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
2128 * for the time until caches have been changed to store RenderedRevision states instead
2129 * of ParserOutput objects. (default: null) (since 1.33)
2132 public function doSecondaryDataUpdates( array $options = [] ) {
2133 $options['recursive'] = $options['recursive'] ??
true;
2134 $revision = $this->getRevisionRecord();
2135 if ( !$revision ||
!$revision->getId() ) {
2136 LoggerFactory
::getInstance( 'wikipage' )->info(
2137 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2141 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2143 $updater = $this->getDerivedDataUpdater( $user, $revision );
2144 $updater->prepareUpdate( $revision, $options );
2145 $updater->doSecondaryDataUpdates( $options );
2149 * Update the article's restriction field, and leave a log entry.
2150 * This works for protection both existing and non-existing pages.
2152 * @param array $limit Set of restriction keys
2153 * @param array $expiry Per restriction type expiration
2154 * @param int &$cascade Set to false if cascading protection isn't allowed.
2155 * @param string $reason
2156 * @param User $user The user updating the restrictions
2157 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2158 * ($user should be able to add the specified tags before this is called)
2159 * @return Status Status object; if action is taken, $status->value is the log_id of the
2160 * protection log entry.
2162 public function doUpdateRestrictions( array $limit, array $expiry,
2163 &$cascade, $reason, User
$user, $tags = null
2165 global $wgCascadingRestrictionLevels;
2167 if ( wfReadOnly() ) {
2168 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2171 $this->loadPageData( 'fromdbmaster' );
2172 $this->mTitle
->loadRestrictions( null, Title
::READ_LATEST
);
2173 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2174 $id = $this->getId();
2180 // Take this opportunity to purge out expired restrictions
2181 Title
::purgeExpiredRestrictions();
2183 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2184 // we expect a single selection, but the schema allows otherwise.
2185 $isProtected = false;
2189 $dbw = wfGetDB( DB_MASTER
);
2191 foreach ( $restrictionTypes as $action ) {
2192 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2193 $expiry[$action] = 'infinity';
2195 if ( !isset( $limit[$action] ) ) {
2196 $limit[$action] = '';
2197 } elseif ( $limit[$action] != '' ) {
2201 // Get current restrictions on $action
2202 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2203 if ( $current != '' ) {
2204 $isProtected = true;
2207 if ( $limit[$action] != $current ) {
2209 } elseif ( $limit[$action] != '' ) {
2210 // Only check expiry change if the action is actually being
2211 // protected, since expiry does nothing on an not-protected
2213 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2219 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2223 // If nothing has changed, do nothing
2225 return Status
::newGood();
2228 if ( !$protect ) { // No protection at all means unprotection
2229 $revCommentMsg = 'unprotectedarticle-comment';
2230 $logAction = 'unprotect';
2231 } elseif ( $isProtected ) {
2232 $revCommentMsg = 'modifiedarticleprotection-comment';
2233 $logAction = 'modify';
2235 $revCommentMsg = 'protectedarticle-comment';
2236 $logAction = 'protect';
2239 $logRelationsValues = [];
2240 $logRelationsField = null;
2241 $logParamsDetails = [];
2243 // Null revision (used for change tag insertion)
2244 $nullRevision = null;
2246 if ( $id ) { // Protection of existing page
2247 // Avoid PHP 7.1 warning of passing $this by reference
2250 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2251 return Status
::newGood();
2254 // Only certain restrictions can cascade...
2255 $editrestriction = isset( $limit['edit'] )
2256 ?
[ $limit['edit'] ]
2257 : $this->mTitle
->getRestrictions( 'edit' );
2258 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2259 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2261 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2262 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2265 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2266 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2267 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2269 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2270 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2273 // The schema allows multiple restrictions
2274 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2278 // insert null revision to identify the page protection change as edit summary
2279 $latest = $this->getLatest();
2280 $nullRevision = $this->insertProtectNullRevision(
2289 if ( $nullRevision === null ) {
2290 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2293 $logRelationsField = 'pr_id';
2295 // Update restrictions table
2296 foreach ( $limit as $action => $restrictions ) {
2298 'page_restrictions',
2301 'pr_type' => $action
2305 if ( $restrictions != '' ) {
2306 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2308 'page_restrictions',
2311 'pr_type' => $action,
2312 'pr_level' => $restrictions,
2313 'pr_cascade' => $cascadeValue,
2314 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2318 $logRelationsValues[] = $dbw->insertId();
2319 $logParamsDetails[] = [
2321 'level' => $restrictions,
2322 'expiry' => $expiry[$action],
2323 'cascade' => (bool)$cascadeValue,
2328 // Clear out legacy restriction fields
2331 [ 'page_restrictions' => '' ],
2332 [ 'page_id' => $id ],
2336 // Avoid PHP 7.1 warning of passing $this by reference
2339 Hooks
::run( 'NewRevisionFromEditComplete',
2340 [ $this, $nullRevision, $latest, $user ] );
2341 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2342 } else { // Protection of non-existing page (also known as "title protection")
2343 // Cascade protection is meaningless in this case
2346 if ( $limit['create'] != '' ) {
2347 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2348 $dbw->replace( 'protected_titles',
2349 [ [ 'pt_namespace', 'pt_title' ] ],
2351 'pt_namespace' => $this->mTitle
->getNamespace(),
2352 'pt_title' => $this->mTitle
->getDBkey(),
2353 'pt_create_perm' => $limit['create'],
2354 'pt_timestamp' => $dbw->timestamp(),
2355 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2356 'pt_user' => $user->getId(),
2357 ] +
$commentFields, __METHOD__
2359 $logParamsDetails[] = [
2361 'level' => $limit['create'],
2362 'expiry' => $expiry['create'],
2365 $dbw->delete( 'protected_titles',
2367 'pt_namespace' => $this->mTitle
->getNamespace(),
2368 'pt_title' => $this->mTitle
->getDBkey()
2374 $this->mTitle
->flushRestrictions();
2375 InfoAction
::invalidateCache( $this->mTitle
);
2377 if ( $logAction == 'unprotect' ) {
2380 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2382 '4::description' => $protectDescriptionLog, // parameter for IRC
2383 '5:bool:cascade' => $cascade,
2384 'details' => $logParamsDetails, // parameter for localize and api
2388 // Update the protection log
2389 $logEntry = new ManualLogEntry( 'protect', $logAction );
2390 $logEntry->setTarget( $this->mTitle
);
2391 $logEntry->setComment( $reason );
2392 $logEntry->setPerformer( $user );
2393 $logEntry->setParameters( $params );
2394 if ( !is_null( $nullRevision ) ) {
2395 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2397 $logEntry->addTags( $tags );
2398 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2399 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2401 $logId = $logEntry->insert();
2402 $logEntry->publish( $logId );
2404 return Status
::newGood( $logId );
2408 * Insert a new null revision for this page.
2410 * @param string $revCommentMsg Comment message key for the revision
2411 * @param array $limit Set of restriction keys
2412 * @param array $expiry Per restriction type expiration
2413 * @param int $cascade Set to false if cascading protection isn't allowed.
2414 * @param string $reason
2415 * @param User|null $user
2416 * @return Revision|null Null on error
2418 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2419 array $expiry, $cascade, $reason, $user = null
2421 $dbw = wfGetDB( DB_MASTER
);
2423 // Prepare a null revision to be added to the history
2424 $editComment = wfMessage(
2426 $this->mTitle
->getPrefixedText(),
2427 $user ?
$user->getName() : ''
2428 )->inContentLanguage()->text();
2430 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2432 $protectDescription = $this->protectDescription( $limit, $expiry );
2433 if ( $protectDescription ) {
2434 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2435 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2436 ->inContentLanguage()->text();
2439 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2440 $editComment .= wfMessage( 'brackets' )->params(
2441 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2442 )->inContentLanguage()->text();
2445 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2447 $nullRev->insertOn( $dbw );
2449 // Update page record and touch page
2450 $oldLatest = $nullRev->getParentId();
2451 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2458 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2461 protected function formatExpiry( $expiry ) {
2462 if ( $expiry != 'infinity' ) {
2463 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2466 $contLang->timeanddate( $expiry, false, false ),
2467 $contLang->date( $expiry, false, false ),
2468 $contLang->time( $expiry, false, false )
2469 )->inContentLanguage()->text();
2471 return wfMessage( 'protect-expiry-indefinite' )
2472 ->inContentLanguage()->text();
2477 * Builds the description to serve as comment for the edit.
2479 * @param array $limit Set of restriction keys
2480 * @param array $expiry Per restriction type expiration
2483 public function protectDescription( array $limit, array $expiry ) {
2484 $protectDescription = '';
2486 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2487 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2488 # All possible message keys are listed here for easier grepping:
2489 # * restriction-create
2490 # * restriction-edit
2491 # * restriction-move
2492 # * restriction-upload
2493 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2494 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2495 # with '' filtered out. All possible message keys are listed below:
2496 # * protect-level-autoconfirmed
2497 # * protect-level-sysop
2498 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2499 ->inContentLanguage()->text();
2501 $expiryText = $this->formatExpiry( $expiry[$action] );
2503 if ( $protectDescription !== '' ) {
2504 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2506 $protectDescription .= wfMessage( 'protect-summary-desc' )
2507 ->params( $actionText, $restrictionsText, $expiryText )
2508 ->inContentLanguage()->text();
2511 return $protectDescription;
2515 * Builds the description to serve as comment for the log entry.
2517 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2518 * protect description text. Keep them in old format to avoid breaking compatibility.
2519 * TODO: Fix protection log to store structured description and format it on-the-fly.
2521 * @param array $limit Set of restriction keys
2522 * @param array $expiry Per restriction type expiration
2525 public function protectDescriptionLog( array $limit, array $expiry ) {
2526 $protectDescriptionLog = '';
2528 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2529 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2530 $expiryText = $this->formatExpiry( $expiry[$action] );
2531 $protectDescriptionLog .=
2533 "[$action=$restrictions] ($expiryText)";
2536 return trim( $protectDescriptionLog );
2540 * Take an array of page restrictions and flatten it to a string
2541 * suitable for insertion into the page_restrictions field.
2543 * @param string[] $limit
2545 * @throws MWException
2548 protected static function flattenRestrictions( $limit ) {
2549 if ( !is_array( $limit ) ) {
2550 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2556 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2557 $bits[] = "$action=$restrictions";
2560 return implode( ':', $bits );
2564 * Determines if deletion of this page would be batched (executed over time by the job queue)
2565 * or not (completed in the same request as the delete call).
2567 * It is unlikely but possible that an edit from another request could push the page over the
2568 * batching threshold after this function is called, but before the caller acts upon the
2569 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2570 * is provided as an unreliable but situationally useful help for some common cases.
2572 * @param int $safetyMargin Added to the revision count when checking for batching
2573 * @return bool True if deletion would be batched, false otherwise
2575 public function isBatchedDelete( $safetyMargin = 0 ) {
2576 global $wgDeleteRevisionsBatchSize;
2578 $dbr = wfGetDB( DB_REPLICA
);
2579 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2580 $revCount +
= $safetyMargin;
2582 return $revCount >= $wgDeleteRevisionsBatchSize;
2586 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2587 * backwards compatibility, if you care about error reporting you should use
2588 * doDeleteArticleReal() instead.
2590 * Deletes the article with database consistency, writes logs, purges caches
2592 * @param string $reason Delete reason for deletion log
2593 * @param bool $suppress Suppress all revisions and log the deletion in
2594 * the suppression log instead of the deletion log
2595 * @param int|null $u1 Unused
2596 * @param bool|null $u2 Unused
2597 * @param array|string &$error Array of errors to append to
2598 * @param User|null $user The deleting user
2599 * @param bool $immediate false allows deleting over time via the job queue
2600 * @return bool True if successful
2601 * @throws FatalError
2602 * @throws MWException
2604 public function doDeleteArticle(
2605 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2608 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2609 [], 'delete', $immediate );
2611 // Returns true if the page was actually deleted, or is scheduled for deletion
2612 return $status->isOK();
2616 * Back-end article deletion
2617 * Deletes the article with database consistency, writes logs, purges caches
2621 * @param string $reason Delete reason for deletion log
2622 * @param bool $suppress Suppress all revisions and log the deletion in
2623 * the suppression log instead of the deletion log
2624 * @param int|null $u1 Unused
2625 * @param bool|null $u2 Unused
2626 * @param array|string &$error Array of errors to append to
2627 * @param User|null $deleter The deleting user
2628 * @param array $tags Tags to apply to the deletion action
2629 * @param string $logsubtype
2630 * @param bool $immediate false allows deleting over time via the job queue
2631 * @return Status Status object; if successful, $status->value is the log_id of the
2632 * deletion log entry. If the page couldn't be deleted because it wasn't
2633 * found, $status is a non-fatal 'cannotdelete' error
2634 * @throws FatalError
2635 * @throws MWException
2637 public function doDeleteArticleReal(
2638 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2639 $tags = [], $logsubtype = 'delete', $immediate = false
2643 wfDebug( __METHOD__
. "\n" );
2645 $status = Status
::newGood();
2647 // Avoid PHP 7.1 warning of passing $this by reference
2653 if ( !Hooks
::run( 'ArticleDelete',
2654 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2656 if ( $status->isOK() ) {
2657 // Hook aborted but didn't set a fatal status
2658 $status->fatal( 'delete-hook-aborted' );
2663 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2664 $logsubtype, $immediate );
2668 * Back-end article deletion
2670 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2671 * Deletions can often be completed inline without involving the job queue.
2673 * Potentially called many times per deletion operation for pages with many revisions.
2675 public function doDeleteArticleBatched(
2676 $reason, $suppress, User
$deleter, $tags,
2677 $logsubtype, $immediate = false, $webRequestId = null
2679 wfDebug( __METHOD__
. "\n" );
2681 $status = Status
::newGood();
2683 $dbw = wfGetDB( DB_MASTER
);
2684 $dbw->startAtomic( __METHOD__
);
2686 $this->loadPageData( self
::READ_LATEST
);
2687 $id = $this->getId();
2688 // T98706: lock the page from various other updates but avoid using
2689 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2690 // the revisions queries (which also JOIN on user). Only lock the page
2691 // row and CAS check on page_latest to see if the trx snapshot matches.
2692 $lockedLatest = $this->lockAndGetLatest();
2693 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2694 $dbw->endAtomic( __METHOD__
);
2695 // Page not there or trx snapshot is stale
2696 $status->error( 'cannotdelete',
2697 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2701 // At this point we are now committed to returning an OK
2702 // status unless some DB query error or other exception comes up.
2703 // This way callers don't have to call rollback() if $status is bad
2704 // unless they actually try to catch exceptions (which is rare).
2706 // we need to remember the old content so we can use it to generate all deletion updates.
2707 $revision = $this->getRevision();
2709 $content = $this->getContent( RevisionRecord
::RAW
);
2710 } catch ( Exception
$ex ) {
2711 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2712 . $ex->getMessage() );
2717 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2718 // one batch of revisions and defer archival of any others to the job queue.
2719 $explictTrxLogged = false;
2721 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2722 if ( $done ||
!$immediate ) {
2725 $dbw->endAtomic( __METHOD__
);
2726 if ( $dbw->explicitTrxActive() ) {
2727 // Explict transactions may never happen here in practice. Log to be sure.
2728 if ( !$explictTrxLogged ) {
2729 $explictTrxLogged = true;
2730 LoggerFactory
::getInstance( 'wfDebug' )->debug(
2731 'explicit transaction active in ' . __METHOD__
. ' while deleting {title}', [
2732 'title' => $this->getTitle()->getText(),
2737 if ( $dbw->trxLevel() ) {
2740 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
2741 $lbFactory->waitForReplication();
2742 $dbw->startAtomic( __METHOD__
);
2745 // If done archiving, also delete the article.
2747 $dbw->endAtomic( __METHOD__
);
2750 'namespace' => $this->getTitle()->getNamespace(),
2751 'title' => $this->getTitle()->getDBkey(),
2752 'wikiPageId' => $id,
2753 'requestId' => $webRequestId ?? WebRequest
::getRequestId(),
2754 'reason' => $reason,
2755 'suppress' => $suppress,
2756 'userId' => $deleter->getId(),
2757 'tags' => json_encode( $tags ),
2758 'logsubtype' => $logsubtype,
2761 $job = new DeletePageJob( $jobParams );
2762 JobQueueGroup
::singleton()->push( $job );
2764 $status->warning( 'delete-scheduled',
2765 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2767 // Get archivedRevisionCount by db query, because there's no better alternative.
2768 // Jobs cannot pass a count of archived revisions to the next job, because additional
2769 // deletion operations can be started while the first is running. Jobs from each
2770 // gracefully interleave, but would not know about each other's count. Deduplication
2771 // in the job queue to avoid simultaneous deletion operations would add overhead.
2772 // Number of archived revisions cannot be known beforehand, because edits can be made
2773 // while deletion operations are being processed, changing the number of archivals.
2774 $archivedRevisionCount = (int)$dbw->selectField(
2775 'archive', 'COUNT(*)',
2777 'ar_namespace' => $this->getTitle()->getNamespace(),
2778 'ar_title' => $this->getTitle()->getDBkey(),
2783 // Clone the title and wikiPage, so we have the information we need when
2784 // we log and run the ArticleDeleteComplete hook.
2785 $logTitle = clone $this->mTitle
;
2786 $wikiPageBeforeDelete = clone $this;
2788 // Now that it's safely backed up, delete it
2789 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2791 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2792 $logtype = $suppress ?
'suppress' : 'delete';
2794 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2795 $logEntry->setPerformer( $deleter );
2796 $logEntry->setTarget( $logTitle );
2797 $logEntry->setComment( $reason );
2798 $logEntry->addTags( $tags );
2799 $logid = $logEntry->insert();
2801 $dbw->onTransactionPreCommitOrIdle(
2802 function () use ( $logEntry, $logid ) {
2803 // T58776: avoid deadlocks (especially from FileDeleteForm)
2804 $logEntry->publish( $logid );
2809 $dbw->endAtomic( __METHOD__
);
2811 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2813 Hooks
::run( 'ArticleDeleteComplete', [
2814 &$wikiPageBeforeDelete,
2820 $archivedRevisionCount
2822 $status->value
= $logid;
2824 // Show log excerpt on 404 pages rather than just a link
2825 $dbCache = ObjectCache
::getInstance( 'db-replicated' );
2826 $key = $dbCache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2827 $dbCache->set( $key, 1, $dbCache::TTL_DAY
);
2834 * Archives revisions as part of page deletion.
2836 * @param IDatabase $dbw
2838 * @param bool $suppress Suppress all revisions and log the deletion in
2839 * the suppression log instead of the deletion log
2842 protected function archiveRevisions( $dbw, $id, $suppress ) {
2843 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2844 $wgActorTableSchemaMigrationStage, $wgDeleteRevisionsBatchSize;
2846 // Given the lock above, we can be confident in the title and page ID values
2847 $namespace = $this->getTitle()->getNamespace();
2848 $dbKey = $this->getTitle()->getDBkey();
2850 $commentStore = CommentStore
::getStore();
2851 $actorMigration = ActorMigration
::newMigration();
2853 $revQuery = Revision
::getQueryInfo();
2856 // Bitfields to further suppress the content
2858 $bitfield = RevisionRecord
::SUPPRESSED_ALL
;
2859 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2862 // For now, shunt the revision data into the archive table.
2863 // Text is *not* removed from the text table; bulk storage
2864 // is left intact to avoid breaking block-compression or
2865 // immutable storage schemes.
2866 // In the future, we may keep revisions and mark them with
2867 // the rev_deleted field, which is reserved for this purpose.
2869 // Lock rows in `revision` and its temp tables, but not any others.
2870 // Note array_intersect() preserves keys from the first arg, and we're
2871 // assuming $revQuery has `revision` primary and isn't using subtables
2872 // for anything we care about.
2873 $dbw->lockForUpdate(
2875 $revQuery['tables'],
2876 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2878 [ 'rev_page' => $id ],
2884 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2885 // so we can copy it to the archive table.
2886 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2887 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2888 $revQuery['fields'][] = 'rev_text_id';
2890 if ( $wgContentHandlerUseDB ) {
2891 $revQuery['fields'][] = 'rev_content_model';
2892 $revQuery['fields'][] = 'rev_content_format';
2896 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2897 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2898 $res = $dbw->select(
2899 $revQuery['tables'],
2900 $revQuery['fields'],
2901 [ 'rev_page' => $id ],
2903 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize +
1 ],
2907 // Build their equivalent archive rows
2911 /** @var int[] Revision IDs of edits that were made by IPs */
2915 foreach ( $res as $row ) {
2916 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2921 $comment = $commentStore->getComment( 'rev_comment', $row );
2922 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2924 'ar_namespace' => $namespace,
2925 'ar_title' => $dbKey,
2926 'ar_timestamp' => $row->rev_timestamp
,
2927 'ar_minor_edit' => $row->rev_minor_edit
,
2928 'ar_rev_id' => $row->rev_id
,
2929 'ar_parent_id' => $row->rev_parent_id
,
2931 * ar_text_id should probably not be written to when the multi content schema has
2932 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2933 * default for the field in WMF production currently so we must keep writing
2934 * writing until a default of 0 is set.
2935 * Task: https://phabricator.wikimedia.org/T190148
2936 * Copying the value from the revision table should not lead to any issues for now.
2938 'ar_len' => $row->rev_len
,
2939 'ar_page_id' => $id,
2940 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2941 'ar_sha1' => $row->rev_sha1
,
2942 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2943 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2945 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2946 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2948 if ( $wgContentHandlerUseDB ) {
2949 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2950 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2954 $rowsInsert[] = $rowInsert;
2955 $revids[] = $row->rev_id
;
2957 // Keep track of IP edits, so that the corresponding rows can
2958 // be deleted in the ip_changes table.
2959 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2960 $ipRevIds[] = $row->rev_id
;
2964 // This conditional is just a sanity check
2965 if ( count( $revids ) > 0 ) {
2966 // Copy them into the archive table
2967 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2969 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__
);
2970 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2971 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2972 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2975 // Also delete records from ip_changes as applicable.
2976 if ( count( $ipRevIds ) > 0 ) {
2977 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2985 * Lock the page row for this title+id and return page_latest (or 0)
2987 * @return int Returns 0 if no row was found with this title+id
2990 public function lockAndGetLatest() {
2991 return (int)wfGetDB( DB_MASTER
)->selectField(
2995 'page_id' => $this->getId(),
2996 // Typically page_id is enough, but some code might try to do
2997 // updates assuming the title is the same, so verify that
2998 'page_namespace' => $this->getTitle()->getNamespace(),
2999 'page_title' => $this->getTitle()->getDBkey()
3007 * Do some database updates after deletion
3009 * @param int $id The page_id value of the page being deleted
3010 * @param Content|null $content Page content to be used when determining
3011 * the required updates. This may be needed because $this->getContent()
3012 * may already return null when the page proper was deleted.
3013 * @param Revision|null $revision The current page revision at the time of
3014 * deletion, used when determining the required updates. This may be needed because
3015 * $this->getRevision() may already return null when the page proper was deleted.
3016 * @param User|null $user The user that caused the deletion
3018 public function doDeleteUpdates(
3019 $id, Content
$content = null, Revision
$revision = null, User
$user = null
3021 if ( $id !== $this->getId() ) {
3022 throw new InvalidArgumentException( 'Mismatching page ID' );
3026 $countable = $this->isCountable();
3027 } catch ( Exception
$ex ) {
3028 // fallback for deleting broken pages for which we cannot load the content for
3029 // some reason. Note that doDeleteArticleReal() already logged this problem.
3033 // Update site status
3034 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
3035 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
3038 // Delete pagelinks, update secondary indexes, etc
3039 $updates = $this->getDeletionUpdates(
3040 $revision ?
$revision->getRevisionRecord() : $content
3042 foreach ( $updates as $update ) {
3043 DeferredUpdates
::addUpdate( $update );
3046 $causeAgent = $user ?
$user->getName() : 'unknown';
3047 // Reparse any pages transcluding this page
3048 LinksUpdate
::queueRecursiveJobsForTable(
3049 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3050 // Reparse any pages including this image
3051 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3052 LinksUpdate
::queueRecursiveJobsForTable(
3053 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3057 self
::onArticleDelete( $this->mTitle
);
3058 ResourceLoaderWikiModule
::invalidateModuleCache(
3062 WikiMap
::getCurrentWikiDbDomain()->getId()
3065 // Reset this object and the Title object
3066 $this->loadFromRow( false, self
::READ_LATEST
);
3069 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3073 * Roll back the most recent consecutive set of edits to a page
3074 * from the same user; fails if there are no eligible edits to
3075 * roll back to, e.g. user is the sole contributor. This function
3076 * performs permissions checks on $user, then calls commitRollback()
3077 * to do the dirty work
3079 * @todo Separate the business/permission stuff out from backend code
3080 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3082 * @param string $fromP Name of the user whose edits to rollback.
3083 * @param string $summary Custom summary. Set to default summary if empty.
3084 * @param string $token Rollback token.
3085 * @param bool $bot If true, mark all reverted edits as bot.
3087 * @param array &$resultDetails Array contains result-specific array of additional values
3088 * 'alreadyrolled' : 'current' (rev)
3089 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3091 * @param User $user The user performing the rollback
3092 * @param array|null $tags Change tags to apply to the rollback
3093 * Callers are responsible for permission checks
3094 * (with ChangeTags::canAddTagsAccompanyingChange)
3096 * @return array Array of errors, each error formatted as
3097 * [ messagekey, param1, param2, ... ].
3098 * On success, the array is empty. This array can also be passed to
3099 * OutputPage::showPermissionsErrorPage().
3101 public function doRollback(
3102 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3104 $resultDetails = null;
3106 // Check permissions
3107 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3108 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3109 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3111 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3112 $errors[] = [ 'sessionfailure' ];
3115 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3116 $errors[] = [ 'actionthrottledtext' ];
3119 // If there were errors, bail out now
3120 if ( !empty( $errors ) ) {
3124 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3128 * Backend implementation of doRollback(), please refer there for parameter
3129 * and return value documentation
3131 * NOTE: This function does NOT check ANY permissions, it just commits the
3132 * rollback to the DB. Therefore, you should only call this function direct-
3133 * ly if you want to use custom permissions checks. If you don't, use
3134 * doRollback() instead.
3135 * @param string $fromP Name of the user whose edits to rollback.
3136 * @param string $summary Custom summary. Set to default summary if empty.
3137 * @param bool $bot If true, mark all reverted edits as bot.
3139 * @param array &$resultDetails Contains result-specific array of additional values
3140 * @param User $guser The user performing the rollback
3141 * @param array|null $tags Change tags to apply to the rollback
3142 * Callers are responsible for permission checks
3143 * (with ChangeTags::canAddTagsAccompanyingChange)
3145 * @return array An array of error messages, as returned by Status::getErrorsArray()
3147 public function commitRollback( $fromP, $summary, $bot,
3148 &$resultDetails, User
$guser, $tags = null
3150 global $wgUseRCPatrol, $wgDisableAnonTalk;
3152 $dbw = wfGetDB( DB_MASTER
);
3154 if ( wfReadOnly() ) {
3155 return [ [ 'readonlytext' ] ];
3158 // Begin revision creation cycle by creating a PageUpdater.
3159 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3160 $updater = $this->newPageUpdater( $guser );
3161 $current = $updater->grabParentRevision();
3163 if ( is_null( $current ) ) {
3164 // Something wrong... no page?
3165 return [ [ 'notanarticle' ] ];
3168 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
3169 $legacyCurrent = new Revision( $current );
3170 $from = str_replace( '_', ' ', $fromP );
3172 // User name given should match up with the top revision.
3173 // If the revision's user is not visible, then $from should be empty.
3174 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
3175 $resultDetails = [ 'current' => $legacyCurrent ];
3176 return [ [ 'alreadyrolled',
3177 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3178 htmlspecialchars( $fromP ),
3179 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3183 // Get the last edit not by this person...
3184 // Note: these may not be public values
3185 $actorWhere = ActorMigration
::newMigration()->getWhere(
3188 $current->getUser( RevisionRecord
::RAW
)
3191 $s = $dbw->selectRow(
3192 [ 'revision' ] +
$actorWhere['tables'],
3193 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3195 'rev_page' => $current->getPageId(),
3196 'NOT(' . $actorWhere['conds'] . ')',
3200 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3201 'ORDER BY' => 'rev_timestamp DESC'
3203 $actorWhere['joins']
3205 if ( $s === false ) {
3206 // No one else ever edited this page
3207 return [ [ 'cantrollback' ] ];
3208 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3209 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3211 // Only admins can see this text
3212 return [ [ 'notvisiblerev' ] ];
3215 // Generate the edit summary if necessary
3216 $target = $this->getRevisionStore()->getRevisionById(
3218 RevisionStore
::READ_LATEST
3220 if ( empty( $summary ) ) {
3221 if ( !$currentEditorForPublic ) { // no public user name
3222 $summary = wfMessage( 'revertpage-nouser' );
3223 } elseif ( $wgDisableAnonTalk && $current->getUser() === 0 ) {
3224 $summary = wfMessage( 'revertpage-anon' );
3226 $summary = wfMessage( 'revertpage' );
3229 $legacyTarget = new Revision( $target );
3230 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3232 // Allow the custom summary to use the same args as the default message
3233 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3235 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3236 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3238 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3240 $contLang->timeanddate( $current->getTimestamp() )
3242 if ( $summary instanceof Message
) {
3243 $summary = $summary->params( $args )->inContentLanguage()->text();
3245 $summary = wfMsgReplaceArgs( $summary, $args );
3248 // Trim spaces on user supplied text
3249 $summary = trim( $summary );
3252 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3254 if ( $guser->isAllowed( 'minoredit' ) ) {
3255 $flags |
= EDIT_MINOR
;
3258 if ( $bot && ( MediaWikiServices
::getInstance()
3259 ->getPermissionManager()
3260 ->userHasAnyRight( $guser, 'markbotedits', 'bot' ) )
3262 $flags |
= EDIT_FORCE_BOT
;
3265 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3266 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3267 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3268 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3270 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3271 $tags[] = 'mw-rollback';
3274 // Build rollback revision:
3275 // Restore old content
3276 // TODO: MCR: test this once we can store multiple slots
3277 foreach ( $target->getSlots()->getSlots() as $slot ) {
3278 $updater->inheritSlot( $slot );
3281 // Remove extra slots
3282 // TODO: MCR: test this once we can store multiple slots
3283 foreach ( $current->getSlotRoles() as $role ) {
3284 if ( !$target->hasSlot( $role ) ) {
3285 $updater->removeSlot( $role );
3289 $updater->setOriginalRevisionId( $target->getId() );
3290 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3291 $updater->addTags( $tags );
3293 // TODO: this logic should not be in the storage layer, it's here for compatibility
3294 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3295 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3296 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
3298 if ( $wgUseRCPatrol && $permissionManager->userCan(
3299 'autopatrol', $guser, $this->getTitle()
3301 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3304 // Actually store the rollback
3305 $rev = $updater->saveRevision(
3306 CommentStoreComment
::newUnsavedComment( $summary ),
3310 // Set patrolling and bot flag on the edits, which gets rollbacked.
3311 // This is done even on edit failure to have patrolling in that case (T64157).
3313 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3314 // Mark all reverted edits as bot
3318 if ( $wgUseRCPatrol ) {
3319 // Mark all reverted edits as patrolled
3320 $set['rc_patrolled'] = RecentChange
::PRC_AUTOPATROLLED
;
3323 if ( count( $set ) ) {
3324 $actorWhere = ActorMigration
::newMigration()->getWhere(
3327 $current->getUser( RevisionRecord
::RAW
),
3330 $dbw->update( 'recentchanges', $set,
3332 'rc_cur_id' => $current->getPageId(),
3333 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3334 $actorWhere['conds'], // No tables/joins are needed for rc_user
3340 if ( !$updater->wasSuccessful() ) {
3341 return $updater->getStatus()->getErrorsArray();
3344 // Report if the edit was not created because it did not change the content.
3345 if ( $updater->isUnchanged() ) {
3346 $resultDetails = [ 'current' => $legacyCurrent ];
3347 return [ [ 'alreadyrolled',
3348 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3349 htmlspecialchars( $fromP ),
3350 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3354 if ( $changingContentModel ) {
3355 // If the content model changed during the rollback,
3356 // make sure it gets logged to Special:Log/contentmodel
3357 $log = new ManualLogEntry( 'contentmodel', 'change' );
3358 $log->setPerformer( $guser );
3359 $log->setTarget( $this->mTitle
);
3360 $log->setComment( $summary );
3361 $log->setParameters( [
3362 '4::oldmodel' => $currentContent->getModel(),
3363 '5::newmodel' => $targetContent->getModel(),
3366 $logId = $log->insert( $dbw );
3367 $log->publish( $logId );
3370 $revId = $rev->getId();
3372 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3375 'summary' => $summary,
3376 'current' => $legacyCurrent,
3377 'target' => $legacyTarget,
3382 // TODO: make this return a Status object and wrap $resultDetails in that.
3387 * The onArticle*() functions are supposed to be a kind of hooks
3388 * which should be called whenever any of the specified actions
3391 * This is a good place to put code to clear caches, for instance.
3393 * This is called on page move and undelete, as well as edit
3395 * @param Title $title
3397 public static function onArticleCreate( Title
$title ) {
3398 // TODO: move this into a PageEventEmitter service
3400 // Update existence markers on article/talk tabs...
3401 $other = $title->getOtherPage();
3403 $other->purgeSquid();
3405 $title->touchLinks();
3406 $title->purgeSquid();
3407 $title->deleteTitleProtection();
3409 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3411 // Invalidate caches of articles which include this page
3412 DeferredUpdates
::addUpdate(
3413 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3416 if ( $title->getNamespace() == NS_CATEGORY
) {
3417 // Load the Category object, which will schedule a job to create
3418 // the category table row if necessary. Checking a replica DB is ok
3419 // here, in the worst case it'll run an unnecessary recount job on
3420 // a category that probably doesn't have many members.
3421 Category
::newFromTitle( $title )->getID();
3426 * Clears caches when article is deleted
3428 * @param Title $title
3430 public static function onArticleDelete( Title
$title ) {
3431 // TODO: move this into a PageEventEmitter service
3433 // Update existence markers on article/talk tabs...
3434 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3435 BacklinkCache
::get( $title )->clear();
3436 $other = $title->getOtherPage();
3438 $other->purgeSquid();
3440 $title->touchLinks();
3441 $title->purgeSquid();
3443 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3446 HTMLFileCache
::clearFileCache( $title );
3447 InfoAction
::invalidateCache( $title );
3450 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3451 MessageCache
::singleton()->updateMessageOverride( $title, null );
3455 if ( $title->getNamespace() == NS_FILE
) {
3456 DeferredUpdates
::addUpdate(
3457 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3462 if ( $title->getNamespace() == NS_USER_TALK
) {
3463 $user = User
::newFromName( $title->getText(), false );
3465 $user->setNewtalk( false );
3470 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3472 // Purge cross-wiki cache entities referencing this page
3473 self
::purgeInterwikiCheckKey( $title );
3477 * Purge caches on page update etc
3479 * @param Title $title
3480 * @param Revision|null $revision Revision that was just saved, may be null
3481 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3482 * If not given, all slots are assumed to have changed.
3484 public static function onArticleEdit(
3486 Revision
$revision = null,
3487 $slotsChanged = null
3489 // TODO: move this into a PageEventEmitter service
3491 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3492 // Invalidate caches of articles which include this page.
3493 // Only for the main slot, because only the main slot is transcluded.
3494 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3495 DeferredUpdates
::addUpdate(
3496 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3500 // Invalidate the caches of all pages which redirect here
3501 DeferredUpdates
::addUpdate(
3502 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3505 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3507 // Purge CDN for this page only
3508 $title->purgeSquid();
3509 // Clear file cache for this page only
3510 HTMLFileCache
::clearFileCache( $title );
3512 // Purge ?action=info cache
3513 $revid = $revision ?
$revision->getId() : null;
3514 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3515 InfoAction
::invalidateCache( $title, $revid );
3518 // Purge cross-wiki cache entities referencing this page
3519 self
::purgeInterwikiCheckKey( $title );
3525 * Purge the check key for cross-wiki cache entries referencing this page
3527 * @param Title $title
3529 private static function purgeInterwikiCheckKey( Title
$title ) {
3530 global $wgEnableScaryTranscluding;
3532 if ( !$wgEnableScaryTranscluding ) {
3533 return; // @todo: perhaps this wiki is only used as a *source* for content?
3536 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3537 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3538 $cache->resetCheckKey(
3539 // Do not include the namespace since there can be multiple aliases to it
3540 // due to different namespace text definitions on different wikis. This only
3541 // means that some cache invalidations happen that are not strictly needed.
3542 $cache->makeGlobalKey(
3544 WikiMap
::getCurrentWikiDbDomain()->getId(),
3552 * Returns a list of categories this page is a member of.
3553 * Results will include hidden categories
3555 * @return TitleArray
3557 public function getCategories() {
3558 $id = $this->getId();
3560 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3563 $dbr = wfGetDB( DB_REPLICA
);
3564 $res = $dbr->select( 'categorylinks',
3565 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3566 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3567 // as not being aliases, and NS_CATEGORY is numeric
3568 [ 'cl_from' => $id ],
3571 return TitleArray
::newFromResult( $res );
3575 * Returns a list of hidden categories this page is a member of.
3576 * Uses the page_props and categorylinks tables.
3578 * @return array Array of Title objects
3580 public function getHiddenCategories() {
3582 $id = $this->getId();
3588 $dbr = wfGetDB( DB_REPLICA
);
3589 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3591 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3592 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3595 if ( $res !== false ) {
3596 foreach ( $res as $row ) {
3597 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3605 * Auto-generates a deletion reason
3607 * @param bool &$hasHistory Whether the page has a history
3608 * @return string|bool String containing deletion reason or empty string, or boolean false
3609 * if no revision occurred
3611 public function getAutoDeleteReason( &$hasHistory ) {
3612 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3616 * Update all the appropriate counts in the category table, given that
3617 * we've added the categories $added and deleted the categories $deleted.
3619 * This should only be called from deferred updates or jobs to avoid contention.
3621 * @param array $added The names of categories that were added
3622 * @param array $deleted The names of categories that were deleted
3623 * @param int $id Page ID (this should be the original deleted page ID)
3625 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3626 $id = $id ?
: $this->getId();
3627 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
3628 getCategoryLinkType( $this->getTitle()->getNamespace() );
3630 $addFields = [ 'cat_pages = cat_pages + 1' ];
3631 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3632 if ( $type !== 'page' ) {
3633 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3634 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3637 $dbw = wfGetDB( DB_MASTER
);
3639 if ( count( $added ) ) {
3640 $existingAdded = $dbw->selectFieldValues(
3643 [ 'cat_title' => $added ],
3647 // For category rows that already exist, do a plain
3648 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3649 // to avoid creating gaps in the cat_id sequence.
3650 if ( count( $existingAdded ) ) {
3654 [ 'cat_title' => $existingAdded ],
3659 $missingAdded = array_diff( $added, $existingAdded );
3660 if ( count( $missingAdded ) ) {
3662 foreach ( $missingAdded as $cat ) {
3664 'cat_title' => $cat,
3666 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3667 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3680 if ( count( $deleted ) ) {
3684 [ 'cat_title' => $deleted ],
3689 foreach ( $added as $catName ) {
3690 $cat = Category
::newFromName( $catName );
3691 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3694 foreach ( $deleted as $catName ) {
3695 $cat = Category
::newFromName( $catName );
3696 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3697 // Refresh counts on categories that should be empty now (after commit, T166757)
3698 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3699 $cat->refreshCountsIfEmpty();
3705 * Opportunistically enqueue link update jobs given fresh parser output if useful
3707 * @param ParserOutput $parserOutput Current version page output
3710 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3711 if ( wfReadOnly() ) {
3715 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3716 [ $this, $this->mTitle
, $parserOutput ]
3721 $config = RequestContext
::getMain()->getConfig();
3724 'isOpportunistic' => true,
3725 'rootJobTimestamp' => $parserOutput->getCacheTime()
3728 if ( $this->mTitle
->areRestrictionsCascading() ) {
3729 // If the page is cascade protecting, the links should really be up-to-date
3730 JobQueueGroup
::singleton()->lazyPush(
3731 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3733 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3734 // Assume the output contains "dynamic" time/random based magic words.
3735 // Only update pages that expired due to dynamic content and NOT due to edits
3736 // to referenced templates/files. When the cache expires due to dynamic content,
3737 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3738 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3739 // template/file edit already triggered recursive RefreshLinksJob jobs.
3740 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3741 // If a page is uncacheable, do not keep spamming a job for it.
3742 // Although it would be de-duplicated, it would still waste I/O.
3743 $cache = ObjectCache
::getLocalClusterInstance();
3744 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3745 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3746 if ( $cache->add( $key, time(), $ttl ) ) {
3747 JobQueueGroup
::singleton()->lazyPush(
3748 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3756 * Returns a list of updates to be performed when this page is deleted. The
3757 * updates should remove any information about this page from secondary data
3758 * stores such as links tables.
3760 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3761 * object for backwards compatibility.
3762 * @return DeferrableUpdate[]
3764 public function getDeletionUpdates( $rev = null ) {
3766 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3769 $rev = $this->getRevisionRecord();
3770 } catch ( Exception
$ex ) {
3771 // If we can't load the content, something is wrong. Perhaps that's why
3772 // the user is trying to delete the page, so let's not fail in that case.
3773 // Note that doDeleteArticleReal() will already have logged an issue with
3774 // loading the content.
3775 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3781 } elseif ( $rev instanceof Content
) {
3782 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3784 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3786 $slotContent = array_map( function ( SlotRecord
$slot ) {
3787 return $slot->getContent( RevisionRecord
::RAW
);
3788 }, $rev->getSlots()->getSlots() );
3791 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3793 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3794 // model here, not the content object!
3795 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3796 /** @var Content $content */
3797 foreach ( $slotContent as $role => $content ) {
3798 $handler = $content->getContentHandler();
3800 $updates = $handler->getDeletionUpdates(
3804 $allUpdates = array_merge( $allUpdates, $updates );
3806 // TODO: remove B/C hack in 1.32!
3807 $legacyUpdates = $content->getDeletionUpdates( $this );
3809 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3810 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3811 return !( $update instanceof LinksDeletionUpdate
);
3814 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3817 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3819 // TODO: hard deprecate old hook in 1.33
3820 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3825 * Whether this content displayed on this page
3826 * comes from the local database
3831 public function isLocal() {
3836 * The display name for the site this content
3837 * come from. If a subclass overrides isLocal(),
3838 * this could return something other than the
3844 public function getWikiDisplayName() {
3850 * Get the source URL for the content on this page,
3851 * typically the canonical URL, but may be a remote
3852 * link if the content comes from another site
3857 public function getSourceURL() {
3858 return $this->getTitle()->getCanonicalURL();
3862 * @param WANObjectCache $cache
3866 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3867 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3869 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );