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 class WikiPage
implements Page
, IDBAccessObject
{
46 // Constants for $mDataLoadedFrom and related
51 public $mTitle = null;
57 public $mDataLoaded = false;
63 public $mIsRedirect = false;
66 * @var int|false False means "not loaded"
69 public $mLatest = false;
72 * @var PreparedEdit|false Map of cache fields (text, parser output, ect) for a proposed/new edit
74 public $mPreparedEdit = false;
79 protected $mId = null;
82 * @var int One of the READ_* constants
84 protected $mDataLoadedFrom = self
::READ_NONE
;
89 protected $mRedirectTarget = null;
94 protected $mLastRevision = null;
97 * @var string Timestamp of the current revision or empty string if not loaded
99 protected $mTimestamp = '';
104 protected $mTouched = '19700101000000';
109 protected $mLinksUpdated = '19700101000000';
112 * @var DerivedPageDataUpdater|null
114 private $derivedDataUpdater = null;
117 * Constructor and clear the article
118 * @param Title $title Reference to a Title object.
120 public function __construct( Title
$title ) {
121 $this->mTitle
= $title;
125 * Makes sure that the mTitle object is cloned
126 * to the newly cloned WikiPage.
128 public function __clone() {
129 $this->mTitle
= clone $this->mTitle
;
133 * Create a WikiPage object of the appropriate class for the given title.
135 * @param Title $title
137 * @throws MWException
138 * @return WikiPage|WikiCategoryPage|WikiFilePage
140 public static function factory( Title
$title ) {
141 $ns = $title->getNamespace();
143 if ( $ns == NS_MEDIA
) {
144 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
145 } elseif ( $ns < 0 ) {
146 throw new MWException( "Invalid or virtual namespace $ns given." );
150 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
156 $page = new WikiFilePage( $title );
159 $page = new WikiCategoryPage( $title );
162 $page = new WikiPage( $title );
169 * Constructor from a page id
171 * @param int $id Article ID to load
172 * @param string|int $from One of the following values:
173 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
174 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
176 * @return WikiPage|null
178 public static function newFromID( $id, $from = 'fromdb' ) {
179 // page ids are never 0 or negative, see T63166
184 $from = self
::convertSelectType( $from );
185 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
186 $pageQuery = self
::getQueryInfo();
187 $row = $db->selectRow(
188 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
189 [], $pageQuery['joins']
194 return self
::newFromRow( $row, $from );
198 * Constructor from a database row
201 * @param object $row Database row containing at least fields returned by selectFields().
202 * @param string|int $from Source of $data:
203 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
204 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
205 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
208 public static function newFromRow( $row, $from = 'fromdb' ) {
209 $page = self
::factory( Title
::newFromRow( $row ) );
210 $page->loadFromRow( $row, $from );
215 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
217 * @param object|string|int $type
220 protected static function convertSelectType( $type ) {
223 return self
::READ_NORMAL
;
225 return self
::READ_LATEST
;
227 return self
::READ_LOCKING
;
229 // It may already be an integer or whatever else
235 * @return RevisionStore
237 private function getRevisionStore() {
238 return MediaWikiServices
::getInstance()->getRevisionStore();
242 * @return RevisionRenderer
244 private function getRevisionRenderer() {
245 return MediaWikiServices
::getInstance()->getRevisionRenderer();
249 * @return SlotRoleRegistry
251 private function getSlotRoleRegistry() {
252 return MediaWikiServices
::getInstance()->getSlotRoleRegistry();
256 * @return ParserCache
258 private function getParserCache() {
259 return MediaWikiServices
::getInstance()->getParserCache();
263 * @return LoadBalancer
265 private function getDBLoadBalancer() {
266 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
270 * @todo Move this UI stuff somewhere else
272 * @see ContentHandler::getActionOverrides
275 public function getActionOverrides() {
276 return $this->getContentHandler()->getActionOverrides();
280 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
282 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
284 * @return ContentHandler
288 public function getContentHandler() {
289 return ContentHandler
::getForModelID( $this->getContentModel() );
293 * Get the title object of the article
294 * @return Title Title object of this page
296 public function getTitle() {
297 return $this->mTitle
;
304 public function clear() {
305 $this->mDataLoaded
= false;
306 $this->mDataLoadedFrom
= self
::READ_NONE
;
308 $this->clearCacheFields();
312 * Clear the object cache fields
315 protected function clearCacheFields() {
317 $this->mRedirectTarget
= null; // Title object if set
318 $this->mLastRevision
= null; // Latest revision
319 $this->mTouched
= '19700101000000';
320 $this->mLinksUpdated
= '19700101000000';
321 $this->mTimestamp
= '';
322 $this->mIsRedirect
= false;
323 $this->mLatest
= false;
324 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
325 // checks the requested rev ID and content against the cached one. For most
326 // content types, the output should not change during the lifetime of this cache.
327 // Clearing it can cause extra parses on edit for no reason.
331 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
335 public function clearPreparedEdit() {
336 $this->mPreparedEdit
= false;
340 * Return the list of revision fields that should be selected to create
343 * @deprecated since 1.31, use self::getQueryInfo() instead.
346 public static function selectFields() {
347 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
349 wfDeprecated( __METHOD__
, '1.31' );
360 'page_links_updated',
365 if ( $wgContentHandlerUseDB ) {
366 $fields[] = 'page_content_model';
369 if ( $wgPageLanguageUseDB ) {
370 $fields[] = 'page_lang';
377 * Return the tables, fields, and join conditions to be selected to create
380 * @return array With three keys:
381 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
382 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
383 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
385 public static function getQueryInfo() {
386 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
389 'tables' => [ 'page' ],
399 'page_links_updated',
406 if ( $wgContentHandlerUseDB ) {
407 $ret['fields'][] = 'page_content_model';
410 if ( $wgPageLanguageUseDB ) {
411 $ret['fields'][] = 'page_lang';
418 * Fetch a page record with the given conditions
419 * @param IDatabase $dbr
420 * @param array $conditions
421 * @param array $options
422 * @return object|bool Database result resource, or false on failure
424 protected function pageData( $dbr, $conditions, $options = [] ) {
425 $pageQuery = self
::getQueryInfo();
427 // Avoid PHP 7.1 warning of passing $this by reference
430 Hooks
::run( 'ArticlePageDataBefore', [
431 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
434 $row = $dbr->selectRow(
435 $pageQuery['tables'],
436 $pageQuery['fields'],
443 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
449 * Fetch a page record matching the Title object's namespace and title
450 * using a sanitized title string
452 * @param IDatabase $dbr
453 * @param Title $title
454 * @param array $options
455 * @return object|bool Database result resource, or false on failure
457 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
458 return $this->pageData( $dbr, [
459 'page_namespace' => $title->getNamespace(),
460 'page_title' => $title->getDBkey() ], $options );
464 * Fetch a page record matching the requested ID
466 * @param IDatabase $dbr
468 * @param array $options
469 * @return object|bool Database result resource, or false on failure
471 public function pageDataFromId( $dbr, $id, $options = [] ) {
472 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
476 * Load the object from a given source by title
478 * @param object|string|int $from One of the following:
479 * - A DB query result object.
480 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
481 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
482 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
483 * using SELECT FOR UPDATE.
487 public function loadPageData( $from = 'fromdb' ) {
488 $from = self
::convertSelectType( $from );
489 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
490 // We already have the data from the correct location, no need to load it twice.
494 if ( is_int( $from ) ) {
495 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
496 $loadBalancer = $this->getDBLoadBalancer();
497 $db = $loadBalancer->getConnection( $index );
498 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
501 && $index == DB_REPLICA
502 && $loadBalancer->getServerCount() > 1
503 && $loadBalancer->hasOrMadeRecentMasterChanges()
505 $from = self
::READ_LATEST
;
506 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
507 $db = $loadBalancer->getConnection( $index );
508 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
511 // No idea from where the caller got this data, assume replica DB.
513 $from = self
::READ_NORMAL
;
516 $this->loadFromRow( $data, $from );
520 * Checks whether the page data was loaded using the given database access mode (or better).
524 * @param string|int $from One of the following:
525 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
526 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
527 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
528 * using SELECT FOR UPDATE.
532 public function wasLoadedFrom( $from ) {
533 $from = self
::convertSelectType( $from );
535 if ( !is_int( $from ) ) {
536 // No idea from where the caller got this data, assume replica DB.
537 $from = self
::READ_NORMAL
;
540 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
548 * Load the object from a database row
551 * @param object|bool $data DB row containing fields returned by selectFields() or false
552 * @param string|int $from One of the following:
553 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
554 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
555 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
556 * the master DB using SELECT FOR UPDATE
558 public function loadFromRow( $data, $from ) {
559 $lc = MediaWikiServices
::getInstance()->getLinkCache();
560 $lc->clearLink( $this->mTitle
);
563 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
565 $this->mTitle
->loadFromRow( $data );
567 // Old-fashioned restrictions
568 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
570 $this->mId
= intval( $data->page_id
);
571 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
572 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
573 $this->mIsRedirect
= intval( $data->page_is_redirect
);
574 $this->mLatest
= intval( $data->page_latest
);
575 // T39225: $latest may no longer match the cached latest Revision object.
576 // Double-check the ID of any cached latest Revision object for consistency.
577 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
578 $this->mLastRevision
= null;
579 $this->mTimestamp
= '';
582 $lc->addBadLinkObj( $this->mTitle
);
584 $this->mTitle
->loadFromRow( false );
586 $this->clearCacheFields();
591 $this->mDataLoaded
= true;
592 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
596 * @return int Page ID
598 public function getId() {
599 if ( !$this->mDataLoaded
) {
600 $this->loadPageData();
606 * @return bool Whether or not the page exists in the database
608 public function exists() {
609 if ( !$this->mDataLoaded
) {
610 $this->loadPageData();
612 return $this->mId
> 0;
616 * Check if this page is something we're going to be showing
617 * some sort of sensible content for. If we return false, page
618 * views (plain action=view) will return an HTTP 404 response,
619 * so spiders and robots can know they're following a bad link.
623 public function hasViewableContent() {
624 return $this->mTitle
->isKnown();
628 * Tests if the article content represents a redirect
632 public function isRedirect() {
633 if ( !$this->mDataLoaded
) {
634 $this->loadPageData();
637 return (bool)$this->mIsRedirect
;
641 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
643 * Will use the revisions actual content model if the page exists,
644 * and the page's default if the page doesn't exist yet.
650 public function getContentModel() {
651 if ( $this->exists() ) {
652 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
654 return $cache->getWithSetCallback(
655 $cache->makeKey( 'page-content-model', $this->getLatest() ),
658 $rev = $this->getRevision();
660 // Look at the revision's actual content model
661 return $rev->getContentModel();
663 $title = $this->mTitle
->getPrefixedDBkey();
664 wfWarn( "Page $title exists but has no (visible) revisions!" );
665 return $this->mTitle
->getContentModel();
671 // use the default model for this page
672 return $this->mTitle
->getContentModel();
676 * Loads page_touched and returns a value indicating if it should be used
677 * @return bool True if this page exists and is not a redirect
679 public function checkTouched() {
680 if ( !$this->mDataLoaded
) {
681 $this->loadPageData();
683 return ( $this->mId
&& !$this->mIsRedirect
);
687 * Get the page_touched field
688 * @return string Containing GMT timestamp
690 public function getTouched() {
691 if ( !$this->mDataLoaded
) {
692 $this->loadPageData();
694 return $this->mTouched
;
698 * Get the page_links_updated field
699 * @return string|null Containing GMT timestamp
701 public function getLinksTimestamp() {
702 if ( !$this->mDataLoaded
) {
703 $this->loadPageData();
705 return $this->mLinksUpdated
;
709 * Get the page_latest field
710 * @return int The rev_id of current revision
712 public function getLatest() {
713 if ( !$this->mDataLoaded
) {
714 $this->loadPageData();
716 return (int)$this->mLatest
;
720 * Get the Revision object of the oldest revision
721 * @return Revision|null
723 public function getOldestRevision() {
724 // Try using the replica DB first, then try the master
725 $rev = $this->mTitle
->getFirstRevision();
727 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
733 * Loads everything except the text
734 * This isn't necessary for all uses, so it's only done if needed.
736 protected function loadLastEdit() {
737 if ( $this->mLastRevision
!== null ) {
738 return; // already loaded
741 $latest = $this->getLatest();
743 return; // page doesn't exist or is missing page_latest info
746 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
747 // T39225: if session S1 loads the page row FOR UPDATE, the result always
748 // includes the latest changes committed. This is true even within REPEATABLE-READ
749 // transactions, where S1 normally only sees changes committed before the first S1
750 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
751 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
752 // happened after the first S1 SELECT.
753 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
754 $flags = Revision
::READ_LOCKING
;
755 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
756 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
757 // Bug T93976: if page_latest was loaded from the master, fetch the
758 // revision from there as well, as it may not exist yet on a replica DB.
759 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
760 $flags = Revision
::READ_LATEST
;
761 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
763 $dbr = wfGetDB( DB_REPLICA
);
764 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
767 if ( $revision ) { // sanity
768 $this->setLastEdit( $revision );
773 * Set the latest revision
774 * @param Revision $revision
776 protected function setLastEdit( Revision
$revision ) {
777 $this->mLastRevision
= $revision;
778 $this->mTimestamp
= $revision->getTimestamp();
782 * Get the latest revision
783 * @return Revision|null
785 public function getRevision() {
786 $this->loadLastEdit();
787 if ( $this->mLastRevision
) {
788 return $this->mLastRevision
;
794 * Get the latest revision
795 * @return RevisionRecord|null
797 public function getRevisionRecord() {
798 $this->loadLastEdit();
799 if ( $this->mLastRevision
) {
800 return $this->mLastRevision
->getRevisionRecord();
806 * Get the content of the current revision. No side-effects...
808 * @param int $audience One of:
809 * Revision::FOR_PUBLIC to be displayed to all users
810 * Revision::FOR_THIS_USER to be displayed to $wgUser
811 * Revision::RAW get the text regardless of permissions
812 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
813 * to the $audience parameter
814 * @return Content|null The content of the current revision
818 public function getContent( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
819 $this->loadLastEdit();
820 if ( $this->mLastRevision
) {
821 return $this->mLastRevision
->getContent( $audience, $user );
827 * @return string MW timestamp of last article revision
829 public function getTimestamp() {
830 // Check if the field has been filled by WikiPage::setTimestamp()
831 if ( !$this->mTimestamp
) {
832 $this->loadLastEdit();
835 return wfTimestamp( TS_MW
, $this->mTimestamp
);
839 * Set the page timestamp (use only to avoid DB queries)
840 * @param string $ts MW timestamp of last article revision
843 public function setTimestamp( $ts ) {
844 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
848 * @param int $audience One of:
849 * Revision::FOR_PUBLIC to be displayed to all users
850 * Revision::FOR_THIS_USER to be displayed to the given user
851 * Revision::RAW get the text regardless of permissions
852 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
853 * to the $audience parameter
854 * @return int User ID for the user that made the last article revision
856 public function getUser( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
857 $this->loadLastEdit();
858 if ( $this->mLastRevision
) {
859 return $this->mLastRevision
->getUser( $audience, $user );
866 * Get the User object of the user who created the page
867 * @param int $audience One of:
868 * Revision::FOR_PUBLIC to be displayed to all users
869 * Revision::FOR_THIS_USER to be displayed to the given user
870 * Revision::RAW get the text regardless of permissions
871 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
872 * to the $audience parameter
875 public function getCreator( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
876 $revision = $this->getOldestRevision();
878 $userName = $revision->getUserText( $audience, $user );
879 return User
::newFromName( $userName, false );
886 * @param int $audience One of:
887 * Revision::FOR_PUBLIC to be displayed to all users
888 * Revision::FOR_THIS_USER to be displayed to the given user
889 * Revision::RAW get the text regardless of permissions
890 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
891 * to the $audience parameter
892 * @return string Username of the user that made the last article revision
894 public function getUserText( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
895 $this->loadLastEdit();
896 if ( $this->mLastRevision
) {
897 return $this->mLastRevision
->getUserText( $audience, $user );
904 * @param int $audience One of:
905 * Revision::FOR_PUBLIC to be displayed to all users
906 * Revision::FOR_THIS_USER to be displayed to the given user
907 * Revision::RAW get the text regardless of permissions
908 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
909 * to the $audience parameter
910 * @return string|null Comment stored for the last article revision, or null if the specified
911 * audience does not have access to the comment.
913 public function getComment( $audience = RevisionRecord
::FOR_PUBLIC
, User
$user = null ) {
914 $this->loadLastEdit();
915 if ( $this->mLastRevision
) {
916 return $this->mLastRevision
->getComment( $audience, $user );
923 * Returns true if last revision was marked as "minor edit"
925 * @return bool Minor edit indicator for the last article revision.
927 public function getMinorEdit() {
928 $this->loadLastEdit();
929 if ( $this->mLastRevision
) {
930 return $this->mLastRevision
->isMinor();
937 * Determine whether a page would be suitable for being counted as an
938 * article in the site_stats table based on the title & its content
940 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
941 * if false, the current database state will be used
944 public function isCountable( $editInfo = false ) {
945 global $wgArticleCountMethod;
947 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
949 if ( !$this->mTitle
->isContentPage() ) {
954 // NOTE: only the main slot can make a page a redirect
955 $content = $editInfo->pstContent
;
957 $content = $this->getContent();
960 if ( !$content ||
$content->isRedirect() ) {
966 if ( $wgArticleCountMethod === 'link' ) {
967 // nasty special case to avoid re-parsing to detect links
970 // ParserOutput::getLinks() is a 2D array of page links, so
971 // to be really correct we would need to recurse in the array
972 // but the main array should only have items in it if there are
974 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
976 // NOTE: keep in sync with RevisionRenderer::getLinkCount
977 // NOTE: keep in sync with DerivedPageDataUpdater::isCountable
978 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
979 [ 'pl_from' => $this->getId() ], __METHOD__
);
983 // TODO: MCR: determine $hasLinks for each slot, and use that info
984 // with that slot's Content's isCountable method. That requires per-
985 // slot ParserOutput in the ParserCache, or per-slot info in the
987 return $content->isCountable( $hasLinks );
991 * If this page is a redirect, get its target
993 * The target will be fetched from the redirect table if possible.
994 * If this page doesn't have an entry there, call insertRedirect()
995 * @return Title|null Title object, or null if this page is not a redirect
997 public function getRedirectTarget() {
998 if ( !$this->mTitle
->isRedirect() ) {
1002 if ( $this->mRedirectTarget
!== null ) {
1003 return $this->mRedirectTarget
;
1006 // Query the redirect table
1007 $dbr = wfGetDB( DB_REPLICA
);
1008 $row = $dbr->selectRow( 'redirect',
1009 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1010 [ 'rd_from' => $this->getId() ],
1014 // rd_fragment and rd_interwiki were added later, populate them if empty
1015 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
1016 // (T203942) We can't redirect to Media namespace because it's virtual.
1017 // We don't want to modify Title objects farther down the
1018 // line. So, let's fix this here by changing to File namespace.
1019 if ( $row->rd_namespace
== NS_MEDIA
) {
1020 $namespace = NS_FILE
;
1022 $namespace = $row->rd_namespace
;
1024 $this->mRedirectTarget
= Title
::makeTitle(
1025 $namespace, $row->rd_title
,
1026 $row->rd_fragment
, $row->rd_interwiki
1028 return $this->mRedirectTarget
;
1031 // This page doesn't have an entry in the redirect table
1032 $this->mRedirectTarget
= $this->insertRedirect();
1033 return $this->mRedirectTarget
;
1037 * Insert an entry for this page into the redirect table if the content is a redirect
1039 * The database update will be deferred via DeferredUpdates
1041 * Don't call this function directly unless you know what you're doing.
1042 * @return Title|null Title object or null if not a redirect
1044 public function insertRedirect() {
1045 $content = $this->getContent();
1046 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1051 // Update the DB post-send if the page has not cached since now
1052 $latest = $this->getLatest();
1053 DeferredUpdates
::addCallableUpdate(
1054 function () use ( $retval, $latest ) {
1055 $this->insertRedirectEntry( $retval, $latest );
1057 DeferredUpdates
::POSTSEND
,
1058 wfGetDB( DB_MASTER
)
1065 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1066 * @param Title $rt Redirect target
1067 * @param int|null $oldLatest Prior page_latest for check and set
1068 * @return bool Success
1070 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1071 $dbw = wfGetDB( DB_MASTER
);
1072 $dbw->startAtomic( __METHOD__
);
1074 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1075 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1076 $truncatedFragment = $contLang->truncateForDatabase( $rt->getFragment(), 255 );
1080 'rd_from' => $this->getId(),
1081 'rd_namespace' => $rt->getNamespace(),
1082 'rd_title' => $rt->getDBkey(),
1083 'rd_fragment' => $truncatedFragment,
1084 'rd_interwiki' => $rt->getInterwiki(),
1088 'rd_namespace' => $rt->getNamespace(),
1089 'rd_title' => $rt->getDBkey(),
1090 'rd_fragment' => $truncatedFragment,
1091 'rd_interwiki' => $rt->getInterwiki(),
1100 $dbw->endAtomic( __METHOD__
);
1106 * Get the Title object or URL this page redirects to
1108 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1110 public function followRedirect() {
1111 return $this->getRedirectURL( $this->getRedirectTarget() );
1115 * Get the Title object or URL to use for a redirect. We use Title
1116 * objects for same-wiki, non-special redirects and URLs for everything
1118 * @param Title $rt Redirect target
1119 * @return bool|Title|string False, Title object of local target, or string with URL
1121 public function getRedirectURL( $rt ) {
1126 if ( $rt->isExternal() ) {
1127 if ( $rt->isLocal() ) {
1128 // Offsite wikis need an HTTP redirect.
1129 // This can be hard to reverse and may produce loops,
1130 // so they may be disabled in the site configuration.
1131 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1132 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1134 // External pages without "local" bit set are not valid
1140 if ( $rt->isSpecialPage() ) {
1141 // Gotta handle redirects to special pages differently:
1142 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1143 // Some pages are not valid targets.
1144 if ( $rt->isValidRedirectTarget() ) {
1145 return $rt->getFullURL();
1155 * Get a list of users who have edited this article, not including the user who made
1156 * the most recent revision, which you can get from $article->getUser() if you want it
1157 * @return UserArrayFromResult
1159 public function getContributors() {
1160 // @todo: This is expensive; cache this info somewhere.
1162 $dbr = wfGetDB( DB_REPLICA
);
1164 $actorMigration = ActorMigration
::newMigration();
1165 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1167 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1170 'user_id' => $actorQuery['fields']['rev_user'],
1171 'user_name' => $actorQuery['fields']['rev_user_text'],
1172 'actor_id' => $actorQuery['fields']['rev_actor'],
1173 'user_real_name' => 'MIN(user_real_name)',
1174 'timestamp' => 'MAX(rev_timestamp)',
1177 $conds = [ 'rev_page' => $this->getId() ];
1179 // The user who made the top revision gets credited as "this page was last edited by
1180 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1181 $user = $this->getUser()
1182 ? User
::newFromId( $this->getUser() )
1183 : User
::newFromName( $this->getUserText(), false );
1184 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1187 $conds[] = "{$dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER )} = 0";
1190 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1191 ] +
$actorQuery['joins'];
1194 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1195 'ORDER BY' => 'timestamp DESC',
1198 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1199 return new UserArrayFromResult( $res );
1203 * Should the parser cache be used?
1205 * @param ParserOptions $parserOptions ParserOptions to check
1209 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1210 return $parserOptions->getStubThreshold() == 0
1212 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1213 && $this->getContentHandler()->isParserCacheSupported();
1217 * Get a ParserOutput for the given ParserOptions and revision ID.
1219 * The parser cache will be used if possible. Cache misses that result
1220 * in parser runs are debounced with PoolCounter.
1222 * XXX merge this with updateParserCache()?
1225 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1226 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1227 * get the current revision (default value)
1228 * @param bool $forceParse Force reindexing, regardless of cache settings
1229 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1231 public function getParserOutput(
1232 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1235 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1237 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1238 throw new InvalidArgumentException(
1239 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1243 wfDebug( __METHOD__
.
1244 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1245 if ( $parserOptions->getStubThreshold() ) {
1246 wfIncrStats( 'pcache.miss.stub' );
1249 if ( $useParserCache ) {
1250 $parserOutput = $this->getParserCache()
1251 ->get( $this, $parserOptions );
1252 if ( $parserOutput !== false ) {
1253 return $parserOutput;
1257 if ( $oldid === null ||
$oldid === 0 ) {
1258 $oldid = $this->getLatest();
1261 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1264 return $pool->getParserOutput();
1268 * Do standard deferred updates after page view (existing or missing page)
1269 * @param User $user The relevant user
1270 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1272 public function doViewUpdates( User
$user, $oldid = 0 ) {
1273 if ( wfReadOnly() ) {
1277 // Update newtalk / watchlist notification status;
1278 // Avoid outage if the master is not reachable by using a deferred updated
1279 DeferredUpdates
::addCallableUpdate(
1280 function () use ( $user, $oldid ) {
1281 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1283 $user->clearNotification( $this->mTitle
, $oldid );
1285 DeferredUpdates
::PRESEND
1290 * Perform the actions of a page purging
1292 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1293 * controlled how much purging was done.
1295 public function doPurge() {
1296 // Avoid PHP 7.1 warning of passing $this by reference
1299 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1303 $this->mTitle
->invalidateCache();
1306 HTMLFileCache
::clearFileCache( $this->getTitle() );
1307 // Send purge after above page_touched update was committed
1308 DeferredUpdates
::addUpdate(
1309 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1310 DeferredUpdates
::PRESEND
1313 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1314 $messageCache = MessageCache
::singleton();
1315 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1322 * Insert a new empty page record for this article.
1323 * This *must* be followed up by creating a revision
1324 * and running $this->updateRevisionOn( ... );
1325 * or else the record will be left in a funky state.
1326 * Best if all done inside a transaction.
1328 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1330 * @param IDatabase $dbw
1331 * @param int|null $pageId Custom page ID that will be used for the insert statement
1333 * @return bool|int The newly created page_id key; false if the row was not
1334 * inserted, e.g. because the title already existed or because the specified
1335 * page ID is already in use.
1337 public function insertOn( $dbw, $pageId = null ) {
1338 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1342 'page_namespace' => $this->mTitle
->getNamespace(),
1343 'page_title' => $this->mTitle
->getDBkey(),
1344 'page_restrictions' => '',
1345 'page_is_redirect' => 0, // Will set this shortly...
1347 'page_random' => wfRandom(),
1348 'page_touched' => $dbw->timestamp(),
1349 'page_latest' => 0, // Fill this in shortly...
1350 'page_len' => 0, // Fill this in shortly...
1351 ] +
$pageIdForInsert,
1356 if ( $dbw->affectedRows() > 0 ) {
1357 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1358 $this->mId
= $newid;
1359 $this->mTitle
->resetArticleID( $newid );
1363 return false; // nothing changed
1368 * Update the page record to point to a newly saved revision.
1370 * @todo Factor out into a PageStore service, or move into PageUpdater.
1372 * @param IDatabase $dbw
1373 * @param Revision $revision For ID number, and text used to set
1374 * length and redirect status fields
1375 * @param int|null $lastRevision If given, will not overwrite the page field
1376 * when different from the currently set value.
1377 * Giving 0 indicates the new page flag should be set on.
1378 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1379 * removing rows in redirect table.
1380 * @return bool Success; false if the page row was missing or page_latest changed
1382 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1383 $lastRevIsRedirect = null
1385 global $wgContentHandlerUseDB;
1387 // TODO: move into PageUpdater or PageStore
1388 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1389 // and in the compat stub!
1391 // Assertion to try to catch T92046
1392 if ( (int)$revision->getId() === 0 ) {
1393 throw new InvalidArgumentException(
1394 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1398 $content = $revision->getContent();
1399 $len = $content ?
$content->getSize() : 0;
1400 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1402 $conditions = [ 'page_id' => $this->getId() ];
1404 if ( !is_null( $lastRevision ) ) {
1405 // An extra check against threads stepping on each other
1406 $conditions['page_latest'] = $lastRevision;
1409 $revId = $revision->getId();
1410 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1413 'page_latest' => $revId,
1414 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1415 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1416 'page_is_redirect' => $rt !== null ?
1 : 0,
1420 if ( $wgContentHandlerUseDB ) {
1421 $row['page_content_model'] = $revision->getContentModel();
1424 $dbw->update( 'page',
1429 $result = $dbw->affectedRows() > 0;
1431 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1432 $this->setLastEdit( $revision );
1433 $this->mLatest
= $revision->getId();
1434 $this->mIsRedirect
= (bool)$rt;
1435 // Update the LinkCache.
1436 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1437 $linkCache->addGoodLinkObj(
1443 $revision->getContentModel()
1451 * Add row to the redirect table if this is a redirect, remove otherwise.
1453 * @param IDatabase $dbw
1454 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1455 * or NULL if this is not a redirect
1456 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1457 * removing rows in redirect table.
1458 * @return bool True on success, false on failure
1461 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1462 // Always update redirects (target link might have changed)
1463 // Update/Insert if we don't know if the last revision was a redirect or not
1464 // Delete if changing from redirect to non-redirect
1465 $isRedirect = !is_null( $redirectTitle );
1467 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1471 if ( $isRedirect ) {
1472 $success = $this->insertRedirectEntry( $redirectTitle );
1474 // This is not a redirect, remove row from redirect table
1475 $where = [ 'rd_from' => $this->getId() ];
1476 $dbw->delete( 'redirect', $where, __METHOD__
);
1480 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1481 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1488 * If the given revision is newer than the currently set page_latest,
1489 * update the page record. Otherwise, do nothing.
1491 * @deprecated since 1.24, use updateRevisionOn instead
1493 * @param IDatabase $dbw
1494 * @param Revision $revision
1497 public function updateIfNewerOn( $dbw, $revision ) {
1498 $row = $dbw->selectRow(
1499 [ 'revision', 'page' ],
1500 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1502 'page_id' => $this->getId(),
1503 'page_latest=rev_id' ],
1507 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1510 $prev = $row->rev_id
;
1511 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1513 // No or missing previous revision; mark the page as new
1515 $lastRevIsRedirect = null;
1518 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1524 * Helper method for checking whether two revisions have differences that go
1525 * beyond the main slot.
1527 * MCR migration note: this method should go away!
1529 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1531 * @param Revision $a
1532 * @param Revision $b
1535 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1536 $aSlots = $a->getRevisionRecord()->getSlots();
1537 $bSlots = $b->getRevisionRecord()->getSlots();
1538 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1540 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1544 * Get the content that needs to be saved in order to undo all revisions
1545 * between $undo and $undoafter. Revisions must belong to the same page,
1546 * must exist and must not be deleted
1548 * @param Revision $undo
1549 * @param Revision $undoafter Must be an earlier revision than $undo
1550 * @return Content|bool Content on success, false on failure
1552 * Before we had the Content object, this was done in getUndoText
1554 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1555 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1557 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1558 // Cannot yet undo edits that involve anything other the main slot.
1562 $handler = $undo->getContentHandler();
1563 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1567 * Returns true if this page's content model supports sections.
1571 * @todo The skin should check this and not offer section functionality if
1572 * sections are not supported.
1573 * @todo The EditPage should check this and not offer section functionality
1574 * if sections are not supported.
1576 public function supportsSections() {
1577 return $this->getContentHandler()->supportsSections();
1581 * @param string|int|null|bool $sectionId Section identifier as a number or string
1582 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1583 * or 'new' for a new section.
1584 * @param Content $sectionContent New content of the section.
1585 * @param string $sectionTitle New section's subject, only if $section is "new".
1586 * @param string $edittime Revision timestamp or null to use the current revision.
1588 * @throws MWException
1589 * @return Content|null New complete article content, or null if error.
1592 * @deprecated since 1.24, use replaceSectionAtRev instead
1594 public function replaceSectionContent(
1595 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1598 if ( $edittime && $sectionId !== 'new' ) {
1599 $lb = $this->getDBLoadBalancer();
1600 $dbr = $lb->getConnectionRef( DB_REPLICA
);
1601 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1602 // Try the master if this thread may have just added it.
1603 // This could be abstracted into a Revision method, but we don't want
1604 // to encourage loading of revisions by timestamp.
1606 && $lb->getServerCount() > 1
1607 && $lb->hasOrMadeRecentMasterChanges()
1609 $dbw = $lb->getConnectionRef( DB_MASTER
);
1610 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1613 $baseRevId = $rev->getId();
1617 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1621 * @param string|int|null|bool $sectionId Section identifier as a number or string
1622 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1623 * or 'new' for a new section.
1624 * @param Content $sectionContent New content of the section.
1625 * @param string $sectionTitle New section's subject, only if $section is "new".
1626 * @param int|null $baseRevId
1628 * @throws MWException
1629 * @return Content|null New complete article content, or null if error.
1633 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1634 $sectionTitle = '', $baseRevId = null
1636 if ( strval( $sectionId ) === '' ) {
1637 // Whole-page edit; let the whole text through
1638 $newContent = $sectionContent;
1640 if ( !$this->supportsSections() ) {
1641 throw new MWException( "sections not supported for content model " .
1642 $this->getContentHandler()->getModelID() );
1645 // T32711: always use current version when adding a new section
1646 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1647 $oldContent = $this->getContent();
1649 $rev = Revision
::newFromId( $baseRevId );
1651 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1652 $this->getId() . "; section: $sectionId)\n" );
1656 $oldContent = $rev->getContent();
1659 if ( !$oldContent ) {
1660 wfDebug( __METHOD__
. ": no page text\n" );
1664 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1671 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1673 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1674 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1677 * @return int Updated $flags
1679 public function checkFlags( $flags ) {
1680 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1681 if ( $this->exists() ) {
1682 $flags |
= EDIT_UPDATE
;
1692 * @return DerivedPageDataUpdater
1694 private function newDerivedDataUpdater() {
1695 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1697 $derivedDataUpdater = new DerivedPageDataUpdater(
1698 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1699 $this->getRevisionStore(),
1700 $this->getRevisionRenderer(),
1701 $this->getSlotRoleRegistry(),
1702 $this->getParserCache(),
1703 JobQueueGroup
::singleton(),
1704 MessageCache
::singleton(),
1705 MediaWikiServices
::getInstance()->getContentLanguage(),
1706 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1709 $derivedDataUpdater->setLogger( LoggerFactory
::getInstance( 'SaveParse' ) );
1710 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1711 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1713 return $derivedDataUpdater;
1717 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1718 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1719 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1720 * returned matches that caller's expectations, allowing an existing instance to be re-used
1721 * if the given parameters match that instance's internal state according to
1722 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1723 * match the existign one.
1725 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1726 * created, replacing any DerivedPageDataUpdater currently cached.
1728 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1732 * @param User|null $forUser The user that will be used for, or was used for, PST.
1733 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1734 * to perform updates, if the edit was already saved.
1735 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1736 * if the edit was not yet saved.
1737 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1738 * revision as the edit's parent revision. This ensures that the same
1739 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1741 * @return DerivedPageDataUpdater
1743 private function getDerivedDataUpdater(
1744 User
$forUser = null,
1745 RevisionRecord
$forRevision = null,
1746 RevisionSlotsUpdate
$forUpdate = null,
1749 if ( !$forRevision && !$forUpdate ) {
1750 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1751 // going to use it with.
1752 $this->derivedDataUpdater
= null;
1755 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1756 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1757 // to it did not yet initialize it, because we don't know what data it will be
1758 // initialized with.
1759 $this->derivedDataUpdater
= null;
1762 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1763 // However, there is no good way to construct a cache key. We'd need to check against all
1764 // cached instances.
1766 if ( $this->derivedDataUpdater
1767 && !$this->derivedDataUpdater
->isReusableFor(
1771 $forEdit ?
$this->getLatest() : null
1774 $this->derivedDataUpdater
= null;
1777 if ( !$this->derivedDataUpdater
) {
1778 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1781 return $this->derivedDataUpdater
;
1785 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1787 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1788 * and to protected such conflict resolution from concurrent edits using a check-and-set
1794 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1795 * that may already have been returned via getDerivedDataUpdater to be re-used.
1797 * @return PageUpdater
1799 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1800 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1802 $pageUpdater = new PageUpdater(
1804 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1805 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1806 $this->getDBLoadBalancer(),
1807 $this->getRevisionStore(),
1808 $this->getSlotRoleRegistry()
1811 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1812 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1813 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1815 return $pageUpdater;
1819 * Change an existing article or create a new article. Updates RC and all necessary caches,
1820 * optionally via the deferred update array.
1822 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1823 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1824 * apply the autopatrol right as appropriate.
1826 * @param Content $content New content
1827 * @param string|CommentStoreComment $summary Edit summary
1828 * @param int $flags Bitfield:
1830 * Article is known or assumed to be non-existent, create a new one
1832 * Article is known or assumed to be pre-existing, update it
1834 * Mark this edit minor, if the user is allowed to do so
1836 * Do not log the change in recentchanges
1838 * Mark the edit a "bot" edit regardless of user rights
1840 * Fill in blank summaries with generated text where possible
1842 * Signal that the page retrieve/save cycle happened entirely in this request.
1844 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1845 * article will be detected. If EDIT_UPDATE is specified and the article
1846 * doesn't exist, the function will return an edit-gone-missing error. If
1847 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1848 * error will be returned. These two conditions are also possible with
1849 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1851 * @param bool|int $originalRevId: The ID of an original revision that the edit
1852 * restores or repeats. The new revision is expected to have the exact same content as
1853 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1854 * which are created to record things like page moves.
1855 * @param User|null $user The user doing the edit
1856 * @param string|null $serialFormat IGNORED.
1857 * @param array|null $tags Change tags to apply to this edit
1858 * Callers are responsible for permission checks
1859 * (with ChangeTags::canAddTagsAccompanyingChange)
1860 * @param Int $undidRevId Id of revision that was undone or 0
1862 * @throws MWException
1863 * @return Status Possible errors:
1864 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1865 * set the fatal flag of $status.
1866 * edit-gone-missing: In update mode, but the article didn't exist.
1867 * edit-conflict: In update mode, the article changed unexpectedly.
1868 * edit-no-change: Warning that the text was the same as before.
1869 * edit-already-exists: In creation mode, but the article already exists.
1871 * Extensions may define additional errors.
1873 * $return->value will contain an associative array with members as follows:
1874 * new: Boolean indicating if the function attempted to create a new article.
1875 * revision: The revision object for the inserted revision, or null.
1878 * @throws MWException
1880 public function doEditContent(
1881 Content
$content, $summary, $flags = 0, $originalRevId = false,
1882 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1884 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1886 if ( !( $summary instanceof CommentStoreComment
) ) {
1887 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1894 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1895 // Checking the minoredit right should be done in the same place the 'bot' right is
1896 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1897 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1898 $flags = ( $flags & ~EDIT_MINOR
);
1901 $slotsUpdate = new RevisionSlotsUpdate();
1902 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1904 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1905 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1906 // used by this PageUpdater. However, there is no guarantee for this.
1907 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1908 $updater->setContent( SlotRecord
::MAIN
, $content );
1909 $updater->setOriginalRevisionId( $originalRevId );
1910 $updater->setUndidRevisionId( $undidRevId );
1912 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1914 // TODO: this logic should not be in the storage layer, it's here for compatibility
1915 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1916 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1917 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1919 if ( $needsPatrol && $permissionManager->userCan(
1920 'autopatrol', $user, $this->getTitle()
1922 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1925 $updater->addTags( $tags );
1927 $revRec = $updater->saveRevision(
1932 // $revRec will be null if the edit failed, or if no new revision was created because
1933 // the content did not change.
1935 // update cached fields
1936 // TODO: this is currently redundant to what is done in updateRevisionOn.
1937 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1938 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1939 $this->mLatest
= $revRec->getId();
1942 return $updater->getStatus();
1946 * Get parser options suitable for rendering the primary article wikitext
1948 * @see ParserOptions::newCanonical
1950 * @param IContextSource|User|string $context One of the following:
1951 * - IContextSource: Use the User and the Language of the provided
1953 * - User: Use the provided User object and $wgLang for the language,
1954 * so use an IContextSource object if possible.
1955 * - 'canonical': Canonical options (anonymous user with default
1956 * preferences and content language).
1957 * @return ParserOptions
1959 public function makeParserOptions( $context ) {
1960 $options = ParserOptions
::newCanonical( $context );
1962 if ( $this->getTitle()->isConversionTable() ) {
1963 // @todo ConversionTable should become a separate content model, so
1964 // we don't need special cases like this one.
1965 $options->disableContentConversion();
1972 * Prepare content which is about to be saved.
1974 * Prior to 1.30, this returned a stdClass.
1976 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1978 * @param Content $content
1979 * @param Revision|RevisionRecord|null $revision Revision object.
1980 * Used with vary-revision or vary-revision-id.
1981 * @param User|null $user
1982 * @param string|null $serialFormat IGNORED
1983 * @param bool $useCache Check shared prepared edit cache
1985 * @return PreparedEdit
1989 public function prepareContentForEdit(
1993 $serialFormat = null,
2002 if ( $revision !== null ) {
2003 if ( $revision instanceof Revision
) {
2004 $revision = $revision->getRevisionRecord();
2005 } elseif ( !( $revision instanceof RevisionRecord
) ) {
2006 throw new InvalidArgumentException(
2007 __METHOD__
. ': invalid $revision argument type ' . gettype( $revision ) );
2011 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
2012 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
2014 if ( !$updater->isUpdatePrepared() ) {
2015 $updater->prepareContent( $user, $slots, $useCache );
2018 $updater->prepareUpdate(
2021 'causeAction' => 'prepare-edit',
2022 'causeAgent' => $user->getName(),
2028 return $updater->getPreparedEdit();
2032 * Do standard deferred updates after page edit.
2033 * Update links tables, site stats, search index and message cache.
2034 * Purges pages that include this page if the text was changed here.
2035 * Every 100th edit, prune the recent changes table.
2037 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2039 * @param Revision $revision
2040 * @param User $user User object that did the revision
2041 * @param array $options Array of options, following indexes are used:
2042 * - changed: bool, whether the revision changed the content (default true)
2043 * - created: bool, whether the revision created the page (default false)
2044 * - moved: bool, whether the page was moved (default false)
2045 * - restored: bool, whether the page was undeleted (default false)
2046 * - oldrevision: Revision object for the pre-update revision (default null)
2047 * - oldcountable: bool, null, or string 'no-change' (default null):
2048 * - bool: whether the page was counted as an article before that
2049 * revision, only used in changed is true and created is false
2050 * - null: if created is false, don't update the article count; if created
2051 * is true, do update the article count
2052 * - 'no-change': don't update the article count, ever
2053 * - causeAction: an arbitrary string identifying the reason for the update.
2054 * See DataUpdate::getCauseAction(). (default 'edit-page')
2055 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2056 * (string, defaults to the passed user)
2058 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2060 'causeAction' => 'edit-page',
2061 'causeAgent' => $user->getName(),
2064 $revision = $revision->getRevisionRecord();
2066 $updater = $this->getDerivedDataUpdater( $user, $revision );
2068 $updater->prepareUpdate( $revision, $options );
2070 $updater->doUpdates();
2074 * Update the parser cache.
2076 * @note This is a temporary workaround until there is a proper data updater class.
2077 * It will become deprecated soon.
2079 * @param array $options
2080 * - causeAction: an arbitrary string identifying the reason for the update.
2081 * See DataUpdate::getCauseAction(). (default 'edit-page')
2082 * - causeAgent: name of the user who caused the update (string, defaults to the
2083 * user who created the revision)
2086 public function updateParserCache( array $options = [] ) {
2087 $revision = $this->getRevisionRecord();
2088 if ( !$revision ||
!$revision->getId() ) {
2089 LoggerFactory
::getInstance( 'wikipage' )->info(
2090 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2094 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2096 $updater = $this->getDerivedDataUpdater( $user, $revision );
2097 $updater->prepareUpdate( $revision, $options );
2098 $updater->doParserCacheUpdate();
2102 * Do secondary data updates (such as updating link tables).
2103 * Secondary data updates are only a small part of the updates needed after saving
2104 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2105 * secondary data updates). This method is provided for partial purges.
2107 * @note This is a temporary workaround until there is a proper data updater class.
2108 * It will become deprecated soon.
2110 * @param array $options
2111 * - recursive (bool, default true): whether to do a recursive update (update pages that
2112 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2113 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2114 * was something that did not really change the page, such as a null edit.
2115 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2116 * user who created the revision)
2117 * - causeAction: an arbitrary string identifying the reason for the update.
2118 * See DataUpdate::getCauseAction(). (default 'unknown')
2119 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2120 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2121 * Note that even when this is set to false, some updates might still get deferred (as
2122 * some update might directly add child updates to DeferredUpdates).
2123 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
2124 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
2125 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
2126 * for the time until caches have been changed to store RenderedRevision states instead
2127 * of ParserOutput objects. (default: null) (since 1.33)
2130 public function doSecondaryDataUpdates( array $options = [] ) {
2131 $options['recursive'] = $options['recursive'] ??
true;
2132 $revision = $this->getRevisionRecord();
2133 if ( !$revision ||
!$revision->getId() ) {
2134 LoggerFactory
::getInstance( 'wikipage' )->info(
2135 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2139 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2141 $updater = $this->getDerivedDataUpdater( $user, $revision );
2142 $updater->prepareUpdate( $revision, $options );
2143 $updater->doSecondaryDataUpdates( $options );
2147 * Update the article's restriction field, and leave a log entry.
2148 * This works for protection both existing and non-existing pages.
2150 * @param array $limit Set of restriction keys
2151 * @param array $expiry Per restriction type expiration
2152 * @param int &$cascade Set to false if cascading protection isn't allowed.
2153 * @param string $reason
2154 * @param User $user The user updating the restrictions
2155 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2156 * ($user should be able to add the specified tags before this is called)
2157 * @return Status Status object; if action is taken, $status->value is the log_id of the
2158 * protection log entry.
2160 public function doUpdateRestrictions( array $limit, array $expiry,
2161 &$cascade, $reason, User
$user, $tags = null
2163 global $wgCascadingRestrictionLevels;
2165 if ( wfReadOnly() ) {
2166 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2169 $this->loadPageData( 'fromdbmaster' );
2170 $this->mTitle
->loadRestrictions( null, Title
::READ_LATEST
);
2171 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2172 $id = $this->getId();
2178 // Take this opportunity to purge out expired restrictions
2179 Title
::purgeExpiredRestrictions();
2181 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2182 // we expect a single selection, but the schema allows otherwise.
2183 $isProtected = false;
2187 $dbw = wfGetDB( DB_MASTER
);
2189 foreach ( $restrictionTypes as $action ) {
2190 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2191 $expiry[$action] = 'infinity';
2193 if ( !isset( $limit[$action] ) ) {
2194 $limit[$action] = '';
2195 } elseif ( $limit[$action] != '' ) {
2199 // Get current restrictions on $action
2200 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2201 if ( $current != '' ) {
2202 $isProtected = true;
2205 if ( $limit[$action] != $current ) {
2207 } elseif ( $limit[$action] != '' ) {
2208 // Only check expiry change if the action is actually being
2209 // protected, since expiry does nothing on an not-protected
2211 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2217 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2221 // If nothing has changed, do nothing
2223 return Status
::newGood();
2226 if ( !$protect ) { // No protection at all means unprotection
2227 $revCommentMsg = 'unprotectedarticle-comment';
2228 $logAction = 'unprotect';
2229 } elseif ( $isProtected ) {
2230 $revCommentMsg = 'modifiedarticleprotection-comment';
2231 $logAction = 'modify';
2233 $revCommentMsg = 'protectedarticle-comment';
2234 $logAction = 'protect';
2237 $logRelationsValues = [];
2238 $logRelationsField = null;
2239 $logParamsDetails = [];
2241 // Null revision (used for change tag insertion)
2242 $nullRevision = null;
2244 if ( $id ) { // Protection of existing page
2245 // Avoid PHP 7.1 warning of passing $this by reference
2248 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2249 return Status
::newGood();
2252 // Only certain restrictions can cascade...
2253 $editrestriction = isset( $limit['edit'] )
2254 ?
[ $limit['edit'] ]
2255 : $this->mTitle
->getRestrictions( 'edit' );
2256 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2257 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2259 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2260 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2263 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2264 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2265 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2267 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2268 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2271 // The schema allows multiple restrictions
2272 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2276 // insert null revision to identify the page protection change as edit summary
2277 $latest = $this->getLatest();
2278 $nullRevision = $this->insertProtectNullRevision(
2287 if ( $nullRevision === null ) {
2288 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2291 $logRelationsField = 'pr_id';
2293 // Update restrictions table
2294 foreach ( $limit as $action => $restrictions ) {
2296 'page_restrictions',
2299 'pr_type' => $action
2303 if ( $restrictions != '' ) {
2304 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2306 'page_restrictions',
2309 'pr_type' => $action,
2310 'pr_level' => $restrictions,
2311 'pr_cascade' => $cascadeValue,
2312 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2316 $logRelationsValues[] = $dbw->insertId();
2317 $logParamsDetails[] = [
2319 'level' => $restrictions,
2320 'expiry' => $expiry[$action],
2321 'cascade' => (bool)$cascadeValue,
2326 // Clear out legacy restriction fields
2329 [ 'page_restrictions' => '' ],
2330 [ 'page_id' => $id ],
2334 // Avoid PHP 7.1 warning of passing $this by reference
2337 Hooks
::run( 'NewRevisionFromEditComplete',
2338 [ $this, $nullRevision, $latest, $user ] );
2339 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2340 } else { // Protection of non-existing page (also known as "title protection")
2341 // Cascade protection is meaningless in this case
2344 if ( $limit['create'] != '' ) {
2345 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2346 $dbw->replace( 'protected_titles',
2347 [ [ 'pt_namespace', 'pt_title' ] ],
2349 'pt_namespace' => $this->mTitle
->getNamespace(),
2350 'pt_title' => $this->mTitle
->getDBkey(),
2351 'pt_create_perm' => $limit['create'],
2352 'pt_timestamp' => $dbw->timestamp(),
2353 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2354 'pt_user' => $user->getId(),
2355 ] +
$commentFields, __METHOD__
2357 $logParamsDetails[] = [
2359 'level' => $limit['create'],
2360 'expiry' => $expiry['create'],
2363 $dbw->delete( 'protected_titles',
2365 'pt_namespace' => $this->mTitle
->getNamespace(),
2366 'pt_title' => $this->mTitle
->getDBkey()
2372 $this->mTitle
->flushRestrictions();
2373 InfoAction
::invalidateCache( $this->mTitle
);
2375 if ( $logAction == 'unprotect' ) {
2378 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2380 '4::description' => $protectDescriptionLog, // parameter for IRC
2381 '5:bool:cascade' => $cascade,
2382 'details' => $logParamsDetails, // parameter for localize and api
2386 // Update the protection log
2387 $logEntry = new ManualLogEntry( 'protect', $logAction );
2388 $logEntry->setTarget( $this->mTitle
);
2389 $logEntry->setComment( $reason );
2390 $logEntry->setPerformer( $user );
2391 $logEntry->setParameters( $params );
2392 if ( !is_null( $nullRevision ) ) {
2393 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2395 $logEntry->setTags( $tags );
2396 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2397 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2399 $logId = $logEntry->insert();
2400 $logEntry->publish( $logId );
2402 return Status
::newGood( $logId );
2406 * Insert a new null revision for this page.
2408 * @param string $revCommentMsg Comment message key for the revision
2409 * @param array $limit Set of restriction keys
2410 * @param array $expiry Per restriction type expiration
2411 * @param int $cascade Set to false if cascading protection isn't allowed.
2412 * @param string $reason
2413 * @param User|null $user
2414 * @return Revision|null Null on error
2416 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2417 array $expiry, $cascade, $reason, $user = null
2419 $dbw = wfGetDB( DB_MASTER
);
2421 // Prepare a null revision to be added to the history
2422 $editComment = wfMessage(
2424 $this->mTitle
->getPrefixedText(),
2425 $user ?
$user->getName() : ''
2426 )->inContentLanguage()->text();
2428 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2430 $protectDescription = $this->protectDescription( $limit, $expiry );
2431 if ( $protectDescription ) {
2432 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2433 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2434 ->inContentLanguage()->text();
2437 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2438 $editComment .= wfMessage( 'brackets' )->params(
2439 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2440 )->inContentLanguage()->text();
2443 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2445 $nullRev->insertOn( $dbw );
2447 // Update page record and touch page
2448 $oldLatest = $nullRev->getParentId();
2449 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2456 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2459 protected function formatExpiry( $expiry ) {
2460 if ( $expiry != 'infinity' ) {
2461 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2464 $contLang->timeanddate( $expiry, false, false ),
2465 $contLang->date( $expiry, false, false ),
2466 $contLang->time( $expiry, false, false )
2467 )->inContentLanguage()->text();
2469 return wfMessage( 'protect-expiry-indefinite' )
2470 ->inContentLanguage()->text();
2475 * Builds the description to serve as comment for the edit.
2477 * @param array $limit Set of restriction keys
2478 * @param array $expiry Per restriction type expiration
2481 public function protectDescription( array $limit, array $expiry ) {
2482 $protectDescription = '';
2484 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2485 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2486 # All possible message keys are listed here for easier grepping:
2487 # * restriction-create
2488 # * restriction-edit
2489 # * restriction-move
2490 # * restriction-upload
2491 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2492 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2493 # with '' filtered out. All possible message keys are listed below:
2494 # * protect-level-autoconfirmed
2495 # * protect-level-sysop
2496 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2497 ->inContentLanguage()->text();
2499 $expiryText = $this->formatExpiry( $expiry[$action] );
2501 if ( $protectDescription !== '' ) {
2502 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2504 $protectDescription .= wfMessage( 'protect-summary-desc' )
2505 ->params( $actionText, $restrictionsText, $expiryText )
2506 ->inContentLanguage()->text();
2509 return $protectDescription;
2513 * Builds the description to serve as comment for the log entry.
2515 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2516 * protect description text. Keep them in old format to avoid breaking compatibility.
2517 * TODO: Fix protection log to store structured description and format it on-the-fly.
2519 * @param array $limit Set of restriction keys
2520 * @param array $expiry Per restriction type expiration
2523 public function protectDescriptionLog( array $limit, array $expiry ) {
2524 $protectDescriptionLog = '';
2526 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2527 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2528 $expiryText = $this->formatExpiry( $expiry[$action] );
2529 $protectDescriptionLog .=
2531 "[$action=$restrictions] ($expiryText)";
2534 return trim( $protectDescriptionLog );
2538 * Take an array of page restrictions and flatten it to a string
2539 * suitable for insertion into the page_restrictions field.
2541 * @param string[] $limit
2543 * @throws MWException
2546 protected static function flattenRestrictions( $limit ) {
2547 if ( !is_array( $limit ) ) {
2548 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2554 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2555 $bits[] = "$action=$restrictions";
2558 return implode( ':', $bits );
2562 * Determines if deletion of this page would be batched (executed over time by the job queue)
2563 * or not (completed in the same request as the delete call).
2565 * It is unlikely but possible that an edit from another request could push the page over the
2566 * batching threshold after this function is called, but before the caller acts upon the
2567 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2568 * is provided as an unreliable but situationally useful help for some common cases.
2570 * @param int $safetyMargin Added to the revision count when checking for batching
2571 * @return bool True if deletion would be batched, false otherwise
2573 public function isBatchedDelete( $safetyMargin = 0 ) {
2574 global $wgDeleteRevisionsBatchSize;
2576 $dbr = wfGetDB( DB_REPLICA
);
2577 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2578 $revCount +
= $safetyMargin;
2580 return $revCount >= $wgDeleteRevisionsBatchSize;
2584 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2585 * backwards compatibility, if you care about error reporting you should use
2586 * doDeleteArticleReal() instead.
2588 * Deletes the article with database consistency, writes logs, purges caches
2590 * @param string $reason Delete reason for deletion log
2591 * @param bool $suppress Suppress all revisions and log the deletion in
2592 * the suppression log instead of the deletion log
2593 * @param int|null $u1 Unused
2594 * @param bool|null $u2 Unused
2595 * @param array|string &$error Array of errors to append to
2596 * @param User|null $user The deleting user
2597 * @param bool $immediate false allows deleting over time via the job queue
2598 * @return bool True if successful
2599 * @throws FatalError
2600 * @throws MWException
2602 public function doDeleteArticle(
2603 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2606 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2607 [], 'delete', $immediate );
2609 // Returns true if the page was actually deleted, or is scheduled for deletion
2610 return $status->isOK();
2614 * Back-end article deletion
2615 * Deletes the article with database consistency, writes logs, purges caches
2619 * @param string $reason Delete reason for deletion log
2620 * @param bool $suppress Suppress all revisions and log the deletion in
2621 * the suppression log instead of the deletion log
2622 * @param int|null $u1 Unused
2623 * @param bool|null $u2 Unused
2624 * @param array|string &$error Array of errors to append to
2625 * @param User|null $deleter The deleting user
2626 * @param array $tags Tags to apply to the deletion action
2627 * @param string $logsubtype
2628 * @param bool $immediate false allows deleting over time via the job queue
2629 * @return Status Status object; if successful, $status->value is the log_id of the
2630 * deletion log entry. If the page couldn't be deleted because it wasn't
2631 * found, $status is a non-fatal 'cannotdelete' error
2632 * @throws FatalError
2633 * @throws MWException
2635 public function doDeleteArticleReal(
2636 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2637 $tags = [], $logsubtype = 'delete', $immediate = false
2641 wfDebug( __METHOD__
. "\n" );
2643 $status = Status
::newGood();
2645 // Avoid PHP 7.1 warning of passing $this by reference
2651 if ( !Hooks
::run( 'ArticleDelete',
2652 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2654 if ( $status->isOK() ) {
2655 // Hook aborted but didn't set a fatal status
2656 $status->fatal( 'delete-hook-aborted' );
2661 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2662 $logsubtype, $immediate );
2666 * Back-end article deletion
2668 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2669 * Deletions can often be completed inline without involving the job queue.
2671 * Potentially called many times per deletion operation for pages with many revisions.
2673 public function doDeleteArticleBatched(
2674 $reason, $suppress, User
$deleter, $tags,
2675 $logsubtype, $immediate = false, $webRequestId = null
2677 wfDebug( __METHOD__
. "\n" );
2679 $status = Status
::newGood();
2681 $dbw = wfGetDB( DB_MASTER
);
2682 $dbw->startAtomic( __METHOD__
);
2684 $this->loadPageData( self
::READ_LATEST
);
2685 $id = $this->getId();
2686 // T98706: lock the page from various other updates but avoid using
2687 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2688 // the revisions queries (which also JOIN on user). Only lock the page
2689 // row and CAS check on page_latest to see if the trx snapshot matches.
2690 $lockedLatest = $this->lockAndGetLatest();
2691 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2692 $dbw->endAtomic( __METHOD__
);
2693 // Page not there or trx snapshot is stale
2694 $status->error( 'cannotdelete',
2695 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2699 // At this point we are now committed to returning an OK
2700 // status unless some DB query error or other exception comes up.
2701 // This way callers don't have to call rollback() if $status is bad
2702 // unless they actually try to catch exceptions (which is rare).
2704 // we need to remember the old content so we can use it to generate all deletion updates.
2705 $revision = $this->getRevision();
2707 $content = $this->getContent( RevisionRecord
::RAW
);
2708 } catch ( Exception
$ex ) {
2709 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2710 . $ex->getMessage() );
2715 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2716 // one batch of revisions and defer archival of any others to the job queue.
2717 $explictTrxLogged = false;
2719 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2720 if ( $done ||
!$immediate ) {
2723 $dbw->endAtomic( __METHOD__
);
2724 if ( $dbw->explicitTrxActive() ) {
2725 // Explict transactions may never happen here in practice. Log to be sure.
2726 if ( !$explictTrxLogged ) {
2727 $explictTrxLogged = true;
2728 LoggerFactory
::getInstance( 'wfDebug' )->debug(
2729 'explicit transaction active in ' . __METHOD__
. ' while deleting {title}', [
2730 'title' => $this->getTitle()->getText(),
2735 if ( $dbw->trxLevel() ) {
2738 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
2739 $lbFactory->waitForReplication();
2740 $dbw->startAtomic( __METHOD__
);
2743 // If done archiving, also delete the article.
2745 $dbw->endAtomic( __METHOD__
);
2748 'namespace' => $this->getTitle()->getNamespace(),
2749 'title' => $this->getTitle()->getDBkey(),
2750 'wikiPageId' => $id,
2751 'requestId' => $webRequestId ?? WebRequest
::getRequestId(),
2752 'reason' => $reason,
2753 'suppress' => $suppress,
2754 'userId' => $deleter->getId(),
2755 'tags' => json_encode( $tags ),
2756 'logsubtype' => $logsubtype,
2759 $job = new DeletePageJob( $jobParams );
2760 JobQueueGroup
::singleton()->push( $job );
2762 $status->warning( 'delete-scheduled',
2763 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2765 // Get archivedRevisionCount by db query, because there's no better alternative.
2766 // Jobs cannot pass a count of archived revisions to the next job, because additional
2767 // deletion operations can be started while the first is running. Jobs from each
2768 // gracefully interleave, but would not know about each other's count. Deduplication
2769 // in the job queue to avoid simultaneous deletion operations would add overhead.
2770 // Number of archived revisions cannot be known beforehand, because edits can be made
2771 // while deletion operations are being processed, changing the number of archivals.
2772 $archivedRevisionCount = (int)$dbw->selectField(
2773 'archive', 'COUNT(*)',
2775 'ar_namespace' => $this->getTitle()->getNamespace(),
2776 'ar_title' => $this->getTitle()->getDBkey(),
2781 // Clone the title and wikiPage, so we have the information we need when
2782 // we log and run the ArticleDeleteComplete hook.
2783 $logTitle = clone $this->mTitle
;
2784 $wikiPageBeforeDelete = clone $this;
2786 // Now that it's safely backed up, delete it
2787 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2789 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2790 $logtype = $suppress ?
'suppress' : 'delete';
2792 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2793 $logEntry->setPerformer( $deleter );
2794 $logEntry->setTarget( $logTitle );
2795 $logEntry->setComment( $reason );
2796 $logEntry->setTags( $tags );
2797 $logid = $logEntry->insert();
2799 $dbw->onTransactionPreCommitOrIdle(
2800 function () use ( $logEntry, $logid ) {
2801 // T58776: avoid deadlocks (especially from FileDeleteForm)
2802 $logEntry->publish( $logid );
2807 $dbw->endAtomic( __METHOD__
);
2809 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2811 Hooks
::run( 'ArticleDeleteComplete', [
2812 &$wikiPageBeforeDelete,
2818 $archivedRevisionCount
2820 $status->value
= $logid;
2822 // Show log excerpt on 404 pages rather than just a link
2823 $dbCache = ObjectCache
::getInstance( 'db-replicated' );
2824 $key = $dbCache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2825 $dbCache->set( $key, 1, $dbCache::TTL_DAY
);
2832 * Archives revisions as part of page deletion.
2834 * @param IDatabase $dbw
2836 * @param bool $suppress Suppress all revisions and log the deletion in
2837 * the suppression log instead of the deletion log
2840 protected function archiveRevisions( $dbw, $id, $suppress ) {
2841 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2842 $wgActorTableSchemaMigrationStage, $wgDeleteRevisionsBatchSize;
2844 // Given the lock above, we can be confident in the title and page ID values
2845 $namespace = $this->getTitle()->getNamespace();
2846 $dbKey = $this->getTitle()->getDBkey();
2848 $commentStore = CommentStore
::getStore();
2849 $actorMigration = ActorMigration
::newMigration();
2851 $revQuery = Revision
::getQueryInfo();
2854 // Bitfields to further suppress the content
2856 $bitfield = RevisionRecord
::SUPPRESSED_ALL
;
2857 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2860 // For now, shunt the revision data into the archive table.
2861 // Text is *not* removed from the text table; bulk storage
2862 // is left intact to avoid breaking block-compression or
2863 // immutable storage schemes.
2864 // In the future, we may keep revisions and mark them with
2865 // the rev_deleted field, which is reserved for this purpose.
2867 // Lock rows in `revision` and its temp tables, but not any others.
2868 // Note array_intersect() preserves keys from the first arg, and we're
2869 // assuming $revQuery has `revision` primary and isn't using subtables
2870 // for anything we care about.
2871 $dbw->lockForUpdate(
2873 $revQuery['tables'],
2874 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2876 [ 'rev_page' => $id ],
2882 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2883 // so we can copy it to the archive table.
2884 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2885 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2886 $revQuery['fields'][] = 'rev_text_id';
2888 if ( $wgContentHandlerUseDB ) {
2889 $revQuery['fields'][] = 'rev_content_model';
2890 $revQuery['fields'][] = 'rev_content_format';
2894 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2895 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2896 $res = $dbw->select(
2897 $revQuery['tables'],
2898 $revQuery['fields'],
2899 [ 'rev_page' => $id ],
2901 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize +
1 ],
2905 // Build their equivalent archive rows
2909 /** @var int[] Revision IDs of edits that were made by IPs */
2913 foreach ( $res as $row ) {
2914 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2919 $comment = $commentStore->getComment( 'rev_comment', $row );
2920 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2922 'ar_namespace' => $namespace,
2923 'ar_title' => $dbKey,
2924 'ar_timestamp' => $row->rev_timestamp
,
2925 'ar_minor_edit' => $row->rev_minor_edit
,
2926 'ar_rev_id' => $row->rev_id
,
2927 'ar_parent_id' => $row->rev_parent_id
,
2929 * ar_text_id should probably not be written to when the multi content schema has
2930 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2931 * default for the field in WMF production currently so we must keep writing
2932 * writing until a default of 0 is set.
2933 * Task: https://phabricator.wikimedia.org/T190148
2934 * Copying the value from the revision table should not lead to any issues for now.
2936 'ar_len' => $row->rev_len
,
2937 'ar_page_id' => $id,
2938 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2939 'ar_sha1' => $row->rev_sha1
,
2940 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2941 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2943 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2944 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2946 if ( $wgContentHandlerUseDB ) {
2947 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2948 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2952 $rowsInsert[] = $rowInsert;
2953 $revids[] = $row->rev_id
;
2955 // Keep track of IP edits, so that the corresponding rows can
2956 // be deleted in the ip_changes table.
2957 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2958 $ipRevIds[] = $row->rev_id
;
2962 // This conditional is just a sanity check
2963 if ( count( $revids ) > 0 ) {
2964 // Copy them into the archive table
2965 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2967 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__
);
2968 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2969 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2970 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2973 // Also delete records from ip_changes as applicable.
2974 if ( count( $ipRevIds ) > 0 ) {
2975 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2983 * Lock the page row for this title+id and return page_latest (or 0)
2985 * @return int Returns 0 if no row was found with this title+id
2988 public function lockAndGetLatest() {
2989 return (int)wfGetDB( DB_MASTER
)->selectField(
2993 'page_id' => $this->getId(),
2994 // Typically page_id is enough, but some code might try to do
2995 // updates assuming the title is the same, so verify that
2996 'page_namespace' => $this->getTitle()->getNamespace(),
2997 'page_title' => $this->getTitle()->getDBkey()
3005 * Do some database updates after deletion
3007 * @param int $id The page_id value of the page being deleted
3008 * @param Content|null $content Page content to be used when determining
3009 * the required updates. This may be needed because $this->getContent()
3010 * may already return null when the page proper was deleted.
3011 * @param Revision|null $revision The current page revision at the time of
3012 * deletion, used when determining the required updates. This may be needed because
3013 * $this->getRevision() may already return null when the page proper was deleted.
3014 * @param User|null $user The user that caused the deletion
3016 public function doDeleteUpdates(
3017 $id, Content
$content = null, Revision
$revision = null, User
$user = null
3019 if ( $id !== $this->getId() ) {
3020 throw new InvalidArgumentException( 'Mismatching page ID' );
3024 $countable = $this->isCountable();
3025 } catch ( Exception
$ex ) {
3026 // fallback for deleting broken pages for which we cannot load the content for
3027 // some reason. Note that doDeleteArticleReal() already logged this problem.
3031 // Update site status
3032 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
3033 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
3036 // Delete pagelinks, update secondary indexes, etc
3037 $updates = $this->getDeletionUpdates(
3038 $revision ?
$revision->getRevisionRecord() : $content
3040 foreach ( $updates as $update ) {
3041 DeferredUpdates
::addUpdate( $update );
3044 $causeAgent = $user ?
$user->getName() : 'unknown';
3045 // Reparse any pages transcluding this page
3046 LinksUpdate
::queueRecursiveJobsForTable(
3047 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3048 // Reparse any pages including this image
3049 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3050 LinksUpdate
::queueRecursiveJobsForTable(
3051 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3055 self
::onArticleDelete( $this->mTitle
);
3056 ResourceLoaderWikiModule
::invalidateModuleCache(
3060 WikiMap
::getCurrentWikiDbDomain()->getId()
3063 // Reset this object and the Title object
3064 $this->loadFromRow( false, self
::READ_LATEST
);
3067 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3071 * Roll back the most recent consecutive set of edits to a page
3072 * from the same user; fails if there are no eligible edits to
3073 * roll back to, e.g. user is the sole contributor. This function
3074 * performs permissions checks on $user, then calls commitRollback()
3075 * to do the dirty work
3077 * @todo Separate the business/permission stuff out from backend code
3078 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3080 * @param string $fromP Name of the user whose edits to rollback.
3081 * @param string $summary Custom summary. Set to default summary if empty.
3082 * @param string $token Rollback token.
3083 * @param bool $bot If true, mark all reverted edits as bot.
3085 * @param array &$resultDetails Array contains result-specific array of additional values
3086 * 'alreadyrolled' : 'current' (rev)
3087 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3089 * @param User $user The user performing the rollback
3090 * @param array|null $tags Change tags to apply to the rollback
3091 * Callers are responsible for permission checks
3092 * (with ChangeTags::canAddTagsAccompanyingChange)
3094 * @return array Array of errors, each error formatted as
3095 * [ messagekey, param1, param2, ... ].
3096 * On success, the array is empty. This array can also be passed to
3097 * OutputPage::showPermissionsErrorPage().
3099 public function doRollback(
3100 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3102 $resultDetails = null;
3104 // Check permissions
3105 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3106 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3107 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3109 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3110 $errors[] = [ 'sessionfailure' ];
3113 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3114 $errors[] = [ 'actionthrottledtext' ];
3117 // If there were errors, bail out now
3118 if ( !empty( $errors ) ) {
3122 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3126 * Backend implementation of doRollback(), please refer there for parameter
3127 * and return value documentation
3129 * NOTE: This function does NOT check ANY permissions, it just commits the
3130 * rollback to the DB. Therefore, you should only call this function direct-
3131 * ly if you want to use custom permissions checks. If you don't, use
3132 * doRollback() instead.
3133 * @param string $fromP Name of the user whose edits to rollback.
3134 * @param string $summary Custom summary. Set to default summary if empty.
3135 * @param bool $bot If true, mark all reverted edits as bot.
3137 * @param array &$resultDetails Contains result-specific array of additional values
3138 * @param User $guser The user performing the rollback
3139 * @param array|null $tags Change tags to apply to the rollback
3140 * Callers are responsible for permission checks
3141 * (with ChangeTags::canAddTagsAccompanyingChange)
3143 * @return array An array of error messages, as returned by Status::getErrorsArray()
3145 public function commitRollback( $fromP, $summary, $bot,
3146 &$resultDetails, User
$guser, $tags = null
3148 global $wgUseRCPatrol;
3150 $dbw = wfGetDB( DB_MASTER
);
3152 if ( wfReadOnly() ) {
3153 return [ [ 'readonlytext' ] ];
3156 // Begin revision creation cycle by creating a PageUpdater.
3157 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3158 $updater = $this->newPageUpdater( $guser );
3159 $current = $updater->grabParentRevision();
3161 if ( is_null( $current ) ) {
3162 // Something wrong... no page?
3163 return [ [ 'notanarticle' ] ];
3166 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
3167 $legacyCurrent = new Revision( $current );
3168 $from = str_replace( '_', ' ', $fromP );
3170 // User name given should match up with the top revision.
3171 // If the revision's user is not visible, then $from should be empty.
3172 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
3173 $resultDetails = [ 'current' => $legacyCurrent ];
3174 return [ [ 'alreadyrolled',
3175 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3176 htmlspecialchars( $fromP ),
3177 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3181 // Get the last edit not by this person...
3182 // Note: these may not be public values
3183 $actorWhere = ActorMigration
::newMigration()->getWhere(
3186 $current->getUser( RevisionRecord
::RAW
)
3189 $s = $dbw->selectRow(
3190 [ 'revision' ] +
$actorWhere['tables'],
3191 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3193 'rev_page' => $current->getPageId(),
3194 'NOT(' . $actorWhere['conds'] . ')',
3198 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3199 'ORDER BY' => 'rev_timestamp DESC'
3201 $actorWhere['joins']
3203 if ( $s === false ) {
3204 // No one else ever edited this page
3205 return [ [ 'cantrollback' ] ];
3206 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3207 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3209 // Only admins can see this text
3210 return [ [ 'notvisiblerev' ] ];
3213 // Generate the edit summary if necessary
3214 $target = $this->getRevisionStore()->getRevisionById(
3216 RevisionStore
::READ_LATEST
3218 if ( empty( $summary ) ) {
3219 if ( !$currentEditorForPublic ) { // no public user name
3220 $summary = wfMessage( 'revertpage-nouser' );
3222 $summary = wfMessage( 'revertpage' );
3225 $legacyTarget = new Revision( $target );
3226 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3228 // Allow the custom summary to use the same args as the default message
3229 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3231 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3232 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3234 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3236 $contLang->timeanddate( $current->getTimestamp() )
3238 if ( $summary instanceof Message
) {
3239 $summary = $summary->params( $args )->inContentLanguage()->text();
3241 $summary = wfMsgReplaceArgs( $summary, $args );
3244 // Trim spaces on user supplied text
3245 $summary = trim( $summary );
3248 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3250 if ( $guser->isAllowed( 'minoredit' ) ) {
3251 $flags |
= EDIT_MINOR
;
3254 if ( $bot && ( MediaWikiServices
::getInstance()
3255 ->getPermissionManager()
3256 ->userHasAnyRight( $guser, 'markbotedits', 'bot' ) )
3258 $flags |
= EDIT_FORCE_BOT
;
3261 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3262 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3263 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3264 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3266 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3267 $tags[] = 'mw-rollback';
3270 // Build rollback revision:
3271 // Restore old content
3272 // TODO: MCR: test this once we can store multiple slots
3273 foreach ( $target->getSlots()->getSlots() as $slot ) {
3274 $updater->inheritSlot( $slot );
3277 // Remove extra slots
3278 // TODO: MCR: test this once we can store multiple slots
3279 foreach ( $current->getSlotRoles() as $role ) {
3280 if ( !$target->hasSlot( $role ) ) {
3281 $updater->removeSlot( $role );
3285 $updater->setOriginalRevisionId( $target->getId() );
3286 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3287 $updater->addTags( $tags );
3289 // TODO: this logic should not be in the storage layer, it's here for compatibility
3290 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3291 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3292 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
3294 if ( $wgUseRCPatrol && $permissionManager->userCan(
3295 'autopatrol', $guser, $this->getTitle()
3297 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3300 // Actually store the rollback
3301 $rev = $updater->saveRevision(
3302 CommentStoreComment
::newUnsavedComment( $summary ),
3306 // Set patrolling and bot flag on the edits, which gets rollbacked.
3307 // This is done even on edit failure to have patrolling in that case (T64157).
3309 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3310 // Mark all reverted edits as bot
3314 if ( $wgUseRCPatrol ) {
3315 // Mark all reverted edits as patrolled
3316 $set['rc_patrolled'] = RecentChange
::PRC_AUTOPATROLLED
;
3319 if ( count( $set ) ) {
3320 $actorWhere = ActorMigration
::newMigration()->getWhere(
3323 $current->getUser( RevisionRecord
::RAW
),
3326 $dbw->update( 'recentchanges', $set,
3328 'rc_cur_id' => $current->getPageId(),
3329 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3330 $actorWhere['conds'], // No tables/joins are needed for rc_user
3336 if ( !$updater->wasSuccessful() ) {
3337 return $updater->getStatus()->getErrorsArray();
3340 // Report if the edit was not created because it did not change the content.
3341 if ( $updater->isUnchanged() ) {
3342 $resultDetails = [ 'current' => $legacyCurrent ];
3343 return [ [ 'alreadyrolled',
3344 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3345 htmlspecialchars( $fromP ),
3346 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3350 if ( $changingContentModel ) {
3351 // If the content model changed during the rollback,
3352 // make sure it gets logged to Special:Log/contentmodel
3353 $log = new ManualLogEntry( 'contentmodel', 'change' );
3354 $log->setPerformer( $guser );
3355 $log->setTarget( $this->mTitle
);
3356 $log->setComment( $summary );
3357 $log->setParameters( [
3358 '4::oldmodel' => $currentContent->getModel(),
3359 '5::newmodel' => $targetContent->getModel(),
3362 $logId = $log->insert( $dbw );
3363 $log->publish( $logId );
3366 $revId = $rev->getId();
3368 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3371 'summary' => $summary,
3372 'current' => $legacyCurrent,
3373 'target' => $legacyTarget,
3378 // TODO: make this return a Status object and wrap $resultDetails in that.
3383 * The onArticle*() functions are supposed to be a kind of hooks
3384 * which should be called whenever any of the specified actions
3387 * This is a good place to put code to clear caches, for instance.
3389 * This is called on page move and undelete, as well as edit
3391 * @param Title $title
3393 public static function onArticleCreate( Title
$title ) {
3394 // TODO: move this into a PageEventEmitter service
3396 // Update existence markers on article/talk tabs...
3397 $other = $title->getOtherPage();
3399 $other->purgeSquid();
3401 $title->touchLinks();
3402 $title->purgeSquid();
3403 $title->deleteTitleProtection();
3405 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3407 // Invalidate caches of articles which include this page
3408 DeferredUpdates
::addUpdate(
3409 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3412 if ( $title->getNamespace() == NS_CATEGORY
) {
3413 // Load the Category object, which will schedule a job to create
3414 // the category table row if necessary. Checking a replica DB is ok
3415 // here, in the worst case it'll run an unnecessary recount job on
3416 // a category that probably doesn't have many members.
3417 Category
::newFromTitle( $title )->getID();
3422 * Clears caches when article is deleted
3424 * @param Title $title
3426 public static function onArticleDelete( Title
$title ) {
3427 // TODO: move this into a PageEventEmitter service
3429 // Update existence markers on article/talk tabs...
3430 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3431 BacklinkCache
::get( $title )->clear();
3432 $other = $title->getOtherPage();
3434 $other->purgeSquid();
3436 $title->touchLinks();
3437 $title->purgeSquid();
3439 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3442 HTMLFileCache
::clearFileCache( $title );
3443 InfoAction
::invalidateCache( $title );
3446 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3447 MessageCache
::singleton()->updateMessageOverride( $title, null );
3451 if ( $title->getNamespace() == NS_FILE
) {
3452 DeferredUpdates
::addUpdate(
3453 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3458 if ( $title->getNamespace() == NS_USER_TALK
) {
3459 $user = User
::newFromName( $title->getText(), false );
3461 $user->setNewtalk( false );
3466 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3468 // Purge cross-wiki cache entities referencing this page
3469 self
::purgeInterwikiCheckKey( $title );
3473 * Purge caches on page update etc
3475 * @param Title $title
3476 * @param Revision|null $revision Revision that was just saved, may be null
3477 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3478 * If not given, all slots are assumed to have changed.
3480 public static function onArticleEdit(
3482 Revision
$revision = null,
3483 $slotsChanged = null
3485 // TODO: move this into a PageEventEmitter service
3487 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3488 // Invalidate caches of articles which include this page.
3489 // Only for the main slot, because only the main slot is transcluded.
3490 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3491 DeferredUpdates
::addUpdate(
3492 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3496 // Invalidate the caches of all pages which redirect here
3497 DeferredUpdates
::addUpdate(
3498 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3501 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3503 // Purge CDN for this page only
3504 $title->purgeSquid();
3505 // Clear file cache for this page only
3506 HTMLFileCache
::clearFileCache( $title );
3508 // Purge ?action=info cache
3509 $revid = $revision ?
$revision->getId() : null;
3510 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3511 InfoAction
::invalidateCache( $title, $revid );
3514 // Purge cross-wiki cache entities referencing this page
3515 self
::purgeInterwikiCheckKey( $title );
3521 * Purge the check key for cross-wiki cache entries referencing this page
3523 * @param Title $title
3525 private static function purgeInterwikiCheckKey( Title
$title ) {
3526 global $wgEnableScaryTranscluding;
3528 if ( !$wgEnableScaryTranscluding ) {
3529 return; // @todo: perhaps this wiki is only used as a *source* for content?
3532 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3533 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3534 $cache->resetCheckKey(
3535 // Do not include the namespace since there can be multiple aliases to it
3536 // due to different namespace text definitions on different wikis. This only
3537 // means that some cache invalidations happen that are not strictly needed.
3538 $cache->makeGlobalKey(
3540 WikiMap
::getCurrentWikiDbDomain()->getId(),
3548 * Returns a list of categories this page is a member of.
3549 * Results will include hidden categories
3551 * @return TitleArray
3553 public function getCategories() {
3554 $id = $this->getId();
3556 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3559 $dbr = wfGetDB( DB_REPLICA
);
3560 $res = $dbr->select( 'categorylinks',
3561 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3562 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3563 // as not being aliases, and NS_CATEGORY is numeric
3564 [ 'cl_from' => $id ],
3567 return TitleArray
::newFromResult( $res );
3571 * Returns a list of hidden categories this page is a member of.
3572 * Uses the page_props and categorylinks tables.
3574 * @return array Array of Title objects
3576 public function getHiddenCategories() {
3578 $id = $this->getId();
3584 $dbr = wfGetDB( DB_REPLICA
);
3585 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3587 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3588 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3591 if ( $res !== false ) {
3592 foreach ( $res as $row ) {
3593 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3601 * Auto-generates a deletion reason
3603 * @param bool &$hasHistory Whether the page has a history
3604 * @return string|bool String containing deletion reason or empty string, or boolean false
3605 * if no revision occurred
3607 public function getAutoDeleteReason( &$hasHistory ) {
3608 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3612 * Update all the appropriate counts in the category table, given that
3613 * we've added the categories $added and deleted the categories $deleted.
3615 * This should only be called from deferred updates or jobs to avoid contention.
3617 * @param array $added The names of categories that were added
3618 * @param array $deleted The names of categories that were deleted
3619 * @param int $id Page ID (this should be the original deleted page ID)
3621 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3622 $id = $id ?
: $this->getId();
3623 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
3624 getCategoryLinkType( $this->getTitle()->getNamespace() );
3626 $addFields = [ 'cat_pages = cat_pages + 1' ];
3627 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3628 if ( $type !== 'page' ) {
3629 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3630 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3633 $dbw = wfGetDB( DB_MASTER
);
3635 if ( count( $added ) ) {
3636 $existingAdded = $dbw->selectFieldValues(
3639 [ 'cat_title' => $added ],
3643 // For category rows that already exist, do a plain
3644 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3645 // to avoid creating gaps in the cat_id sequence.
3646 if ( count( $existingAdded ) ) {
3650 [ 'cat_title' => $existingAdded ],
3655 $missingAdded = array_diff( $added, $existingAdded );
3656 if ( count( $missingAdded ) ) {
3658 foreach ( $missingAdded as $cat ) {
3660 'cat_title' => $cat,
3662 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3663 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3676 if ( count( $deleted ) ) {
3680 [ 'cat_title' => $deleted ],
3685 foreach ( $added as $catName ) {
3686 $cat = Category
::newFromName( $catName );
3687 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3690 foreach ( $deleted as $catName ) {
3691 $cat = Category
::newFromName( $catName );
3692 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3693 // Refresh counts on categories that should be empty now (after commit, T166757)
3694 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3695 $cat->refreshCountsIfEmpty();
3701 * Opportunistically enqueue link update jobs given fresh parser output if useful
3703 * @param ParserOutput $parserOutput Current version page output
3706 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3707 if ( wfReadOnly() ) {
3711 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3712 [ $this, $this->mTitle
, $parserOutput ]
3717 $config = RequestContext
::getMain()->getConfig();
3720 'isOpportunistic' => true,
3721 'rootJobTimestamp' => $parserOutput->getCacheTime()
3724 if ( $this->mTitle
->areRestrictionsCascading() ) {
3725 // If the page is cascade protecting, the links should really be up-to-date
3726 JobQueueGroup
::singleton()->lazyPush(
3727 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3729 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3730 // Assume the output contains "dynamic" time/random based magic words.
3731 // Only update pages that expired due to dynamic content and NOT due to edits
3732 // to referenced templates/files. When the cache expires due to dynamic content,
3733 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3734 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3735 // template/file edit already triggered recursive RefreshLinksJob jobs.
3736 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3737 // If a page is uncacheable, do not keep spamming a job for it.
3738 // Although it would be de-duplicated, it would still waste I/O.
3739 $cache = ObjectCache
::getLocalClusterInstance();
3740 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3741 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3742 if ( $cache->add( $key, time(), $ttl ) ) {
3743 JobQueueGroup
::singleton()->lazyPush(
3744 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3752 * Returns a list of updates to be performed when this page is deleted. The
3753 * updates should remove any information about this page from secondary data
3754 * stores such as links tables.
3756 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3757 * object for backwards compatibility.
3758 * @return DeferrableUpdate[]
3760 public function getDeletionUpdates( $rev = null ) {
3762 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3765 $rev = $this->getRevisionRecord();
3766 } catch ( Exception
$ex ) {
3767 // If we can't load the content, something is wrong. Perhaps that's why
3768 // the user is trying to delete the page, so let's not fail in that case.
3769 // Note that doDeleteArticleReal() will already have logged an issue with
3770 // loading the content.
3771 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3777 } elseif ( $rev instanceof Content
) {
3778 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3780 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3782 $slotContent = array_map( function ( SlotRecord
$slot ) {
3783 return $slot->getContent( RevisionRecord
::RAW
);
3784 }, $rev->getSlots()->getSlots() );
3787 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3789 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3790 // model here, not the content object!
3791 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3792 /** @var Content $content */
3793 foreach ( $slotContent as $role => $content ) {
3794 $handler = $content->getContentHandler();
3796 $updates = $handler->getDeletionUpdates(
3800 $allUpdates = array_merge( $allUpdates, $updates );
3802 // TODO: remove B/C hack in 1.32!
3803 $legacyUpdates = $content->getDeletionUpdates( $this );
3805 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3806 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3807 return !( $update instanceof LinksDeletionUpdate
);
3810 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3813 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3815 // TODO: hard deprecate old hook in 1.33
3816 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3821 * Whether this content displayed on this page
3822 * comes from the local database
3827 public function isLocal() {
3832 * The display name for the site this content
3833 * come from. If a subclass overrides isLocal(),
3834 * this could return something other than the
3840 public function getWikiDisplayName() {
3846 * Get the source URL for the content on this page,
3847 * typically the canonical URL, but may be a remote
3848 * link if the content comes from another site
3853 public function getSourceURL() {
3854 return $this->getTitle()->getCanonicalURL();
3858 * @param WANObjectCache $cache
3862 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3863 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3865 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );