3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Revision\RevisionRenderer
;
27 use MediaWiki\Storage\DerivedPageDataUpdater
;
28 use MediaWiki\Storage\PageUpdater
;
29 use MediaWiki\Storage\RevisionRecord
;
30 use MediaWiki\Storage\RevisionSlotsUpdate
;
31 use MediaWiki\Storage\RevisionStore
;
32 use Wikimedia\Assert\Assert
;
33 use Wikimedia\Rdbms\FakeResultWrapper
;
34 use Wikimedia\Rdbms\IDatabase
;
35 use Wikimedia\Rdbms\LoadBalancer
;
38 * Class representing a MediaWiki article and history.
40 * Some fields are public only for backwards-compatibility. Use accessors.
41 * In the past, this class was part of Article.php and everything was public.
43 class WikiPage
implements Page
, IDBAccessObject
{
44 // Constants for $mDataLoadedFrom and related
49 public $mTitle = null;
54 public $mDataLoaded = false; // !< Boolean
55 public $mIsRedirect = false; // !< Boolean
56 public $mLatest = false; // !< Integer (false means "not loaded")
59 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
60 public $mPreparedEdit = false;
65 protected $mId = null;
68 * @var int One of the READ_* constants
70 protected $mDataLoadedFrom = self
::READ_NONE
;
75 protected $mRedirectTarget = null;
80 protected $mLastRevision = null;
83 * @var string Timestamp of the current revision or empty string if not loaded
85 protected $mTimestamp = '';
90 protected $mTouched = '19700101000000';
95 protected $mLinksUpdated = '19700101000000';
98 * @var DerivedPageDataUpdater|null
100 private $derivedDataUpdater = null;
103 * Constructor and clear the article
104 * @param Title $title Reference to a Title object.
106 public function __construct( Title
$title ) {
107 $this->mTitle
= $title;
111 * Makes sure that the mTitle object is cloned
112 * to the newly cloned WikiPage.
114 public function __clone() {
115 $this->mTitle
= clone $this->mTitle
;
119 * Create a WikiPage object of the appropriate class for the given title.
121 * @param Title $title
123 * @throws MWException
124 * @return WikiPage|WikiCategoryPage|WikiFilePage
126 public static function factory( Title
$title ) {
127 $ns = $title->getNamespace();
129 if ( $ns == NS_MEDIA
) {
130 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
131 } elseif ( $ns < 0 ) {
132 throw new MWException( "Invalid or virtual namespace $ns given." );
136 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
142 $page = new WikiFilePage( $title );
145 $page = new WikiCategoryPage( $title );
148 $page = new WikiPage( $title );
155 * Constructor from a page id
157 * @param int $id Article ID to load
158 * @param string|int $from One of the following values:
159 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
160 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
162 * @return WikiPage|null
164 public static function newFromID( $id, $from = 'fromdb' ) {
165 // page ids are never 0 or negative, see T63166
170 $from = self
::convertSelectType( $from );
171 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
172 $pageQuery = self
::getQueryInfo();
173 $row = $db->selectRow(
174 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
175 [], $pageQuery['joins']
180 return self
::newFromRow( $row, $from );
184 * Constructor from a database row
187 * @param object $row Database row containing at least fields returned by selectFields().
188 * @param string|int $from Source of $data:
189 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
190 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
191 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
194 public static function newFromRow( $row, $from = 'fromdb' ) {
195 $page = self
::factory( Title
::newFromRow( $row ) );
196 $page->loadFromRow( $row, $from );
201 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
203 * @param object|string|int $type
206 protected static function convertSelectType( $type ) {
209 return self
::READ_NORMAL
;
211 return self
::READ_LATEST
;
213 return self
::READ_LOCKING
;
215 // It may already be an integer or whatever else
221 * @return RevisionStore
223 private function getRevisionStore() {
224 return MediaWikiServices
::getInstance()->getRevisionStore();
228 * @return RevisionRenderer
230 private function getRevisionRenderer() {
231 return MediaWikiServices
::getInstance()->getRevisionRenderer();
235 * @return ParserCache
237 private function getParserCache() {
238 return MediaWikiServices
::getInstance()->getParserCache();
242 * @return LoadBalancer
244 private function getDBLoadBalancer() {
245 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
249 * @todo Move this UI stuff somewhere else
251 * @see ContentHandler::getActionOverrides
254 public function getActionOverrides() {
255 return $this->getContentHandler()->getActionOverrides();
259 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
261 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
263 * @return ContentHandler
267 public function getContentHandler() {
268 return ContentHandler
::getForModelID( $this->getContentModel() );
272 * Get the title object of the article
273 * @return Title Title object of this page
275 public function getTitle() {
276 return $this->mTitle
;
283 public function clear() {
284 $this->mDataLoaded
= false;
285 $this->mDataLoadedFrom
= self
::READ_NONE
;
287 $this->clearCacheFields();
291 * Clear the object cache fields
294 protected function clearCacheFields() {
296 $this->mRedirectTarget
= null; // Title object if set
297 $this->mLastRevision
= null; // Latest revision
298 $this->mTouched
= '19700101000000';
299 $this->mLinksUpdated
= '19700101000000';
300 $this->mTimestamp
= '';
301 $this->mIsRedirect
= false;
302 $this->mLatest
= false;
303 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
304 // checks the requested rev ID and content against the cached one. For most
305 // content types, the output should not change during the lifetime of this cache.
306 // Clearing it can cause extra parses on edit for no reason.
310 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
314 public function clearPreparedEdit() {
315 $this->mPreparedEdit
= false;
319 * Return the list of revision fields that should be selected to create
322 * @deprecated since 1.31, use self::getQueryInfo() instead.
325 public static function selectFields() {
326 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
328 wfDeprecated( __METHOD__
, '1.31' );
339 'page_links_updated',
344 if ( $wgContentHandlerUseDB ) {
345 $fields[] = 'page_content_model';
348 if ( $wgPageLanguageUseDB ) {
349 $fields[] = 'page_lang';
356 * Return the tables, fields, and join conditions to be selected to create
359 * @return array With three keys:
360 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
361 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
362 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
364 public static function getQueryInfo() {
365 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
368 'tables' => [ 'page' ],
378 'page_links_updated',
385 if ( $wgContentHandlerUseDB ) {
386 $ret['fields'][] = 'page_content_model';
389 if ( $wgPageLanguageUseDB ) {
390 $ret['fields'][] = 'page_lang';
397 * Fetch a page record with the given conditions
398 * @param IDatabase $dbr
399 * @param array $conditions
400 * @param array $options
401 * @return object|bool Database result resource, or false on failure
403 protected function pageData( $dbr, $conditions, $options = [] ) {
404 $pageQuery = self
::getQueryInfo();
406 // Avoid PHP 7.1 warning of passing $this by reference
409 Hooks
::run( 'ArticlePageDataBefore', [
410 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
413 $row = $dbr->selectRow(
414 $pageQuery['tables'],
415 $pageQuery['fields'],
422 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
428 * Fetch a page record matching the Title object's namespace and title
429 * using a sanitized title string
431 * @param IDatabase $dbr
432 * @param Title $title
433 * @param array $options
434 * @return object|bool Database result resource, or false on failure
436 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
437 return $this->pageData( $dbr, [
438 'page_namespace' => $title->getNamespace(),
439 'page_title' => $title->getDBkey() ], $options );
443 * Fetch a page record matching the requested ID
445 * @param IDatabase $dbr
447 * @param array $options
448 * @return object|bool Database result resource, or false on failure
450 public function pageDataFromId( $dbr, $id, $options = [] ) {
451 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
455 * Load the object from a given source by title
457 * @param object|string|int $from One of the following:
458 * - A DB query result object.
459 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
460 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
461 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
462 * using SELECT FOR UPDATE.
466 public function loadPageData( $from = 'fromdb' ) {
467 $from = self
::convertSelectType( $from );
468 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
469 // We already have the data from the correct location, no need to load it twice.
473 if ( is_int( $from ) ) {
474 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
475 $loadBalancer = $this->getDBLoadBalancer();
476 $db = $loadBalancer->getConnection( $index );
477 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
480 && $index == DB_REPLICA
481 && $loadBalancer->getServerCount() > 1
482 && $loadBalancer->hasOrMadeRecentMasterChanges()
484 $from = self
::READ_LATEST
;
485 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
486 $db = $loadBalancer->getConnection( $index );
487 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
490 // No idea from where the caller got this data, assume replica DB.
492 $from = self
::READ_NORMAL
;
495 $this->loadFromRow( $data, $from );
499 * Checks whether the page data was loaded using the given database access mode (or better).
503 * @param string|int $from One of the following:
504 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
505 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
506 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
507 * using SELECT FOR UPDATE.
511 public function wasLoadedFrom( $from ) {
512 $from = self
::convertSelectType( $from );
514 if ( !is_int( $from ) ) {
515 // No idea from where the caller got this data, assume replica DB.
516 $from = self
::READ_NORMAL
;
519 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
527 * Load the object from a database row
530 * @param object|bool $data DB row containing fields returned by selectFields() or false
531 * @param string|int $from One of the following:
532 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
533 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
534 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
535 * the master DB using SELECT FOR UPDATE
537 public function loadFromRow( $data, $from ) {
538 $lc = MediaWikiServices
::getInstance()->getLinkCache();
539 $lc->clearLink( $this->mTitle
);
542 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
544 $this->mTitle
->loadFromRow( $data );
546 // Old-fashioned restrictions
547 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
549 $this->mId
= intval( $data->page_id
);
550 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
551 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
552 $this->mIsRedirect
= intval( $data->page_is_redirect
);
553 $this->mLatest
= intval( $data->page_latest
);
554 // T39225: $latest may no longer match the cached latest Revision object.
555 // Double-check the ID of any cached latest Revision object for consistency.
556 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
557 $this->mLastRevision
= null;
558 $this->mTimestamp
= '';
561 $lc->addBadLinkObj( $this->mTitle
);
563 $this->mTitle
->loadFromRow( false );
565 $this->clearCacheFields();
570 $this->mDataLoaded
= true;
571 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
575 * @return int Page ID
577 public function getId() {
578 if ( !$this->mDataLoaded
) {
579 $this->loadPageData();
585 * @return bool Whether or not the page exists in the database
587 public function exists() {
588 if ( !$this->mDataLoaded
) {
589 $this->loadPageData();
591 return $this->mId
> 0;
595 * Check if this page is something we're going to be showing
596 * some sort of sensible content for. If we return false, page
597 * views (plain action=view) will return an HTTP 404 response,
598 * so spiders and robots can know they're following a bad link.
602 public function hasViewableContent() {
603 return $this->mTitle
->isKnown();
607 * Tests if the article content represents a redirect
611 public function isRedirect() {
612 if ( !$this->mDataLoaded
) {
613 $this->loadPageData();
616 return (bool)$this->mIsRedirect
;
620 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
622 * Will use the revisions actual content model if the page exists,
623 * and the page's default if the page doesn't exist yet.
629 public function getContentModel() {
630 if ( $this->exists() ) {
631 $cache = ObjectCache
::getMainWANInstance();
633 return $cache->getWithSetCallback(
634 $cache->makeKey( 'page-content-model', $this->getLatest() ),
637 $rev = $this->getRevision();
639 // Look at the revision's actual content model
640 return $rev->getContentModel();
642 $title = $this->mTitle
->getPrefixedDBkey();
643 wfWarn( "Page $title exists but has no (visible) revisions!" );
644 return $this->mTitle
->getContentModel();
650 // use the default model for this page
651 return $this->mTitle
->getContentModel();
655 * Loads page_touched and returns a value indicating if it should be used
656 * @return bool True if this page exists and is not a redirect
658 public function checkTouched() {
659 if ( !$this->mDataLoaded
) {
660 $this->loadPageData();
662 return ( $this->mId
&& !$this->mIsRedirect
);
666 * Get the page_touched field
667 * @return string Containing GMT timestamp
669 public function getTouched() {
670 if ( !$this->mDataLoaded
) {
671 $this->loadPageData();
673 return $this->mTouched
;
677 * Get the page_links_updated field
678 * @return string|null Containing GMT timestamp
680 public function getLinksTimestamp() {
681 if ( !$this->mDataLoaded
) {
682 $this->loadPageData();
684 return $this->mLinksUpdated
;
688 * Get the page_latest field
689 * @return int The rev_id of current revision
691 public function getLatest() {
692 if ( !$this->mDataLoaded
) {
693 $this->loadPageData();
695 return (int)$this->mLatest
;
699 * Get the Revision object of the oldest revision
700 * @return Revision|null
702 public function getOldestRevision() {
703 // Try using the replica DB first, then try the master
704 $rev = $this->mTitle
->getFirstRevision();
706 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
712 * Loads everything except the text
713 * This isn't necessary for all uses, so it's only done if needed.
715 protected function loadLastEdit() {
716 if ( $this->mLastRevision
!== null ) {
717 return; // already loaded
720 $latest = $this->getLatest();
722 return; // page doesn't exist or is missing page_latest info
725 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
726 // T39225: if session S1 loads the page row FOR UPDATE, the result always
727 // includes the latest changes committed. This is true even within REPEATABLE-READ
728 // transactions, where S1 normally only sees changes committed before the first S1
729 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
730 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
731 // happened after the first S1 SELECT.
732 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
733 $flags = Revision
::READ_LOCKING
;
734 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
735 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
736 // Bug T93976: if page_latest was loaded from the master, fetch the
737 // revision from there as well, as it may not exist yet on a replica DB.
738 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
739 $flags = Revision
::READ_LATEST
;
740 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
742 $dbr = wfGetDB( DB_REPLICA
);
743 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
746 if ( $revision ) { // sanity
747 $this->setLastEdit( $revision );
752 * Set the latest revision
753 * @param Revision $revision
755 protected function setLastEdit( Revision
$revision ) {
756 $this->mLastRevision
= $revision;
757 $this->mTimestamp
= $revision->getTimestamp();
761 * Get the latest revision
762 * @return Revision|null
764 public function getRevision() {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
;
773 * Get the latest revision
774 * @return RevisionRecord|null
776 public function getRevisionRecord() {
777 $this->loadLastEdit();
778 if ( $this->mLastRevision
) {
779 return $this->mLastRevision
->getRevisionRecord();
785 * Get the content of the current revision. No side-effects...
787 * @param int $audience One of:
788 * Revision::FOR_PUBLIC to be displayed to all users
789 * Revision::FOR_THIS_USER to be displayed to $wgUser
790 * Revision::RAW get the text regardless of permissions
791 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
792 * to the $audience parameter
793 * @return Content|null The content of the current revision
797 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
798 $this->loadLastEdit();
799 if ( $this->mLastRevision
) {
800 return $this->mLastRevision
->getContent( $audience, $user );
806 * @return string MW timestamp of last article revision
808 public function getTimestamp() {
809 // Check if the field has been filled by WikiPage::setTimestamp()
810 if ( !$this->mTimestamp
) {
811 $this->loadLastEdit();
814 return wfTimestamp( TS_MW
, $this->mTimestamp
);
818 * Set the page timestamp (use only to avoid DB queries)
819 * @param string $ts MW timestamp of last article revision
822 public function setTimestamp( $ts ) {
823 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
827 * @param int $audience One of:
828 * Revision::FOR_PUBLIC to be displayed to all users
829 * Revision::FOR_THIS_USER to be displayed to the given user
830 * Revision::RAW get the text regardless of permissions
831 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
832 * to the $audience parameter
833 * @return int User ID for the user that made the last article revision
835 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
836 $this->loadLastEdit();
837 if ( $this->mLastRevision
) {
838 return $this->mLastRevision
->getUser( $audience, $user );
845 * Get the User object of the user who created the page
846 * @param int $audience One of:
847 * Revision::FOR_PUBLIC to be displayed to all users
848 * Revision::FOR_THIS_USER to be displayed to the given user
849 * Revision::RAW get the text regardless of permissions
850 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
851 * to the $audience parameter
854 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
855 $revision = $this->getOldestRevision();
857 $userName = $revision->getUserText( $audience, $user );
858 return User
::newFromName( $userName, false );
865 * @param int $audience One of:
866 * Revision::FOR_PUBLIC to be displayed to all users
867 * Revision::FOR_THIS_USER to be displayed to the given user
868 * Revision::RAW get the text regardless of permissions
869 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
870 * to the $audience parameter
871 * @return string Username of the user that made the last article revision
873 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
874 $this->loadLastEdit();
875 if ( $this->mLastRevision
) {
876 return $this->mLastRevision
->getUserText( $audience, $user );
883 * @param int $audience One of:
884 * Revision::FOR_PUBLIC to be displayed to all users
885 * Revision::FOR_THIS_USER to be displayed to the given user
886 * Revision::RAW get the text regardless of permissions
887 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
888 * to the $audience parameter
889 * @return string Comment stored for the last article revision
891 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
892 $this->loadLastEdit();
893 if ( $this->mLastRevision
) {
894 return $this->mLastRevision
->getComment( $audience, $user );
901 * Returns true if last revision was marked as "minor edit"
903 * @return bool Minor edit indicator for the last article revision.
905 public function getMinorEdit() {
906 $this->loadLastEdit();
907 if ( $this->mLastRevision
) {
908 return $this->mLastRevision
->isMinor();
915 * Determine whether a page would be suitable for being counted as an
916 * article in the site_stats table based on the title & its content
918 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
919 * if false, the current database state will be used
922 public function isCountable( $editInfo = false ) {
923 global $wgArticleCountMethod;
925 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
927 if ( !$this->mTitle
->isContentPage() ) {
932 // NOTE: only the main slot can make a page a redirect
933 $content = $editInfo->pstContent
;
935 $content = $this->getContent();
938 if ( !$content ||
$content->isRedirect() ) {
944 if ( $wgArticleCountMethod === 'link' ) {
945 // nasty special case to avoid re-parsing to detect links
948 // ParserOutput::getLinks() is a 2D array of page links, so
949 // to be really correct we would need to recurse in the array
950 // but the main array should only have items in it if there are
952 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
954 // NOTE: keep in sync with revisionRenderer::getLinkCount
955 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
956 [ 'pl_from' => $this->getId() ], __METHOD__
);
960 return $content->isCountable( $hasLinks );
964 * If this page is a redirect, get its target
966 * The target will be fetched from the redirect table if possible.
967 * If this page doesn't have an entry there, call insertRedirect()
968 * @return Title|null Title object, or null if this page is not a redirect
970 public function getRedirectTarget() {
971 if ( !$this->mTitle
->isRedirect() ) {
975 if ( $this->mRedirectTarget
!== null ) {
976 return $this->mRedirectTarget
;
979 // Query the redirect table
980 $dbr = wfGetDB( DB_REPLICA
);
981 $row = $dbr->selectRow( 'redirect',
982 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
983 [ 'rd_from' => $this->getId() ],
987 // rd_fragment and rd_interwiki were added later, populate them if empty
988 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
989 $this->mRedirectTarget
= Title
::makeTitle(
990 $row->rd_namespace
, $row->rd_title
,
991 $row->rd_fragment
, $row->rd_interwiki
993 return $this->mRedirectTarget
;
996 // This page doesn't have an entry in the redirect table
997 $this->mRedirectTarget
= $this->insertRedirect();
998 return $this->mRedirectTarget
;
1002 * Insert an entry for this page into the redirect table if the content is a redirect
1004 * The database update will be deferred via DeferredUpdates
1006 * Don't call this function directly unless you know what you're doing.
1007 * @return Title|null Title object or null if not a redirect
1009 public function insertRedirect() {
1010 $content = $this->getContent();
1011 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1016 // Update the DB post-send if the page has not cached since now
1017 $latest = $this->getLatest();
1018 DeferredUpdates
::addCallableUpdate(
1019 function () use ( $retval, $latest ) {
1020 $this->insertRedirectEntry( $retval, $latest );
1022 DeferredUpdates
::POSTSEND
,
1023 wfGetDB( DB_MASTER
)
1030 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1031 * @param Title $rt Redirect target
1032 * @param int|null $oldLatest Prior page_latest for check and set
1034 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1035 $dbw = wfGetDB( DB_MASTER
);
1036 $dbw->startAtomic( __METHOD__
);
1038 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1042 'rd_from' => $this->getId(),
1043 'rd_namespace' => $rt->getNamespace(),
1044 'rd_title' => $rt->getDBkey(),
1045 'rd_fragment' => $rt->getFragment(),
1046 'rd_interwiki' => $rt->getInterwiki(),
1050 'rd_namespace' => $rt->getNamespace(),
1051 'rd_title' => $rt->getDBkey(),
1052 'rd_fragment' => $rt->getFragment(),
1053 'rd_interwiki' => $rt->getInterwiki(),
1059 $dbw->endAtomic( __METHOD__
);
1063 * Get the Title object or URL this page redirects to
1065 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1067 public function followRedirect() {
1068 return $this->getRedirectURL( $this->getRedirectTarget() );
1072 * Get the Title object or URL to use for a redirect. We use Title
1073 * objects for same-wiki, non-special redirects and URLs for everything
1075 * @param Title $rt Redirect target
1076 * @return bool|Title|string False, Title object of local target, or string with URL
1078 public function getRedirectURL( $rt ) {
1083 if ( $rt->isExternal() ) {
1084 if ( $rt->isLocal() ) {
1085 // Offsite wikis need an HTTP redirect.
1086 // This can be hard to reverse and may produce loops,
1087 // so they may be disabled in the site configuration.
1088 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1089 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1091 // External pages without "local" bit set are not valid
1097 if ( $rt->isSpecialPage() ) {
1098 // Gotta handle redirects to special pages differently:
1099 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1100 // Some pages are not valid targets.
1101 if ( $rt->isValidRedirectTarget() ) {
1102 return $rt->getFullURL();
1112 * Get a list of users who have edited this article, not including the user who made
1113 * the most recent revision, which you can get from $article->getUser() if you want it
1114 * @return UserArrayFromResult
1116 public function getContributors() {
1117 // @todo: This is expensive; cache this info somewhere.
1119 $dbr = wfGetDB( DB_REPLICA
);
1121 $actorMigration = ActorMigration
::newMigration();
1122 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1124 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1127 'user_id' => $actorQuery['fields']['rev_user'],
1128 'user_name' => $actorQuery['fields']['rev_user_text'],
1129 'actor_id' => $actorQuery['fields']['rev_actor'],
1130 'user_real_name' => 'MIN(user_real_name)',
1131 'timestamp' => 'MAX(rev_timestamp)',
1134 $conds = [ 'rev_page' => $this->getId() ];
1136 // The user who made the top revision gets credited as "this page was last edited by
1137 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1138 $user = $this->getUser()
1139 ? User
::newFromId( $this->getUser() )
1140 : User
::newFromName( $this->getUserText(), false );
1141 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1144 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1147 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1148 ] +
$actorQuery['joins'];
1151 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1152 'ORDER BY' => 'timestamp DESC',
1155 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1156 return new UserArrayFromResult( $res );
1160 * Should the parser cache be used?
1162 * @param ParserOptions $parserOptions ParserOptions to check
1166 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1167 return $parserOptions->getStubThreshold() == 0
1169 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1170 && $this->getContentHandler()->isParserCacheSupported();
1174 * Get a ParserOutput for the given ParserOptions and revision ID.
1176 * The parser cache will be used if possible. Cache misses that result
1177 * in parser runs are debounced with PoolCounter.
1179 * XXX merge this with updateParserCache()?
1182 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1183 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1184 * get the current revision (default value)
1185 * @param bool $forceParse Force reindexing, regardless of cache settings
1186 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1188 public function getParserOutput(
1189 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1192 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1194 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1195 throw new InvalidArgumentException(
1196 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1200 wfDebug( __METHOD__
.
1201 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1202 if ( $parserOptions->getStubThreshold() ) {
1203 wfIncrStats( 'pcache.miss.stub' );
1206 if ( $useParserCache ) {
1207 $parserOutput = $this->getParserCache()
1208 ->get( $this, $parserOptions );
1209 if ( $parserOutput !== false ) {
1210 return $parserOutput;
1214 if ( $oldid === null ||
$oldid === 0 ) {
1215 $oldid = $this->getLatest();
1218 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1221 return $pool->getParserOutput();
1225 * Do standard deferred updates after page view (existing or missing page)
1226 * @param User $user The relevant user
1227 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1229 public function doViewUpdates( User
$user, $oldid = 0 ) {
1230 if ( wfReadOnly() ) {
1234 // Update newtalk / watchlist notification status;
1235 // Avoid outage if the master is not reachable by using a deferred updated
1236 DeferredUpdates
::addCallableUpdate(
1237 function () use ( $user, $oldid ) {
1238 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1240 $user->clearNotification( $this->mTitle
, $oldid );
1242 DeferredUpdates
::PRESEND
1247 * Perform the actions of a page purging
1249 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1250 * controlled how much purging was done.
1252 public function doPurge() {
1253 // Avoid PHP 7.1 warning of passing $this by reference
1256 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1260 $this->mTitle
->invalidateCache();
1263 HTMLFileCache
::clearFileCache( $this->getTitle() );
1264 // Send purge after above page_touched update was committed
1265 DeferredUpdates
::addUpdate(
1266 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1267 DeferredUpdates
::PRESEND
1270 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1271 $messageCache = MessageCache
::singleton();
1272 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1279 * Insert a new empty page record for this article.
1280 * This *must* be followed up by creating a revision
1281 * and running $this->updateRevisionOn( ... );
1282 * or else the record will be left in a funky state.
1283 * Best if all done inside a transaction.
1285 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1287 * @param IDatabase $dbw
1288 * @param int|null $pageId Custom page ID that will be used for the insert statement
1290 * @return bool|int The newly created page_id key; false if the row was not
1291 * inserted, e.g. because the title already existed or because the specified
1292 * page ID is already in use.
1294 public function insertOn( $dbw, $pageId = null ) {
1295 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1299 'page_namespace' => $this->mTitle
->getNamespace(),
1300 'page_title' => $this->mTitle
->getDBkey(),
1301 'page_restrictions' => '',
1302 'page_is_redirect' => 0, // Will set this shortly...
1304 'page_random' => wfRandom(),
1305 'page_touched' => $dbw->timestamp(),
1306 'page_latest' => 0, // Fill this in shortly...
1307 'page_len' => 0, // Fill this in shortly...
1308 ] +
$pageIdForInsert,
1313 if ( $dbw->affectedRows() > 0 ) {
1314 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1315 $this->mId
= $newid;
1316 $this->mTitle
->resetArticleID( $newid );
1320 return false; // nothing changed
1325 * Update the page record to point to a newly saved revision.
1327 * @todo Factor out into a PageStore service, or move into PageUpdater.
1329 * @param IDatabase $dbw
1330 * @param Revision $revision For ID number, and text used to set
1331 * length and redirect status fields
1332 * @param int|null $lastRevision If given, will not overwrite the page field
1333 * when different from the currently set value.
1334 * Giving 0 indicates the new page flag should be set on.
1335 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1336 * removing rows in redirect table.
1337 * @return bool Success; false if the page row was missing or page_latest changed
1339 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1340 $lastRevIsRedirect = null
1342 global $wgContentHandlerUseDB;
1344 // TODO: move into PageUpdater or PageStore
1345 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1346 // and in the compat stub!
1348 // Assertion to try to catch T92046
1349 if ( (int)$revision->getId() === 0 ) {
1350 throw new InvalidArgumentException(
1351 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1355 $content = $revision->getContent();
1356 $len = $content ?
$content->getSize() : 0;
1357 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1359 $conditions = [ 'page_id' => $this->getId() ];
1361 if ( !is_null( $lastRevision ) ) {
1362 // An extra check against threads stepping on each other
1363 $conditions['page_latest'] = $lastRevision;
1366 $revId = $revision->getId();
1367 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1370 'page_latest' => $revId,
1371 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1372 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1373 'page_is_redirect' => $rt !== null ?
1 : 0,
1377 if ( $wgContentHandlerUseDB ) {
1378 $row['page_content_model'] = $revision->getContentModel();
1381 $dbw->update( 'page',
1386 $result = $dbw->affectedRows() > 0;
1388 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1389 $this->setLastEdit( $revision );
1390 $this->mLatest
= $revision->getId();
1391 $this->mIsRedirect
= (bool)$rt;
1392 // Update the LinkCache.
1393 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1394 $linkCache->addGoodLinkObj(
1400 $revision->getContentModel()
1408 * Add row to the redirect table if this is a redirect, remove otherwise.
1410 * @param IDatabase $dbw
1411 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1412 * or NULL if this is not a redirect
1413 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1414 * removing rows in redirect table.
1415 * @return bool True on success, false on failure
1418 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1419 // Always update redirects (target link might have changed)
1420 // Update/Insert if we don't know if the last revision was a redirect or not
1421 // Delete if changing from redirect to non-redirect
1422 $isRedirect = !is_null( $redirectTitle );
1424 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1428 if ( $isRedirect ) {
1429 $this->insertRedirectEntry( $redirectTitle );
1431 // This is not a redirect, remove row from redirect table
1432 $where = [ 'rd_from' => $this->getId() ];
1433 $dbw->delete( 'redirect', $where, __METHOD__
);
1436 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1437 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1440 return ( $dbw->affectedRows() != 0 );
1444 * If the given revision is newer than the currently set page_latest,
1445 * update the page record. Otherwise, do nothing.
1447 * @deprecated since 1.24, use updateRevisionOn instead
1449 * @param IDatabase $dbw
1450 * @param Revision $revision
1453 public function updateIfNewerOn( $dbw, $revision ) {
1454 $row = $dbw->selectRow(
1455 [ 'revision', 'page' ],
1456 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1458 'page_id' => $this->getId(),
1459 'page_latest=rev_id' ],
1463 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1466 $prev = $row->rev_id
;
1467 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1469 // No or missing previous revision; mark the page as new
1471 $lastRevIsRedirect = null;
1474 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1480 * Helper method for checking whether two revisions have differences that go
1481 * beyond the main slot.
1483 * MCR migration note: this method should go away!
1485 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1487 * @param Revision $a
1488 * @param Revision $b
1491 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1492 $aSlots = $a->getRevisionRecord()->getSlots();
1493 $bSlots = $b->getRevisionRecord()->getSlots();
1494 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1496 return ( $changedRoles !== [ 'main' ] && $changedRoles !== [] );
1500 * Get the content that needs to be saved in order to undo all revisions
1501 * between $undo and $undoafter. Revisions must belong to the same page,
1502 * must exist and must not be deleted
1504 * @param Revision $undo
1505 * @param Revision $undoafter Must be an earlier revision than $undo
1506 * @return Content|bool Content on success, false on failure
1508 * Before we had the Content object, this was done in getUndoText
1510 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1511 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1513 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1514 // Cannot yet undo edits that involve anything other the main slot.
1518 $handler = $undo->getContentHandler();
1519 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1523 * Returns true if this page's content model supports sections.
1527 * @todo The skin should check this and not offer section functionality if
1528 * sections are not supported.
1529 * @todo The EditPage should check this and not offer section functionality
1530 * if sections are not supported.
1532 public function supportsSections() {
1533 return $this->getContentHandler()->supportsSections();
1537 * @param string|int|null|bool $sectionId Section identifier as a number or string
1538 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1539 * or 'new' for a new section.
1540 * @param Content $sectionContent New content of the section.
1541 * @param string $sectionTitle New section's subject, only if $section is "new".
1542 * @param string $edittime Revision timestamp or null to use the current revision.
1544 * @throws MWException
1545 * @return Content|null New complete article content, or null if error.
1548 * @deprecated since 1.24, use replaceSectionAtRev instead
1550 public function replaceSectionContent(
1551 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1554 if ( $edittime && $sectionId !== 'new' ) {
1555 $lb = $this->getDBLoadBalancer();
1556 $dbr = $lb->getConnection( DB_REPLICA
);
1557 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1558 // Try the master if this thread may have just added it.
1559 // This could be abstracted into a Revision method, but we don't want
1560 // to encourage loading of revisions by timestamp.
1562 && $lb->getServerCount() > 1
1563 && $lb->hasOrMadeRecentMasterChanges()
1565 $dbw = $lb->getConnection( DB_MASTER
);
1566 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1569 $baseRevId = $rev->getId();
1573 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1577 * @param string|int|null|bool $sectionId Section identifier as a number or string
1578 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1579 * or 'new' for a new section.
1580 * @param Content $sectionContent New content of the section.
1581 * @param string $sectionTitle New section's subject, only if $section is "new".
1582 * @param int|null $baseRevId
1584 * @throws MWException
1585 * @return Content|null New complete article content, or null if error.
1589 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1590 $sectionTitle = '', $baseRevId = null
1592 if ( strval( $sectionId ) === '' ) {
1593 // Whole-page edit; let the whole text through
1594 $newContent = $sectionContent;
1596 if ( !$this->supportsSections() ) {
1597 throw new MWException( "sections not supported for content model " .
1598 $this->getContentHandler()->getModelID() );
1601 // T32711: always use current version when adding a new section
1602 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1603 $oldContent = $this->getContent();
1605 $rev = Revision
::newFromId( $baseRevId );
1607 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1608 $this->getId() . "; section: $sectionId)\n" );
1612 $oldContent = $rev->getContent();
1615 if ( !$oldContent ) {
1616 wfDebug( __METHOD__
. ": no page text\n" );
1620 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1627 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1629 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1630 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1633 * @return int Updated $flags
1635 public function checkFlags( $flags ) {
1636 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1637 if ( $this->exists() ) {
1638 $flags |
= EDIT_UPDATE
;
1648 * @return DerivedPageDataUpdater
1650 private function newDerivedDataUpdater() {
1651 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1653 $derivedDataUpdater = new DerivedPageDataUpdater(
1654 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1655 $this->getRevisionStore(),
1656 $this->getRevisionRenderer(),
1657 $this->getParserCache(),
1658 JobQueueGroup
::singleton(),
1659 MessageCache
::singleton(),
1660 MediaWikiServices
::getInstance()->getContentLanguage(),
1661 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1664 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1665 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1667 return $derivedDataUpdater;
1671 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1672 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1673 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1674 * returned matches that caller's expectations, allowing an existing instance to be re-used
1675 * if the given parameters match that instance's internal state according to
1676 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1677 * match the existign one.
1679 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1680 * created, replacing any DerivedPageDataUpdater currently cached.
1682 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1686 * @param User|null $forUser The user that will be used for, or was used for, PST.
1687 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1688 * to perform updates, if the edit was already saved.
1689 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1690 * if the edit was not yet saved.
1691 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1692 * revision as the edit's parent revision. This ensures that the same
1693 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1695 * @return DerivedPageDataUpdater
1697 private function getDerivedDataUpdater(
1698 User
$forUser = null,
1699 RevisionRecord
$forRevision = null,
1700 RevisionSlotsUpdate
$forUpdate = null,
1703 if ( !$forRevision && !$forUpdate ) {
1704 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1705 // going to use it with.
1706 $this->derivedDataUpdater
= null;
1709 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1710 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1711 // to it did not yet initialize it, because we don't know what data it will be
1712 // initialized with.
1713 $this->derivedDataUpdater
= null;
1716 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1717 // However, there is no good way to construct a cache key. We'd need to check against all
1718 // cached instances.
1720 if ( $this->derivedDataUpdater
1721 && !$this->derivedDataUpdater
->isReusableFor(
1725 $forEdit ?
$this->getLatest() : null
1728 $this->derivedDataUpdater
= null;
1731 if ( !$this->derivedDataUpdater
) {
1732 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1735 return $this->derivedDataUpdater
;
1739 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1741 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1742 * and to protected such conflict resolution from concurrent edits using a check-and-set
1748 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1749 * that may already have been returned via getDerivedDataUpdater to be re-used.
1751 * @return PageUpdater
1753 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1754 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1756 $pageUpdater = new PageUpdater(
1758 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1759 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1760 $this->getDBLoadBalancer(),
1761 $this->getRevisionStore()
1764 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1765 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1766 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1768 return $pageUpdater;
1772 * Change an existing article or create a new article. Updates RC and all necessary caches,
1773 * optionally via the deferred update array.
1775 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1776 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1777 * apply the autopatrol right as appropriate.
1779 * @param Content $content New content
1780 * @param string|CommentStoreComment $summary Edit summary
1781 * @param int $flags Bitfield:
1783 * Article is known or assumed to be non-existent, create a new one
1785 * Article is known or assumed to be pre-existing, update it
1787 * Mark this edit minor, if the user is allowed to do so
1789 * Do not log the change in recentchanges
1791 * Mark the edit a "bot" edit regardless of user rights
1793 * Fill in blank summaries with generated text where possible
1795 * Signal that the page retrieve/save cycle happened entirely in this request.
1797 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1798 * article will be detected. If EDIT_UPDATE is specified and the article
1799 * doesn't exist, the function will return an edit-gone-missing error. If
1800 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1801 * error will be returned. These two conditions are also possible with
1802 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1804 * @param bool|int $originalRevId: The ID of an original revision that the edit
1805 * restores or repeats. The new revision is expected to have the exact same content as
1806 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1807 * which are created to record things like page moves.
1808 * @param User|null $user The user doing the edit
1809 * @param string|null $serialFormat IGNORED.
1810 * @param array|null $tags Change tags to apply to this edit
1811 * Callers are responsible for permission checks
1812 * (with ChangeTags::canAddTagsAccompanyingChange)
1813 * @param Int $undidRevId Id of revision that was undone or 0
1815 * @throws MWException
1816 * @return Status Possible errors:
1817 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1818 * set the fatal flag of $status.
1819 * edit-gone-missing: In update mode, but the article didn't exist.
1820 * edit-conflict: In update mode, the article changed unexpectedly.
1821 * edit-no-change: Warning that the text was the same as before.
1822 * edit-already-exists: In creation mode, but the article already exists.
1824 * Extensions may define additional errors.
1826 * $return->value will contain an associative array with members as follows:
1827 * new: Boolean indicating if the function attempted to create a new article.
1828 * revision: The revision object for the inserted revision, or null.
1831 * @throws MWException
1833 public function doEditContent(
1834 Content
$content, $summary, $flags = 0, $originalRevId = false,
1835 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1837 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1839 if ( !( $summary instanceof CommentStoreComment
) ) {
1840 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1847 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1848 // Checking the minoredit right should be done in the same place the 'bot' right is
1849 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1850 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1851 $flags = ( $flags & ~EDIT_MINOR
);
1854 $slotsUpdate = new RevisionSlotsUpdate();
1855 $slotsUpdate->modifyContent( 'main', $content );
1857 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1858 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1859 // used by this PageUpdater. However, there is no guarantee for this.
1860 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1861 $updater->setContent( 'main', $content );
1862 $updater->setOriginalRevisionId( $originalRevId );
1863 $updater->setUndidRevisionId( $undidRevId );
1865 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1867 // TODO: this logic should not be in the storage layer, it's here for compatibility
1868 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1869 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1870 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1871 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1874 $updater->addTags( $tags );
1876 $revRec = $updater->saveRevision(
1881 // $revRec will be null if the edit failed, or if no new revision was created because
1882 // the content did not change.
1884 // update cached fields
1885 // TODO: this is currently redundant to what is done in updateRevisionOn.
1886 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1887 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1888 $this->mLatest
= $revRec->getId();
1891 return $updater->getStatus();
1895 * Get parser options suitable for rendering the primary article wikitext
1897 * @see ParserOptions::newCanonical
1899 * @param IContextSource|User|string $context One of the following:
1900 * - IContextSource: Use the User and the Language of the provided
1902 * - User: Use the provided User object and $wgLang for the language,
1903 * so use an IContextSource object if possible.
1904 * - 'canonical': Canonical options (anonymous user with default
1905 * preferences and content language).
1906 * @return ParserOptions
1908 public function makeParserOptions( $context ) {
1909 $options = ParserOptions
::newCanonical( $context );
1911 if ( $this->getTitle()->isConversionTable() ) {
1912 // @todo ConversionTable should become a separate content model, so
1913 // we don't need special cases like this one.
1914 $options->disableContentConversion();
1921 * Prepare content which is about to be saved.
1923 * Prior to 1.30, this returned a stdClass.
1925 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1927 * @param Content $content
1928 * @param Revision|RevisionRecord|int|null $revision Revision object.
1929 * For backwards compatibility, a revision ID is also accepted,
1930 * but this is deprecated.
1931 * Used with vary-revision or vary-revision-id.
1932 * @param User|null $user
1933 * @param string|null $serialFormat IGNORED
1934 * @param bool $useCache Check shared prepared edit cache
1936 * @return PreparedEdit
1940 public function prepareContentForEdit(
1944 $serialFormat = null,
1953 if ( !is_object( $revision ) ) {
1955 // This code path is deprecated, and nothing is known to
1956 // use it, so performance here shouldn't be a worry.
1957 if ( $revid !== null ) {
1958 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1959 $store = $this->getRevisionStore();
1960 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1964 } elseif ( $revision instanceof Revision
) {
1965 $revision = $revision->getRevisionRecord();
1968 $slots = RevisionSlotsUpdate
::newFromContent( [ 'main' => $content ] );
1969 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1971 if ( !$updater->isUpdatePrepared() ) {
1972 $updater->prepareContent( $user, $slots, $useCache );
1975 $updater->prepareUpdate(
1978 'causeAction' => 'prepare-edit',
1979 'causeAgent' => $user->getName(),
1985 return $updater->getPreparedEdit();
1989 * Do standard deferred updates after page edit.
1990 * Update links tables, site stats, search index and message cache.
1991 * Purges pages that include this page if the text was changed here.
1992 * Every 100th edit, prune the recent changes table.
1994 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
1996 * @param Revision $revision
1997 * @param User $user User object that did the revision
1998 * @param array $options Array of options, following indexes are used:
1999 * - changed: bool, whether the revision changed the content (default true)
2000 * - created: bool, whether the revision created the page (default false)
2001 * - moved: bool, whether the page was moved (default false)
2002 * - restored: bool, whether the page was undeleted (default false)
2003 * - oldrevision: Revision object for the pre-update revision (default null)
2004 * - oldcountable: bool, null, or string 'no-change' (default null):
2005 * - bool: whether the page was counted as an article before that
2006 * revision, only used in changed is true and created is false
2007 * - null: if created is false, don't update the article count; if created
2008 * is true, do update the article count
2009 * - 'no-change': don't update the article count, ever
2010 * - causeAction: an arbitrary string identifying the reason for the update.
2011 * See DataUpdate::getCauseAction(). (default 'edit-page')
2012 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2013 * (string, defaults to the passed user)
2015 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2017 'causeAction' => 'edit-page',
2018 'causeAgent' => $user->getName(),
2021 $revision = $revision->getRevisionRecord();
2023 $updater = $this->getDerivedDataUpdater( $user, $revision );
2025 $updater->prepareUpdate( $revision, $options );
2027 $updater->doUpdates();
2031 * Update the parser cache.
2033 * @note This is a temporary workaround until there is a proper data updater class.
2034 * It will become deprecated soon.
2036 * @param array $options
2037 * - causeAction: an arbitrary string identifying the reason for the update.
2038 * See DataUpdate::getCauseAction(). (default 'edit-page')
2039 * - causeAgent: name of the user who caused the update (string, defaults to the
2040 * user who created the revision)
2043 public function updateParserCache( array $options = [] ) {
2044 $revision = $this->getRevisionRecord();
2045 if ( !$revision ||
!$revision->getId() ) {
2046 LoggerFactory
::getInstance( 'wikipage' )->info(
2047 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2051 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2053 $updater = $this->getDerivedDataUpdater( $user, $revision );
2054 $updater->prepareUpdate( $revision, $options );
2055 $updater->doParserCacheUpdate();
2059 * Do secondary data updates (such as updating link tables).
2060 * Secondary data updates are only a small part of the updates needed after saving
2061 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2062 * secondary data updates). This method is provided for partial purges.
2064 * @note This is a temporary workaround until there is a proper data updater class.
2065 * It will become deprecated soon.
2067 * @param array $options
2068 * - recursive (bool, default true): whether to do a recursive update (update pages that
2069 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2070 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2071 * was something that did not really change the page, such as a null edit.
2072 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2073 * user who created the revision)
2074 * - causeAction: an arbitrary string identifying the reason for the update.
2075 * See DataUpdate::getCauseAction(). (default 'unknown')
2076 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2077 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2078 * Note that even when this is set to false, some updates might still get deferred (as
2079 * some update might directly add child updates to DeferredUpdates).
2080 * - transactionTicket: a transaction ticket from LBFactory::getEmptyTransactionTicket(),
2081 * only when defer is false (default: null)
2084 public function doSecondaryDataUpdates( array $options = [] ) {
2085 $options['recursive'] = $options['recursive'] ??
true;
2086 $revision = $this->getRevisionRecord();
2087 if ( !$revision ||
!$revision->getId() ) {
2088 LoggerFactory
::getInstance( 'wikipage' )->info(
2089 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2093 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2095 $updater = $this->getDerivedDataUpdater( $user, $revision );
2096 $updater->prepareUpdate( $revision, $options );
2097 $updater->doSecondaryDataUpdates( $options );
2101 * Update the article's restriction field, and leave a log entry.
2102 * This works for protection both existing and non-existing pages.
2104 * @param array $limit Set of restriction keys
2105 * @param array $expiry Per restriction type expiration
2106 * @param int &$cascade Set to false if cascading protection isn't allowed.
2107 * @param string $reason
2108 * @param User $user The user updating the restrictions
2109 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2110 * ($user should be able to add the specified tags before this is called)
2111 * @return Status Status object; if action is taken, $status->value is the log_id of the
2112 * protection log entry.
2114 public function doUpdateRestrictions( array $limit, array $expiry,
2115 &$cascade, $reason, User
$user, $tags = null
2117 global $wgCascadingRestrictionLevels;
2119 if ( wfReadOnly() ) {
2120 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2123 $this->loadPageData( 'fromdbmaster' );
2124 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2125 $id = $this->getId();
2131 // Take this opportunity to purge out expired restrictions
2132 Title
::purgeExpiredRestrictions();
2134 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2135 // we expect a single selection, but the schema allows otherwise.
2136 $isProtected = false;
2140 $dbw = wfGetDB( DB_MASTER
);
2142 foreach ( $restrictionTypes as $action ) {
2143 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2144 $expiry[$action] = 'infinity';
2146 if ( !isset( $limit[$action] ) ) {
2147 $limit[$action] = '';
2148 } elseif ( $limit[$action] != '' ) {
2152 // Get current restrictions on $action
2153 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2154 if ( $current != '' ) {
2155 $isProtected = true;
2158 if ( $limit[$action] != $current ) {
2160 } elseif ( $limit[$action] != '' ) {
2161 // Only check expiry change if the action is actually being
2162 // protected, since expiry does nothing on an not-protected
2164 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2170 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2174 // If nothing has changed, do nothing
2176 return Status
::newGood();
2179 if ( !$protect ) { // No protection at all means unprotection
2180 $revCommentMsg = 'unprotectedarticle-comment';
2181 $logAction = 'unprotect';
2182 } elseif ( $isProtected ) {
2183 $revCommentMsg = 'modifiedarticleprotection-comment';
2184 $logAction = 'modify';
2186 $revCommentMsg = 'protectedarticle-comment';
2187 $logAction = 'protect';
2190 $logRelationsValues = [];
2191 $logRelationsField = null;
2192 $logParamsDetails = [];
2194 // Null revision (used for change tag insertion)
2195 $nullRevision = null;
2197 if ( $id ) { // Protection of existing page
2198 // Avoid PHP 7.1 warning of passing $this by reference
2201 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2202 return Status
::newGood();
2205 // Only certain restrictions can cascade...
2206 $editrestriction = isset( $limit['edit'] )
2207 ?
[ $limit['edit'] ]
2208 : $this->mTitle
->getRestrictions( 'edit' );
2209 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2210 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2212 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2213 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2216 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2217 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2218 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2220 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2221 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2224 // The schema allows multiple restrictions
2225 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2229 // insert null revision to identify the page protection change as edit summary
2230 $latest = $this->getLatest();
2231 $nullRevision = $this->insertProtectNullRevision(
2240 if ( $nullRevision === null ) {
2241 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2244 $logRelationsField = 'pr_id';
2246 // Update restrictions table
2247 foreach ( $limit as $action => $restrictions ) {
2249 'page_restrictions',
2252 'pr_type' => $action
2256 if ( $restrictions != '' ) {
2257 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2259 'page_restrictions',
2262 'pr_type' => $action,
2263 'pr_level' => $restrictions,
2264 'pr_cascade' => $cascadeValue,
2265 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2269 $logRelationsValues[] = $dbw->insertId();
2270 $logParamsDetails[] = [
2272 'level' => $restrictions,
2273 'expiry' => $expiry[$action],
2274 'cascade' => (bool)$cascadeValue,
2279 // Clear out legacy restriction fields
2282 [ 'page_restrictions' => '' ],
2283 [ 'page_id' => $id ],
2287 // Avoid PHP 7.1 warning of passing $this by reference
2290 Hooks
::run( 'NewRevisionFromEditComplete',
2291 [ $this, $nullRevision, $latest, $user ] );
2292 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2293 } else { // Protection of non-existing page (also known as "title protection")
2294 // Cascade protection is meaningless in this case
2297 if ( $limit['create'] != '' ) {
2298 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2299 $dbw->replace( 'protected_titles',
2300 [ [ 'pt_namespace', 'pt_title' ] ],
2302 'pt_namespace' => $this->mTitle
->getNamespace(),
2303 'pt_title' => $this->mTitle
->getDBkey(),
2304 'pt_create_perm' => $limit['create'],
2305 'pt_timestamp' => $dbw->timestamp(),
2306 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2307 'pt_user' => $user->getId(),
2308 ] +
$commentFields, __METHOD__
2310 $logParamsDetails[] = [
2312 'level' => $limit['create'],
2313 'expiry' => $expiry['create'],
2316 $dbw->delete( 'protected_titles',
2318 'pt_namespace' => $this->mTitle
->getNamespace(),
2319 'pt_title' => $this->mTitle
->getDBkey()
2325 $this->mTitle
->flushRestrictions();
2326 InfoAction
::invalidateCache( $this->mTitle
);
2328 if ( $logAction == 'unprotect' ) {
2331 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2333 '4::description' => $protectDescriptionLog, // parameter for IRC
2334 '5:bool:cascade' => $cascade,
2335 'details' => $logParamsDetails, // parameter for localize and api
2339 // Update the protection log
2340 $logEntry = new ManualLogEntry( 'protect', $logAction );
2341 $logEntry->setTarget( $this->mTitle
);
2342 $logEntry->setComment( $reason );
2343 $logEntry->setPerformer( $user );
2344 $logEntry->setParameters( $params );
2345 if ( !is_null( $nullRevision ) ) {
2346 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2348 $logEntry->setTags( $tags );
2349 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2350 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2352 $logId = $logEntry->insert();
2353 $logEntry->publish( $logId );
2355 return Status
::newGood( $logId );
2359 * Insert a new null revision for this page.
2361 * @param string $revCommentMsg Comment message key for the revision
2362 * @param array $limit Set of restriction keys
2363 * @param array $expiry Per restriction type expiration
2364 * @param int $cascade Set to false if cascading protection isn't allowed.
2365 * @param string $reason
2366 * @param User|null $user
2367 * @return Revision|null Null on error
2369 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2370 array $expiry, $cascade, $reason, $user = null
2372 $dbw = wfGetDB( DB_MASTER
);
2374 // Prepare a null revision to be added to the history
2375 $editComment = wfMessage(
2377 $this->mTitle
->getPrefixedText(),
2378 $user ?
$user->getName() : ''
2379 )->inContentLanguage()->text();
2381 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2383 $protectDescription = $this->protectDescription( $limit, $expiry );
2384 if ( $protectDescription ) {
2385 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2386 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2387 ->inContentLanguage()->text();
2390 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2391 $editComment .= wfMessage( 'brackets' )->params(
2392 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2393 )->inContentLanguage()->text();
2396 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2398 $nullRev->insertOn( $dbw );
2400 // Update page record and touch page
2401 $oldLatest = $nullRev->getParentId();
2402 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2409 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2412 protected function formatExpiry( $expiry ) {
2413 if ( $expiry != 'infinity' ) {
2414 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2417 $contLang->timeanddate( $expiry, false, false ),
2418 $contLang->date( $expiry, false, false ),
2419 $contLang->time( $expiry, false, false )
2420 )->inContentLanguage()->text();
2422 return wfMessage( 'protect-expiry-indefinite' )
2423 ->inContentLanguage()->text();
2428 * Builds the description to serve as comment for the edit.
2430 * @param array $limit Set of restriction keys
2431 * @param array $expiry Per restriction type expiration
2434 public function protectDescription( array $limit, array $expiry ) {
2435 $protectDescription = '';
2437 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2438 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2439 # All possible message keys are listed here for easier grepping:
2440 # * restriction-create
2441 # * restriction-edit
2442 # * restriction-move
2443 # * restriction-upload
2444 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2445 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2446 # with '' filtered out. All possible message keys are listed below:
2447 # * protect-level-autoconfirmed
2448 # * protect-level-sysop
2449 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2450 ->inContentLanguage()->text();
2452 $expiryText = $this->formatExpiry( $expiry[$action] );
2454 if ( $protectDescription !== '' ) {
2455 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2457 $protectDescription .= wfMessage( 'protect-summary-desc' )
2458 ->params( $actionText, $restrictionsText, $expiryText )
2459 ->inContentLanguage()->text();
2462 return $protectDescription;
2466 * Builds the description to serve as comment for the log entry.
2468 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2469 * protect description text. Keep them in old format to avoid breaking compatibility.
2470 * TODO: Fix protection log to store structured description and format it on-the-fly.
2472 * @param array $limit Set of restriction keys
2473 * @param array $expiry Per restriction type expiration
2476 public function protectDescriptionLog( array $limit, array $expiry ) {
2477 $protectDescriptionLog = '';
2479 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2480 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2481 $expiryText = $this->formatExpiry( $expiry[$action] );
2482 $protectDescriptionLog .=
2484 "[$action=$restrictions] ($expiryText)";
2487 return trim( $protectDescriptionLog );
2491 * Take an array of page restrictions and flatten it to a string
2492 * suitable for insertion into the page_restrictions field.
2494 * @param string[] $limit
2496 * @throws MWException
2499 protected static function flattenRestrictions( $limit ) {
2500 if ( !is_array( $limit ) ) {
2501 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2507 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2508 $bits[] = "$action=$restrictions";
2511 return implode( ':', $bits );
2515 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2516 * backwards compatibility, if you care about error reporting you should use
2517 * doDeleteArticleReal() instead.
2519 * Deletes the article with database consistency, writes logs, purges caches
2521 * @param string $reason Delete reason for deletion log
2522 * @param bool $suppress Suppress all revisions and log the deletion in
2523 * the suppression log instead of the deletion log
2524 * @param int|null $u1 Unused
2525 * @param bool|null $u2 Unused
2526 * @param array|string &$error Array of errors to append to
2527 * @param User|null $user The deleting user
2528 * @return bool True if successful
2530 public function doDeleteArticle(
2531 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2533 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2534 return $status->isGood();
2538 * Back-end article deletion
2539 * Deletes the article with database consistency, writes logs, purges caches
2543 * @param string $reason Delete reason for deletion log
2544 * @param bool $suppress Suppress all revisions and log the deletion in
2545 * the suppression log instead of the deletion log
2546 * @param int|null $u1 Unused
2547 * @param bool|null $u2 Unused
2548 * @param array|string &$error Array of errors to append to
2549 * @param User|null $deleter The deleting user
2550 * @param array $tags Tags to apply to the deletion action
2551 * @param string $logsubtype
2552 * @return Status Status object; if successful, $status->value is the log_id of the
2553 * deletion log entry. If the page couldn't be deleted because it wasn't
2554 * found, $status is a non-fatal 'cannotdelete' error
2556 public function doDeleteArticleReal(
2557 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2558 $tags = [], $logsubtype = 'delete'
2560 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage,
2561 $wgActorTableSchemaMigrationStage, $wgMultiContentRevisionSchemaMigrationStage;
2563 wfDebug( __METHOD__
. "\n" );
2565 $status = Status
::newGood();
2567 if ( $this->mTitle
->getDBkey() === '' ) {
2568 $status->error( 'cannotdelete',
2569 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2573 // Avoid PHP 7.1 warning of passing $this by reference
2576 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2577 if ( !Hooks
::run( 'ArticleDelete',
2578 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2580 if ( $status->isOK() ) {
2581 // Hook aborted but didn't set a fatal status
2582 $status->fatal( 'delete-hook-aborted' );
2587 $dbw = wfGetDB( DB_MASTER
);
2588 $dbw->startAtomic( __METHOD__
);
2590 $this->loadPageData( self
::READ_LATEST
);
2591 $id = $this->getId();
2592 // T98706: lock the page from various other updates but avoid using
2593 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2594 // the revisions queries (which also JOIN on user). Only lock the page
2595 // row and CAS check on page_latest to see if the trx snapshot matches.
2596 $lockedLatest = $this->lockAndGetLatest();
2597 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2598 $dbw->endAtomic( __METHOD__
);
2599 // Page not there or trx snapshot is stale
2600 $status->error( 'cannotdelete',
2601 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2605 // Given the lock above, we can be confident in the title and page ID values
2606 $namespace = $this->getTitle()->getNamespace();
2607 $dbKey = $this->getTitle()->getDBkey();
2609 // At this point we are now comitted to returning an OK
2610 // status unless some DB query error or other exception comes up.
2611 // This way callers don't have to call rollback() if $status is bad
2612 // unless they actually try to catch exceptions (which is rare).
2614 // we need to remember the old content so we can use it to generate all deletion updates.
2615 $revision = $this->getRevision();
2617 $content = $this->getContent( Revision
::RAW
);
2618 } catch ( Exception
$ex ) {
2619 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2620 . $ex->getMessage() );
2625 $commentStore = CommentStore
::getStore();
2626 $actorMigration = ActorMigration
::newMigration();
2628 $revQuery = Revision
::getQueryInfo();
2631 // Bitfields to further suppress the content
2633 $bitfield = Revision
::SUPPRESSED_ALL
;
2634 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2637 // For now, shunt the revision data into the archive table.
2638 // Text is *not* removed from the text table; bulk storage
2639 // is left intact to avoid breaking block-compression or
2640 // immutable storage schemes.
2641 // In the future, we may keep revisions and mark them with
2642 // the rev_deleted field, which is reserved for this purpose.
2644 // Lock rows in `revision` and its temp tables, but not any others.
2645 // Note array_intersect() preserves keys from the first arg, and we're
2646 // assuming $revQuery has `revision` primary and isn't using subtables
2647 // for anything we care about.
2648 $dbw->lockForUpdate(
2650 $revQuery['tables'],
2651 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2653 [ 'rev_page' => $id ],
2659 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2660 // so we can copy it to the archive table.
2661 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2662 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2663 $revQuery['fields'][] = 'rev_text_id';
2665 if ( $wgContentHandlerUseDB ) {
2666 $revQuery['fields'][] = 'rev_content_model';
2667 $revQuery['fields'][] = 'rev_content_format';
2671 // Get all of the page revisions
2672 $res = $dbw->select(
2673 $revQuery['tables'],
2674 $revQuery['fields'],
2675 [ 'rev_page' => $id ],
2681 // Build their equivalent archive rows
2685 /** @var int[] Revision IDs of edits that were made by IPs */
2688 foreach ( $res as $row ) {
2689 $comment = $commentStore->getComment( 'rev_comment', $row );
2690 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2692 'ar_namespace' => $namespace,
2693 'ar_title' => $dbKey,
2694 'ar_timestamp' => $row->rev_timestamp
,
2695 'ar_minor_edit' => $row->rev_minor_edit
,
2696 'ar_rev_id' => $row->rev_id
,
2697 'ar_parent_id' => $row->rev_parent_id
,
2699 * ar_text_id should probably not be written to when the multi content schema has
2700 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2701 * default for the field in WMF production currently so we must keep writing
2702 * writing until a default of 0 is set.
2703 * Task: https://phabricator.wikimedia.org/T190148
2704 * Copying the value from the revision table should not lead to any issues for now.
2706 'ar_len' => $row->rev_len
,
2707 'ar_page_id' => $id,
2708 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2709 'ar_sha1' => $row->rev_sha1
,
2710 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2711 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2713 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2714 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2716 if ( $wgContentHandlerUseDB ) {
2717 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2718 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2722 $rowsInsert[] = $rowInsert;
2723 $revids[] = $row->rev_id
;
2725 // Keep track of IP edits, so that the corresponding rows can
2726 // be deleted in the ip_changes table.
2727 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2728 $ipRevIds[] = $row->rev_id
;
2731 // Copy them into the archive table
2732 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2733 // Save this so we can pass it to the ArticleDeleteComplete hook.
2734 $archivedRevisionCount = $dbw->affectedRows();
2736 // Clone the title and wikiPage, so we have the information we need when
2737 // we log and run the ArticleDeleteComplete hook.
2738 $logTitle = clone $this->mTitle
;
2739 $wikiPageBeforeDelete = clone $this;
2741 // Now that it's safely backed up, delete it
2742 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2743 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2744 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2745 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2747 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
2748 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2751 // Also delete records from ip_changes as applicable.
2752 if ( count( $ipRevIds ) > 0 ) {
2753 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2756 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2757 $logtype = $suppress ?
'suppress' : 'delete';
2759 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2760 $logEntry->setPerformer( $deleter );
2761 $logEntry->setTarget( $logTitle );
2762 $logEntry->setComment( $reason );
2763 $logEntry->setTags( $tags );
2764 $logid = $logEntry->insert();
2766 $dbw->onTransactionPreCommitOrIdle(
2767 function () use ( $logEntry, $logid ) {
2768 // T58776: avoid deadlocks (especially from FileDeleteForm)
2769 $logEntry->publish( $logid );
2774 $dbw->endAtomic( __METHOD__
);
2776 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2778 Hooks
::run( 'ArticleDeleteComplete', [
2779 &$wikiPageBeforeDelete,
2785 $archivedRevisionCount
2787 $status->value
= $logid;
2789 // Show log excerpt on 404 pages rather than just a link
2790 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2791 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2792 $cache->set( $key, 1, $cache::TTL_DAY
);
2798 * Lock the page row for this title+id and return page_latest (or 0)
2800 * @return int Returns 0 if no row was found with this title+id
2803 public function lockAndGetLatest() {
2804 return (int)wfGetDB( DB_MASTER
)->selectField(
2808 'page_id' => $this->getId(),
2809 // Typically page_id is enough, but some code might try to do
2810 // updates assuming the title is the same, so verify that
2811 'page_namespace' => $this->getTitle()->getNamespace(),
2812 'page_title' => $this->getTitle()->getDBkey()
2820 * Do some database updates after deletion
2822 * @param int $id The page_id value of the page being deleted
2823 * @param Content|null $content Optional page content to be used when determining
2824 * the required updates. This may be needed because $this->getContent()
2825 * may already return null when the page proper was deleted.
2826 * @param Revision|null $revision The latest page revision
2827 * @param User|null $user The user that caused the deletion
2829 public function doDeleteUpdates(
2830 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2833 $countable = $this->isCountable();
2834 } catch ( Exception
$ex ) {
2835 // fallback for deleting broken pages for which we cannot load the content for
2836 // some reason. Note that doDeleteArticleReal() already logged this problem.
2840 // Update site status
2841 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2842 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2845 // Delete pagelinks, update secondary indexes, etc
2846 $updates = $this->getDeletionUpdates( $content );
2847 foreach ( $updates as $update ) {
2848 DeferredUpdates
::addUpdate( $update );
2851 $causeAgent = $user ?
$user->getName() : 'unknown';
2852 // Reparse any pages transcluding this page
2853 LinksUpdate
::queueRecursiveJobsForTable(
2854 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
2855 // Reparse any pages including this image
2856 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2857 LinksUpdate
::queueRecursiveJobsForTable(
2858 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
2862 self
::onArticleDelete( $this->mTitle
);
2863 ResourceLoaderWikiModule
::invalidateModuleCache(
2864 $this->mTitle
, $revision, null, wfWikiID()
2867 // Reset this object and the Title object
2868 $this->loadFromRow( false, self
::READ_LATEST
);
2871 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2875 * Roll back the most recent consecutive set of edits to a page
2876 * from the same user; fails if there are no eligible edits to
2877 * roll back to, e.g. user is the sole contributor. This function
2878 * performs permissions checks on $user, then calls commitRollback()
2879 * to do the dirty work
2881 * @todo Separate the business/permission stuff out from backend code
2882 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2884 * @param string $fromP Name of the user whose edits to rollback.
2885 * @param string $summary Custom summary. Set to default summary if empty.
2886 * @param string $token Rollback token.
2887 * @param bool $bot If true, mark all reverted edits as bot.
2889 * @param array &$resultDetails Array contains result-specific array of additional values
2890 * 'alreadyrolled' : 'current' (rev)
2891 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2893 * @param User $user The user performing the rollback
2894 * @param array|null $tags Change tags to apply to the rollback
2895 * Callers are responsible for permission checks
2896 * (with ChangeTags::canAddTagsAccompanyingChange)
2898 * @return array Array of errors, each error formatted as
2899 * array(messagekey, param1, param2, ...).
2900 * On success, the array is empty. This array can also be passed to
2901 * OutputPage::showPermissionsErrorPage().
2903 public function doRollback(
2904 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
2906 $resultDetails = null;
2908 // Check permissions
2909 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2910 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2911 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2913 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
2914 $errors[] = [ 'sessionfailure' ];
2917 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2918 $errors[] = [ 'actionthrottledtext' ];
2921 // If there were errors, bail out now
2922 if ( !empty( $errors ) ) {
2926 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
2930 * Backend implementation of doRollback(), please refer there for parameter
2931 * and return value documentation
2933 * NOTE: This function does NOT check ANY permissions, it just commits the
2934 * rollback to the DB. Therefore, you should only call this function direct-
2935 * ly if you want to use custom permissions checks. If you don't, use
2936 * doRollback() instead.
2937 * @param string $fromP Name of the user whose edits to rollback.
2938 * @param string $summary Custom summary. Set to default summary if empty.
2939 * @param bool $bot If true, mark all reverted edits as bot.
2941 * @param array &$resultDetails Contains result-specific array of additional values
2942 * @param User $guser The user performing the rollback
2943 * @param array|null $tags Change tags to apply to the rollback
2944 * Callers are responsible for permission checks
2945 * (with ChangeTags::canAddTagsAccompanyingChange)
2947 * @return array An array of error messages, as returned by Status::getErrorsArray()
2949 public function commitRollback( $fromP, $summary, $bot,
2950 &$resultDetails, User
$guser, $tags = null
2952 global $wgUseRCPatrol;
2954 $dbw = wfGetDB( DB_MASTER
);
2956 if ( wfReadOnly() ) {
2957 return [ [ 'readonlytext' ] ];
2960 // Begin revision creation cycle by creating a PageUpdater.
2961 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
2962 $updater = $this->newPageUpdater( $guser );
2963 $current = $updater->grabParentRevision();
2965 if ( is_null( $current ) ) {
2966 // Something wrong... no page?
2967 return [ [ 'notanarticle' ] ];
2970 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
2971 $legacyCurrent = new Revision( $current );
2972 $from = str_replace( '_', ' ', $fromP );
2974 // User name given should match up with the top revision.
2975 // If the revision's user is not visible, then $from should be empty.
2976 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
2977 $resultDetails = [ 'current' => $legacyCurrent ];
2978 return [ [ 'alreadyrolled',
2979 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2980 htmlspecialchars( $fromP ),
2981 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
2985 // Get the last edit not by this person...
2986 // Note: these may not be public values
2987 $actorWhere = ActorMigration
::newMigration()->getWhere(
2990 $current->getUser( RevisionRecord
::RAW
)
2993 $s = $dbw->selectRow(
2994 [ 'revision' ] +
$actorWhere['tables'],
2995 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
2997 'rev_page' => $current->getPageId(),
2998 'NOT(' . $actorWhere['conds'] . ')',
3002 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3003 'ORDER BY' => 'rev_timestamp DESC'
3005 $actorWhere['joins']
3007 if ( $s === false ) {
3008 // No one else ever edited this page
3009 return [ [ 'cantrollback' ] ];
3010 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3011 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3013 // Only admins can see this text
3014 return [ [ 'notvisiblerev' ] ];
3017 // Generate the edit summary if necessary
3018 $target = $this->getRevisionStore()->getRevisionById(
3020 RevisionStore
::READ_LATEST
3022 if ( empty( $summary ) ) {
3023 if ( !$currentEditorForPublic ) { // no public user name
3024 $summary = wfMessage( 'revertpage-nouser' );
3026 $summary = wfMessage( 'revertpage' );
3029 $legacyTarget = new Revision( $target );
3030 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3032 // Allow the custom summary to use the same args as the default message
3033 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3035 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3036 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3038 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3040 $contLang->timeanddate( $current->getTimestamp() )
3042 if ( $summary instanceof Message
) {
3043 $summary = $summary->params( $args )->inContentLanguage()->text();
3045 $summary = wfMsgReplaceArgs( $summary, $args );
3048 // Trim spaces on user supplied text
3049 $summary = trim( $summary );
3052 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3054 if ( $guser->isAllowed( 'minoredit' ) ) {
3055 $flags |
= EDIT_MINOR
;
3058 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3059 $flags |
= EDIT_FORCE_BOT
;
3062 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3063 $currentContent = $current->getContent( 'main' );
3064 $targetContent = $target->getContent( 'main' );
3065 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3067 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3068 $tags[] = 'mw-rollback';
3071 // Build rollback revision:
3072 // Restore old content
3073 // TODO: MCR: test this once we can store multiple slots
3074 foreach ( $target->getSlots()->getSlots() as $slot ) {
3075 $updater->inheritSlot( $slot );
3078 // Remove extra slots
3079 // TODO: MCR: test this once we can store multiple slots
3080 foreach ( $current->getSlotRoles() as $role ) {
3081 if ( !$target->hasSlot( $role ) ) {
3082 $updater->removeSlot( $role );
3086 $updater->setOriginalRevisionId( $target->getId() );
3087 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3088 $updater->addTags( $tags );
3090 // TODO: this logic should not be in the storage layer, it's here for compatibility
3091 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3092 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3093 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
3094 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3097 // Actually store the rollback
3098 $rev = $updater->saveRevision(
3099 CommentStoreComment
::newUnsavedComment( $summary ),
3103 // Set patrolling and bot flag on the edits, which gets rollbacked.
3104 // This is done even on edit failure to have patrolling in that case (T64157).
3106 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3107 // Mark all reverted edits as bot
3111 if ( $wgUseRCPatrol ) {
3112 // Mark all reverted edits as patrolled
3113 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3116 if ( count( $set ) ) {
3117 $actorWhere = ActorMigration
::newMigration()->getWhere(
3120 $current->getUser( RevisionRecord
::RAW
),
3123 $dbw->update( 'recentchanges', $set,
3125 'rc_cur_id' => $current->getPageId(),
3126 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3127 $actorWhere['conds'], // No tables/joins are needed for rc_user
3133 if ( !$updater->wasSuccessful() ) {
3134 return $updater->getStatus()->getErrorsArray();
3137 // Report if the edit was not created because it did not change the content.
3138 if ( $updater->isUnchanged() ) {
3139 $resultDetails = [ 'current' => $legacyCurrent ];
3140 return [ [ 'alreadyrolled',
3141 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3142 htmlspecialchars( $fromP ),
3143 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3147 if ( $changingContentModel ) {
3148 // If the content model changed during the rollback,
3149 // make sure it gets logged to Special:Log/contentmodel
3150 $log = new ManualLogEntry( 'contentmodel', 'change' );
3151 $log->setPerformer( $guser );
3152 $log->setTarget( $this->mTitle
);
3153 $log->setComment( $summary );
3154 $log->setParameters( [
3155 '4::oldmodel' => $currentContent->getModel(),
3156 '5::newmodel' => $targetContent->getModel(),
3159 $logId = $log->insert( $dbw );
3160 $log->publish( $logId );
3163 $revId = $rev->getId();
3165 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3168 'summary' => $summary,
3169 'current' => $legacyCurrent,
3170 'target' => $legacyTarget,
3175 // TODO: make this return a Status object and wrap $resultDetails in that.
3180 * The onArticle*() functions are supposed to be a kind of hooks
3181 * which should be called whenever any of the specified actions
3184 * This is a good place to put code to clear caches, for instance.
3186 * This is called on page move and undelete, as well as edit
3188 * @param Title $title
3190 public static function onArticleCreate( Title
$title ) {
3191 // TODO: move this into a PageEventEmitter service
3193 // Update existence markers on article/talk tabs...
3194 $other = $title->getOtherPage();
3196 $other->purgeSquid();
3198 $title->touchLinks();
3199 $title->purgeSquid();
3200 $title->deleteTitleProtection();
3202 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3204 // Invalidate caches of articles which include this page
3205 DeferredUpdates
::addUpdate(
3206 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3209 if ( $title->getNamespace() == NS_CATEGORY
) {
3210 // Load the Category object, which will schedule a job to create
3211 // the category table row if necessary. Checking a replica DB is ok
3212 // here, in the worst case it'll run an unnecessary recount job on
3213 // a category that probably doesn't have many members.
3214 Category
::newFromTitle( $title )->getID();
3219 * Clears caches when article is deleted
3221 * @param Title $title
3223 public static function onArticleDelete( Title
$title ) {
3224 // TODO: move this into a PageEventEmitter service
3226 // Update existence markers on article/talk tabs...
3227 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3228 BacklinkCache
::get( $title )->clear();
3229 $other = $title->getOtherPage();
3231 $other->purgeSquid();
3233 $title->touchLinks();
3234 $title->purgeSquid();
3236 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3239 HTMLFileCache
::clearFileCache( $title );
3240 InfoAction
::invalidateCache( $title );
3243 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3244 MessageCache
::singleton()->updateMessageOverride( $title, null );
3248 if ( $title->getNamespace() == NS_FILE
) {
3249 DeferredUpdates
::addUpdate(
3250 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3255 if ( $title->getNamespace() == NS_USER_TALK
) {
3256 $user = User
::newFromName( $title->getText(), false );
3258 $user->setNewtalk( false );
3263 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3265 // Purge cross-wiki cache entities referencing this page
3266 self
::purgeInterwikiCheckKey( $title );
3270 * Purge caches on page update etc
3272 * @param Title $title
3273 * @param Revision|null $revision Revision that was just saved, may be null
3274 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3275 * If not given, all slots are assumed to have changed.
3277 public static function onArticleEdit(
3279 Revision
$revision = null,
3280 $slotsChanged = null
3282 // TODO: move this into a PageEventEmitter service
3284 if ( $slotsChanged === null ||
in_array( 'main', $slotsChanged ) ) {
3285 // Invalidate caches of articles which include this page.
3286 // Only for the main slot, because only the main slot is transcluded.
3287 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3288 DeferredUpdates
::addUpdate(
3289 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3293 // Invalidate the caches of all pages which redirect here
3294 DeferredUpdates
::addUpdate(
3295 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3298 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3300 // Purge CDN for this page only
3301 $title->purgeSquid();
3302 // Clear file cache for this page only
3303 HTMLFileCache
::clearFileCache( $title );
3305 // Purge ?action=info cache
3306 $revid = $revision ?
$revision->getId() : null;
3307 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3308 InfoAction
::invalidateCache( $title, $revid );
3311 // Purge cross-wiki cache entities referencing this page
3312 self
::purgeInterwikiCheckKey( $title );
3318 * Purge the check key for cross-wiki cache entries referencing this page
3320 * @param Title $title
3322 private static function purgeInterwikiCheckKey( Title
$title ) {
3323 global $wgEnableScaryTranscluding;
3325 if ( !$wgEnableScaryTranscluding ) {
3326 return; // @todo: perhaps this wiki is only used as a *source* for content?
3329 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3330 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3331 $cache->resetCheckKey(
3332 // Do not include the namespace since there can be multiple aliases to it
3333 // due to different namespace text definitions on different wikis. This only
3334 // means that some cache invalidations happen that are not strictly needed.
3335 $cache->makeGlobalKey( 'interwiki-page', wfWikiID(), $title->getDBkey() )
3341 * Returns a list of categories this page is a member of.
3342 * Results will include hidden categories
3344 * @return TitleArray
3346 public function getCategories() {
3347 $id = $this->getId();
3349 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3352 $dbr = wfGetDB( DB_REPLICA
);
3353 $res = $dbr->select( 'categorylinks',
3354 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3355 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3356 // as not being aliases, and NS_CATEGORY is numeric
3357 [ 'cl_from' => $id ],
3360 return TitleArray
::newFromResult( $res );
3364 * Returns a list of hidden categories this page is a member of.
3365 * Uses the page_props and categorylinks tables.
3367 * @return array Array of Title objects
3369 public function getHiddenCategories() {
3371 $id = $this->getId();
3377 $dbr = wfGetDB( DB_REPLICA
);
3378 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3380 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3381 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3384 if ( $res !== false ) {
3385 foreach ( $res as $row ) {
3386 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3394 * Auto-generates a deletion reason
3396 * @param bool &$hasHistory Whether the page has a history
3397 * @return string|bool String containing deletion reason or empty string, or boolean false
3398 * if no revision occurred
3400 public function getAutoDeleteReason( &$hasHistory ) {
3401 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3405 * Update all the appropriate counts in the category table, given that
3406 * we've added the categories $added and deleted the categories $deleted.
3408 * This should only be called from deferred updates or jobs to avoid contention.
3410 * @param array $added The names of categories that were added
3411 * @param array $deleted The names of categories that were deleted
3412 * @param int $id Page ID (this should be the original deleted page ID)
3414 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3415 $id = $id ?
: $this->getId();
3416 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3418 $addFields = [ 'cat_pages = cat_pages + 1' ];
3419 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3420 if ( $type !== 'page' ) {
3421 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3422 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3425 $dbw = wfGetDB( DB_MASTER
);
3427 if ( count( $added ) ) {
3428 $existingAdded = $dbw->selectFieldValues(
3431 [ 'cat_title' => $added ],
3435 // For category rows that already exist, do a plain
3436 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3437 // to avoid creating gaps in the cat_id sequence.
3438 if ( count( $existingAdded ) ) {
3442 [ 'cat_title' => $existingAdded ],
3447 $missingAdded = array_diff( $added, $existingAdded );
3448 if ( count( $missingAdded ) ) {
3450 foreach ( $missingAdded as $cat ) {
3452 'cat_title' => $cat,
3454 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3455 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3468 if ( count( $deleted ) ) {
3472 [ 'cat_title' => $deleted ],
3477 foreach ( $added as $catName ) {
3478 $cat = Category
::newFromName( $catName );
3479 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3482 foreach ( $deleted as $catName ) {
3483 $cat = Category
::newFromName( $catName );
3484 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3485 // Refresh counts on categories that should be empty now (after commit, T166757)
3486 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3487 $cat->refreshCountsIfEmpty();
3493 * Opportunistically enqueue link update jobs given fresh parser output if useful
3495 * @param ParserOutput $parserOutput Current version page output
3498 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3499 if ( wfReadOnly() ) {
3503 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3504 [ $this, $this->mTitle
, $parserOutput ]
3509 $config = RequestContext
::getMain()->getConfig();
3512 'isOpportunistic' => true,
3513 'rootJobTimestamp' => $parserOutput->getCacheTime()
3516 if ( $this->mTitle
->areRestrictionsCascading() ) {
3517 // If the page is cascade protecting, the links should really be up-to-date
3518 JobQueueGroup
::singleton()->lazyPush(
3519 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3521 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3522 // Assume the output contains "dynamic" time/random based magic words.
3523 // Only update pages that expired due to dynamic content and NOT due to edits
3524 // to referenced templates/files. When the cache expires due to dynamic content,
3525 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3526 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3527 // template/file edit already triggered recursive RefreshLinksJob jobs.
3528 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3529 // If a page is uncacheable, do not keep spamming a job for it.
3530 // Although it would be de-duplicated, it would still waste I/O.
3531 $cache = ObjectCache
::getLocalClusterInstance();
3532 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3533 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3534 if ( $cache->add( $key, time(), $ttl ) ) {
3535 JobQueueGroup
::singleton()->lazyPush(
3536 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3544 * Returns a list of updates to be performed when this page is deleted. The
3545 * updates should remove any information about this page from secondary data
3546 * stores such as links tables.
3548 * @param Content|null $content Optional Content object for determining the
3549 * necessary updates.
3550 * @return DeferrableUpdate[]
3552 public function getDeletionUpdates( Content
$content = null ) {
3554 // load content object, which may be used to determine the necessary updates.
3555 // XXX: the content may not be needed to determine the updates.
3557 $content = $this->getContent( Revision
::RAW
);
3558 } catch ( Exception
$ex ) {
3559 // If we can't load the content, something is wrong. Perhaps that's why
3560 // the user is trying to delete the page, so let's not fail in that case.
3561 // Note that doDeleteArticleReal() will already have logged an issue with
3562 // loading the content.
3569 $updates = $content->getDeletionUpdates( $this );
3572 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3577 * Whether this content displayed on this page
3578 * comes from the local database
3583 public function isLocal() {
3588 * The display name for the site this content
3589 * come from. If a subclass overrides isLocal(),
3590 * this could return something other than the
3596 public function getWikiDisplayName() {
3602 * Get the source URL for the content on this page,
3603 * typically the canonical URL, but may be a remote
3604 * link if the content comes from another site
3609 public function getSourceURL() {
3610 return $this->getTitle()->getCanonicalURL();
3614 * @param WANObjectCache $cache
3618 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3619 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3621 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );