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\Storage\DerivedPageDataUpdater
;
27 use MediaWiki\Storage\PageUpdater
;
28 use MediaWiki\Storage\RevisionRecord
;
29 use MediaWiki\Storage\RevisionSlotsUpdate
;
30 use MediaWiki\Storage\RevisionStore
;
31 use Wikimedia\Assert\Assert
;
32 use Wikimedia\Rdbms\FakeResultWrapper
;
33 use Wikimedia\Rdbms\IDatabase
;
34 use Wikimedia\Rdbms\LoadBalancer
;
37 * Class representing a MediaWiki article and history.
39 * Some fields are public only for backwards-compatibility. Use accessors.
40 * In the past, this class was part of Article.php and everything was public.
42 class WikiPage
implements Page
, IDBAccessObject
{
43 // Constants for $mDataLoadedFrom and related
48 public $mTitle = null;
53 public $mDataLoaded = false; // !< Boolean
54 public $mIsRedirect = false; // !< Boolean
55 public $mLatest = false; // !< Integer (false means "not loaded")
58 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
59 public $mPreparedEdit = false;
64 protected $mId = null;
67 * @var int One of the READ_* constants
69 protected $mDataLoadedFrom = self
::READ_NONE
;
74 protected $mRedirectTarget = null;
79 protected $mLastRevision = null;
82 * @var string Timestamp of the current revision or empty string if not loaded
84 protected $mTimestamp = '';
89 protected $mTouched = '19700101000000';
94 protected $mLinksUpdated = '19700101000000';
97 * @var DerivedPageDataUpdater|null
99 private $derivedDataUpdater = null;
102 * Constructor and clear the article
103 * @param Title $title Reference to a Title object.
105 public function __construct( Title
$title ) {
106 $this->mTitle
= $title;
110 * Makes sure that the mTitle object is cloned
111 * to the newly cloned WikiPage.
113 public function __clone() {
114 $this->mTitle
= clone $this->mTitle
;
118 * Create a WikiPage object of the appropriate class for the given title.
120 * @param Title $title
122 * @throws MWException
123 * @return WikiPage|WikiCategoryPage|WikiFilePage
125 public static function factory( Title
$title ) {
126 $ns = $title->getNamespace();
128 if ( $ns == NS_MEDIA
) {
129 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
130 } elseif ( $ns < 0 ) {
131 throw new MWException( "Invalid or virtual namespace $ns given." );
135 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
141 $page = new WikiFilePage( $title );
144 $page = new WikiCategoryPage( $title );
147 $page = new WikiPage( $title );
154 * Constructor from a page id
156 * @param int $id Article ID to load
157 * @param string|int $from One of the following values:
158 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
159 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
161 * @return WikiPage|null
163 public static function newFromID( $id, $from = 'fromdb' ) {
164 // page ids are never 0 or negative, see T63166
169 $from = self
::convertSelectType( $from );
170 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
171 $pageQuery = self
::getQueryInfo();
172 $row = $db->selectRow(
173 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
174 [], $pageQuery['joins']
179 return self
::newFromRow( $row, $from );
183 * Constructor from a database row
186 * @param object $row Database row containing at least fields returned by selectFields().
187 * @param string|int $from Source of $data:
188 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
189 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
190 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
193 public static function newFromRow( $row, $from = 'fromdb' ) {
194 $page = self
::factory( Title
::newFromRow( $row ) );
195 $page->loadFromRow( $row, $from );
200 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
202 * @param object|string|int $type
205 protected static function convertSelectType( $type ) {
208 return self
::READ_NORMAL
;
210 return self
::READ_LATEST
;
212 return self
::READ_LOCKING
;
214 // It may already be an integer or whatever else
220 * @return RevisionStore
222 private function getRevisionStore() {
223 return MediaWikiServices
::getInstance()->getRevisionStore();
227 * @return ParserCache
229 private function getParserCache() {
230 return MediaWikiServices
::getInstance()->getParserCache();
234 * @return LoadBalancer
236 private function getDBLoadBalancer() {
237 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
241 * @todo Move this UI stuff somewhere else
243 * @see ContentHandler::getActionOverrides
246 public function getActionOverrides() {
247 return $this->getContentHandler()->getActionOverrides();
251 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
253 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
255 * @return ContentHandler
259 public function getContentHandler() {
260 return ContentHandler
::getForModelID( $this->getContentModel() );
264 * Get the title object of the article
265 * @return Title Title object of this page
267 public function getTitle() {
268 return $this->mTitle
;
275 public function clear() {
276 $this->mDataLoaded
= false;
277 $this->mDataLoadedFrom
= self
::READ_NONE
;
279 $this->clearCacheFields();
283 * Clear the object cache fields
286 protected function clearCacheFields() {
288 $this->mRedirectTarget
= null; // Title object if set
289 $this->mLastRevision
= null; // Latest revision
290 $this->mTouched
= '19700101000000';
291 $this->mLinksUpdated
= '19700101000000';
292 $this->mTimestamp
= '';
293 $this->mIsRedirect
= false;
294 $this->mLatest
= false;
295 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
296 // checks the requested rev ID and content against the cached one. For most
297 // content types, the output should not change during the lifetime of this cache.
298 // Clearing it can cause extra parses on edit for no reason.
302 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
306 public function clearPreparedEdit() {
307 $this->mPreparedEdit
= false;
311 * Return the list of revision fields that should be selected to create
314 * @deprecated since 1.31, use self::getQueryInfo() instead.
317 public static function selectFields() {
318 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
320 wfDeprecated( __METHOD__
, '1.31' );
331 'page_links_updated',
336 if ( $wgContentHandlerUseDB ) {
337 $fields[] = 'page_content_model';
340 if ( $wgPageLanguageUseDB ) {
341 $fields[] = 'page_lang';
348 * Return the tables, fields, and join conditions to be selected to create
351 * @return array With three keys:
352 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
353 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
354 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
356 public static function getQueryInfo() {
357 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
360 'tables' => [ 'page' ],
370 'page_links_updated',
377 if ( $wgContentHandlerUseDB ) {
378 $ret['fields'][] = 'page_content_model';
381 if ( $wgPageLanguageUseDB ) {
382 $ret['fields'][] = 'page_lang';
389 * Fetch a page record with the given conditions
390 * @param IDatabase $dbr
391 * @param array $conditions
392 * @param array $options
393 * @return object|bool Database result resource, or false on failure
395 protected function pageData( $dbr, $conditions, $options = [] ) {
396 $pageQuery = self
::getQueryInfo();
398 // Avoid PHP 7.1 warning of passing $this by reference
401 Hooks
::run( 'ArticlePageDataBefore', [
402 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
405 $row = $dbr->selectRow(
406 $pageQuery['tables'],
407 $pageQuery['fields'],
414 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
420 * Fetch a page record matching the Title object's namespace and title
421 * using a sanitized title string
423 * @param IDatabase $dbr
424 * @param Title $title
425 * @param array $options
426 * @return object|bool Database result resource, or false on failure
428 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
429 return $this->pageData( $dbr, [
430 'page_namespace' => $title->getNamespace(),
431 'page_title' => $title->getDBkey() ], $options );
435 * Fetch a page record matching the requested ID
437 * @param IDatabase $dbr
439 * @param array $options
440 * @return object|bool Database result resource, or false on failure
442 public function pageDataFromId( $dbr, $id, $options = [] ) {
443 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
447 * Load the object from a given source by title
449 * @param object|string|int $from One of the following:
450 * - A DB query result object.
451 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
452 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
453 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
454 * using SELECT FOR UPDATE.
458 public function loadPageData( $from = 'fromdb' ) {
459 $from = self
::convertSelectType( $from );
460 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
461 // We already have the data from the correct location, no need to load it twice.
465 if ( is_int( $from ) ) {
466 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
467 $loadBalancer = $this->getDBLoadBalancer();
468 $db = $loadBalancer->getConnection( $index );
469 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
472 && $index == DB_REPLICA
473 && $loadBalancer->getServerCount() > 1
474 && $loadBalancer->hasOrMadeRecentMasterChanges()
476 $from = self
::READ_LATEST
;
477 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
478 $db = $loadBalancer->getConnection( $index );
479 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
482 // No idea from where the caller got this data, assume replica DB.
484 $from = self
::READ_NORMAL
;
487 $this->loadFromRow( $data, $from );
491 * Checks whether the page data was loaded using the given database access mode (or better).
495 * @param string|int $from One of the following:
496 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
497 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
498 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
499 * using SELECT FOR UPDATE.
503 public function wasLoadedFrom( $from ) {
504 $from = self
::convertSelectType( $from );
506 if ( !is_int( $from ) ) {
507 // No idea from where the caller got this data, assume replica DB.
508 $from = self
::READ_NORMAL
;
511 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
519 * Load the object from a database row
522 * @param object|bool $data DB row containing fields returned by selectFields() or false
523 * @param string|int $from One of the following:
524 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
525 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
526 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
527 * the master DB using SELECT FOR UPDATE
529 public function loadFromRow( $data, $from ) {
530 $lc = MediaWikiServices
::getInstance()->getLinkCache();
531 $lc->clearLink( $this->mTitle
);
534 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
536 $this->mTitle
->loadFromRow( $data );
538 // Old-fashioned restrictions
539 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
541 $this->mId
= intval( $data->page_id
);
542 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
543 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
544 $this->mIsRedirect
= intval( $data->page_is_redirect
);
545 $this->mLatest
= intval( $data->page_latest
);
546 // T39225: $latest may no longer match the cached latest Revision object.
547 // Double-check the ID of any cached latest Revision object for consistency.
548 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
549 $this->mLastRevision
= null;
550 $this->mTimestamp
= '';
553 $lc->addBadLinkObj( $this->mTitle
);
555 $this->mTitle
->loadFromRow( false );
557 $this->clearCacheFields();
562 $this->mDataLoaded
= true;
563 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
567 * @return int Page ID
569 public function getId() {
570 if ( !$this->mDataLoaded
) {
571 $this->loadPageData();
577 * @return bool Whether or not the page exists in the database
579 public function exists() {
580 if ( !$this->mDataLoaded
) {
581 $this->loadPageData();
583 return $this->mId
> 0;
587 * Check if this page is something we're going to be showing
588 * some sort of sensible content for. If we return false, page
589 * views (plain action=view) will return an HTTP 404 response,
590 * so spiders and robots can know they're following a bad link.
594 public function hasViewableContent() {
595 return $this->mTitle
->isKnown();
599 * Tests if the article content represents a redirect
603 public function isRedirect() {
604 if ( !$this->mDataLoaded
) {
605 $this->loadPageData();
608 return (bool)$this->mIsRedirect
;
612 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
614 * Will use the revisions actual content model if the page exists,
615 * and the page's default if the page doesn't exist yet.
621 public function getContentModel() {
622 if ( $this->exists() ) {
623 $cache = ObjectCache
::getMainWANInstance();
625 return $cache->getWithSetCallback(
626 $cache->makeKey( 'page-content-model', $this->getLatest() ),
629 $rev = $this->getRevision();
631 // Look at the revision's actual content model
632 return $rev->getContentModel();
634 $title = $this->mTitle
->getPrefixedDBkey();
635 wfWarn( "Page $title exists but has no (visible) revisions!" );
636 return $this->mTitle
->getContentModel();
642 // use the default model for this page
643 return $this->mTitle
->getContentModel();
647 * Loads page_touched and returns a value indicating if it should be used
648 * @return bool True if this page exists and is not a redirect
650 public function checkTouched() {
651 if ( !$this->mDataLoaded
) {
652 $this->loadPageData();
654 return ( $this->mId
&& !$this->mIsRedirect
);
658 * Get the page_touched field
659 * @return string Containing GMT timestamp
661 public function getTouched() {
662 if ( !$this->mDataLoaded
) {
663 $this->loadPageData();
665 return $this->mTouched
;
669 * Get the page_links_updated field
670 * @return string|null Containing GMT timestamp
672 public function getLinksTimestamp() {
673 if ( !$this->mDataLoaded
) {
674 $this->loadPageData();
676 return $this->mLinksUpdated
;
680 * Get the page_latest field
681 * @return int The rev_id of current revision
683 public function getLatest() {
684 if ( !$this->mDataLoaded
) {
685 $this->loadPageData();
687 return (int)$this->mLatest
;
691 * Get the Revision object of the oldest revision
692 * @return Revision|null
694 public function getOldestRevision() {
695 // Try using the replica DB first, then try the master
696 $rev = $this->mTitle
->getFirstRevision();
698 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
704 * Loads everything except the text
705 * This isn't necessary for all uses, so it's only done if needed.
707 protected function loadLastEdit() {
708 if ( $this->mLastRevision
!== null ) {
709 return; // already loaded
712 $latest = $this->getLatest();
714 return; // page doesn't exist or is missing page_latest info
717 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
718 // T39225: if session S1 loads the page row FOR UPDATE, the result always
719 // includes the latest changes committed. This is true even within REPEATABLE-READ
720 // transactions, where S1 normally only sees changes committed before the first S1
721 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
722 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
723 // happened after the first S1 SELECT.
724 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
725 $flags = Revision
::READ_LOCKING
;
726 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
727 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
728 // Bug T93976: if page_latest was loaded from the master, fetch the
729 // revision from there as well, as it may not exist yet on a replica DB.
730 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
731 $flags = Revision
::READ_LATEST
;
732 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
734 $dbr = wfGetDB( DB_REPLICA
);
735 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
738 if ( $revision ) { // sanity
739 $this->setLastEdit( $revision );
744 * Set the latest revision
745 * @param Revision $revision
747 protected function setLastEdit( Revision
$revision ) {
748 $this->mLastRevision
= $revision;
749 $this->mTimestamp
= $revision->getTimestamp();
753 * Get the latest revision
754 * @return Revision|null
756 public function getRevision() {
757 $this->loadLastEdit();
758 if ( $this->mLastRevision
) {
759 return $this->mLastRevision
;
765 * Get the content of the current revision. No side-effects...
767 * @param int $audience One of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to $wgUser
770 * Revision::RAW get the text regardless of permissions
771 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
772 * to the $audience parameter
773 * @return Content|null The content of the current revision
777 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
778 $this->loadLastEdit();
779 if ( $this->mLastRevision
) {
780 return $this->mLastRevision
->getContent( $audience, $user );
786 * @return string MW timestamp of last article revision
788 public function getTimestamp() {
789 // Check if the field has been filled by WikiPage::setTimestamp()
790 if ( !$this->mTimestamp
) {
791 $this->loadLastEdit();
794 return wfTimestamp( TS_MW
, $this->mTimestamp
);
798 * Set the page timestamp (use only to avoid DB queries)
799 * @param string $ts MW timestamp of last article revision
802 public function setTimestamp( $ts ) {
803 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
807 * @param int $audience One of:
808 * Revision::FOR_PUBLIC to be displayed to all users
809 * Revision::FOR_THIS_USER to be displayed to the given user
810 * Revision::RAW get the text regardless of permissions
811 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
812 * to the $audience parameter
813 * @return int User ID for the user that made the last article revision
815 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
816 $this->loadLastEdit();
817 if ( $this->mLastRevision
) {
818 return $this->mLastRevision
->getUser( $audience, $user );
825 * Get the User object of the user who created the page
826 * @param int $audience One of:
827 * Revision::FOR_PUBLIC to be displayed to all users
828 * Revision::FOR_THIS_USER to be displayed to the given user
829 * Revision::RAW get the text regardless of permissions
830 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
831 * to the $audience parameter
834 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
835 $revision = $this->getOldestRevision();
837 $userName = $revision->getUserText( $audience, $user );
838 return User
::newFromName( $userName, false );
845 * @param int $audience One of:
846 * Revision::FOR_PUBLIC to be displayed to all users
847 * Revision::FOR_THIS_USER to be displayed to the given user
848 * Revision::RAW get the text regardless of permissions
849 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
850 * to the $audience parameter
851 * @return string Username of the user that made the last article revision
853 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
854 $this->loadLastEdit();
855 if ( $this->mLastRevision
) {
856 return $this->mLastRevision
->getUserText( $audience, $user );
863 * @param int $audience One of:
864 * Revision::FOR_PUBLIC to be displayed to all users
865 * Revision::FOR_THIS_USER to be displayed to the given user
866 * Revision::RAW get the text regardless of permissions
867 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
868 * to the $audience parameter
869 * @return string Comment stored for the last article revision
871 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
872 $this->loadLastEdit();
873 if ( $this->mLastRevision
) {
874 return $this->mLastRevision
->getComment( $audience, $user );
881 * Returns true if last revision was marked as "minor edit"
883 * @return bool Minor edit indicator for the last article revision.
885 public function getMinorEdit() {
886 $this->loadLastEdit();
887 if ( $this->mLastRevision
) {
888 return $this->mLastRevision
->isMinor();
895 * Determine whether a page would be suitable for being counted as an
896 * article in the site_stats table based on the title & its content
898 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
899 * if false, the current database state will be used
902 public function isCountable( $editInfo = false ) {
903 global $wgArticleCountMethod;
905 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
907 if ( !$this->mTitle
->isContentPage() ) {
912 // NOTE: only the main slot can make a page a redirect
913 $content = $editInfo->pstContent
;
915 $content = $this->getContent();
918 if ( !$content ||
$content->isRedirect() ) {
924 if ( $wgArticleCountMethod === 'link' ) {
925 // nasty special case to avoid re-parsing to detect links
928 // ParserOutput::getLinks() is a 2D array of page links, so
929 // to be really correct we would need to recurse in the array
930 // but the main array should only have items in it if there are
932 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
934 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
935 [ 'pl_from' => $this->getId() ], __METHOD__
);
939 return $content->isCountable( $hasLinks );
943 * If this page is a redirect, get its target
945 * The target will be fetched from the redirect table if possible.
946 * If this page doesn't have an entry there, call insertRedirect()
947 * @return Title|null Title object, or null if this page is not a redirect
949 public function getRedirectTarget() {
950 if ( !$this->mTitle
->isRedirect() ) {
954 if ( $this->mRedirectTarget
!== null ) {
955 return $this->mRedirectTarget
;
958 // Query the redirect table
959 $dbr = wfGetDB( DB_REPLICA
);
960 $row = $dbr->selectRow( 'redirect',
961 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
962 [ 'rd_from' => $this->getId() ],
966 // rd_fragment and rd_interwiki were added later, populate them if empty
967 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
968 $this->mRedirectTarget
= Title
::makeTitle(
969 $row->rd_namespace
, $row->rd_title
,
970 $row->rd_fragment
, $row->rd_interwiki
972 return $this->mRedirectTarget
;
975 // This page doesn't have an entry in the redirect table
976 $this->mRedirectTarget
= $this->insertRedirect();
977 return $this->mRedirectTarget
;
981 * Insert an entry for this page into the redirect table if the content is a redirect
983 * The database update will be deferred via DeferredUpdates
985 * Don't call this function directly unless you know what you're doing.
986 * @return Title|null Title object or null if not a redirect
988 public function insertRedirect() {
989 $content = $this->getContent();
990 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
995 // Update the DB post-send if the page has not cached since now
996 $latest = $this->getLatest();
997 DeferredUpdates
::addCallableUpdate(
998 function () use ( $retval, $latest ) {
999 $this->insertRedirectEntry( $retval, $latest );
1001 DeferredUpdates
::POSTSEND
,
1002 wfGetDB( DB_MASTER
)
1009 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1010 * @param Title $rt Redirect target
1011 * @param int|null $oldLatest Prior page_latest for check and set
1013 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1014 $dbw = wfGetDB( DB_MASTER
);
1015 $dbw->startAtomic( __METHOD__
);
1017 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1021 'rd_from' => $this->getId(),
1022 'rd_namespace' => $rt->getNamespace(),
1023 'rd_title' => $rt->getDBkey(),
1024 'rd_fragment' => $rt->getFragment(),
1025 'rd_interwiki' => $rt->getInterwiki(),
1029 'rd_namespace' => $rt->getNamespace(),
1030 'rd_title' => $rt->getDBkey(),
1031 'rd_fragment' => $rt->getFragment(),
1032 'rd_interwiki' => $rt->getInterwiki(),
1038 $dbw->endAtomic( __METHOD__
);
1042 * Get the Title object or URL this page redirects to
1044 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1046 public function followRedirect() {
1047 return $this->getRedirectURL( $this->getRedirectTarget() );
1051 * Get the Title object or URL to use for a redirect. We use Title
1052 * objects for same-wiki, non-special redirects and URLs for everything
1054 * @param Title $rt Redirect target
1055 * @return bool|Title|string False, Title object of local target, or string with URL
1057 public function getRedirectURL( $rt ) {
1062 if ( $rt->isExternal() ) {
1063 if ( $rt->isLocal() ) {
1064 // Offsite wikis need an HTTP redirect.
1065 // This can be hard to reverse and may produce loops,
1066 // so they may be disabled in the site configuration.
1067 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1068 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1070 // External pages without "local" bit set are not valid
1076 if ( $rt->isSpecialPage() ) {
1077 // Gotta handle redirects to special pages differently:
1078 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1079 // Some pages are not valid targets.
1080 if ( $rt->isValidRedirectTarget() ) {
1081 return $rt->getFullURL();
1091 * Get a list of users who have edited this article, not including the user who made
1092 * the most recent revision, which you can get from $article->getUser() if you want it
1093 * @return UserArrayFromResult
1095 public function getContributors() {
1096 // @todo: This is expensive; cache this info somewhere.
1098 $dbr = wfGetDB( DB_REPLICA
);
1100 $actorMigration = ActorMigration
::newMigration();
1101 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1103 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1106 'user_id' => $actorQuery['fields']['rev_user'],
1107 'user_name' => $actorQuery['fields']['rev_user_text'],
1108 'actor_id' => $actorQuery['fields']['rev_actor'],
1109 'user_real_name' => 'MIN(user_real_name)',
1110 'timestamp' => 'MAX(rev_timestamp)',
1113 $conds = [ 'rev_page' => $this->getId() ];
1115 // The user who made the top revision gets credited as "this page was last edited by
1116 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1117 $user = $this->getUser()
1118 ? User
::newFromId( $this->getUser() )
1119 : User
::newFromName( $this->getUserText(), false );
1120 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1123 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1126 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1127 ] +
$actorQuery['joins'];
1130 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1131 'ORDER BY' => 'timestamp DESC',
1134 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1135 return new UserArrayFromResult( $res );
1139 * Should the parser cache be used?
1141 * @param ParserOptions $parserOptions ParserOptions to check
1145 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1146 return $parserOptions->getStubThreshold() == 0
1148 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1149 && $this->getContentHandler()->isParserCacheSupported();
1153 * Get a ParserOutput for the given ParserOptions and revision ID.
1155 * The parser cache will be used if possible. Cache misses that result
1156 * in parser runs are debounced with PoolCounter.
1159 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1160 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1161 * get the current revision (default value)
1162 * @param bool $forceParse Force reindexing, regardless of cache settings
1163 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1165 public function getParserOutput(
1166 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1169 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1171 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1172 throw new InvalidArgumentException(
1173 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1177 wfDebug( __METHOD__
.
1178 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1179 if ( $parserOptions->getStubThreshold() ) {
1180 wfIncrStats( 'pcache.miss.stub' );
1183 if ( $useParserCache ) {
1184 $parserOutput = $this->getParserCache()
1185 ->get( $this, $parserOptions );
1186 if ( $parserOutput !== false ) {
1187 return $parserOutput;
1191 if ( $oldid === null ||
$oldid === 0 ) {
1192 $oldid = $this->getLatest();
1195 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1198 return $pool->getParserOutput();
1202 * Do standard deferred updates after page view (existing or missing page)
1203 * @param User $user The relevant user
1204 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1206 public function doViewUpdates( User
$user, $oldid = 0 ) {
1207 if ( wfReadOnly() ) {
1211 // Update newtalk / watchlist notification status;
1212 // Avoid outage if the master is not reachable by using a deferred updated
1213 DeferredUpdates
::addCallableUpdate(
1214 function () use ( $user, $oldid ) {
1215 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1217 $user->clearNotification( $this->mTitle
, $oldid );
1219 DeferredUpdates
::PRESEND
1224 * Perform the actions of a page purging
1226 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1227 * controlled how much purging was done.
1229 public function doPurge() {
1230 // Avoid PHP 7.1 warning of passing $this by reference
1233 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1237 $this->mTitle
->invalidateCache();
1240 HTMLFileCache
::clearFileCache( $this->getTitle() );
1241 // Send purge after above page_touched update was committed
1242 DeferredUpdates
::addUpdate(
1243 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1244 DeferredUpdates
::PRESEND
1247 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1248 $messageCache = MessageCache
::singleton();
1249 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1256 * Insert a new empty page record for this article.
1257 * This *must* be followed up by creating a revision
1258 * and running $this->updateRevisionOn( ... );
1259 * or else the record will be left in a funky state.
1260 * Best if all done inside a transaction.
1262 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1264 * @param IDatabase $dbw
1265 * @param int|null $pageId Custom page ID that will be used for the insert statement
1267 * @return bool|int The newly created page_id key; false if the row was not
1268 * inserted, e.g. because the title already existed or because the specified
1269 * page ID is already in use.
1271 public function insertOn( $dbw, $pageId = null ) {
1272 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1276 'page_namespace' => $this->mTitle
->getNamespace(),
1277 'page_title' => $this->mTitle
->getDBkey(),
1278 'page_restrictions' => '',
1279 'page_is_redirect' => 0, // Will set this shortly...
1281 'page_random' => wfRandom(),
1282 'page_touched' => $dbw->timestamp(),
1283 'page_latest' => 0, // Fill this in shortly...
1284 'page_len' => 0, // Fill this in shortly...
1285 ] +
$pageIdForInsert,
1290 if ( $dbw->affectedRows() > 0 ) {
1291 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1292 $this->mId
= $newid;
1293 $this->mTitle
->resetArticleID( $newid );
1297 return false; // nothing changed
1302 * Update the page record to point to a newly saved revision.
1304 * @todo Factor out into a PageStore service, or move into PageUpdater.
1306 * @param IDatabase $dbw
1307 * @param Revision $revision For ID number, and text used to set
1308 * length and redirect status fields
1309 * @param int|null $lastRevision If given, will not overwrite the page field
1310 * when different from the currently set value.
1311 * Giving 0 indicates the new page flag should be set on.
1312 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1313 * removing rows in redirect table.
1314 * @return bool Success; false if the page row was missing or page_latest changed
1316 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1317 $lastRevIsRedirect = null
1319 global $wgContentHandlerUseDB;
1321 // TODO: move into PageUpdater or PageStore
1322 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1323 // and in the compat stub!
1325 // Assertion to try to catch T92046
1326 if ( (int)$revision->getId() === 0 ) {
1327 throw new InvalidArgumentException(
1328 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1332 $content = $revision->getContent();
1333 $len = $content ?
$content->getSize() : 0;
1334 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1336 $conditions = [ 'page_id' => $this->getId() ];
1338 if ( !is_null( $lastRevision ) ) {
1339 // An extra check against threads stepping on each other
1340 $conditions['page_latest'] = $lastRevision;
1343 $revId = $revision->getId();
1344 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1347 'page_latest' => $revId,
1348 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1349 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1350 'page_is_redirect' => $rt !== null ?
1 : 0,
1354 if ( $wgContentHandlerUseDB ) {
1355 $row['page_content_model'] = $revision->getContentModel();
1358 $dbw->update( 'page',
1363 $result = $dbw->affectedRows() > 0;
1365 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1366 $this->setLastEdit( $revision );
1367 $this->mLatest
= $revision->getId();
1368 $this->mIsRedirect
= (bool)$rt;
1369 // Update the LinkCache.
1370 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1371 $linkCache->addGoodLinkObj(
1377 $revision->getContentModel()
1385 * Add row to the redirect table if this is a redirect, remove otherwise.
1387 * @param IDatabase $dbw
1388 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1389 * or NULL if this is not a redirect
1390 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1391 * removing rows in redirect table.
1392 * @return bool True on success, false on failure
1395 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1396 // Always update redirects (target link might have changed)
1397 // Update/Insert if we don't know if the last revision was a redirect or not
1398 // Delete if changing from redirect to non-redirect
1399 $isRedirect = !is_null( $redirectTitle );
1401 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1405 if ( $isRedirect ) {
1406 $this->insertRedirectEntry( $redirectTitle );
1408 // This is not a redirect, remove row from redirect table
1409 $where = [ 'rd_from' => $this->getId() ];
1410 $dbw->delete( 'redirect', $where, __METHOD__
);
1413 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1414 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1417 return ( $dbw->affectedRows() != 0 );
1421 * If the given revision is newer than the currently set page_latest,
1422 * update the page record. Otherwise, do nothing.
1424 * @deprecated since 1.24, use updateRevisionOn instead
1426 * @param IDatabase $dbw
1427 * @param Revision $revision
1430 public function updateIfNewerOn( $dbw, $revision ) {
1431 $row = $dbw->selectRow(
1432 [ 'revision', 'page' ],
1433 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1435 'page_id' => $this->getId(),
1436 'page_latest=rev_id' ],
1440 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1443 $prev = $row->rev_id
;
1444 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1446 // No or missing previous revision; mark the page as new
1448 $lastRevIsRedirect = null;
1451 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1457 * Helper method for checking whether two revisions have differences that go
1458 * beyond the main slot.
1460 * MCR migration note: this method should go away!
1462 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1464 * @param Revision $a
1465 * @param Revision $b
1468 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1469 $aSlots = $a->getRevisionRecord()->getSlots();
1470 $bSlots = $b->getRevisionRecord()->getSlots();
1471 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1473 return ( $changedRoles !== [ 'main' ] && $changedRoles !== [] );
1477 * Get the content that needs to be saved in order to undo all revisions
1478 * between $undo and $undoafter. Revisions must belong to the same page,
1479 * must exist and must not be deleted
1481 * @param Revision $undo
1482 * @param Revision $undoafter Must be an earlier revision than $undo
1483 * @return Content|bool Content on success, false on failure
1485 * Before we had the Content object, this was done in getUndoText
1487 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1488 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1490 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1491 // Cannot yet undo edits that involve anything other the main slot.
1495 $handler = $undo->getContentHandler();
1496 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1500 * Returns true if this page's content model supports sections.
1504 * @todo The skin should check this and not offer section functionality if
1505 * sections are not supported.
1506 * @todo The EditPage should check this and not offer section functionality
1507 * if sections are not supported.
1509 public function supportsSections() {
1510 return $this->getContentHandler()->supportsSections();
1514 * @param string|int|null|bool $sectionId Section identifier as a number or string
1515 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1516 * or 'new' for a new section.
1517 * @param Content $sectionContent New content of the section.
1518 * @param string $sectionTitle New section's subject, only if $section is "new".
1519 * @param string $edittime Revision timestamp or null to use the current revision.
1521 * @throws MWException
1522 * @return Content|null New complete article content, or null if error.
1525 * @deprecated since 1.24, use replaceSectionAtRev instead
1527 public function replaceSectionContent(
1528 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1531 if ( $edittime && $sectionId !== 'new' ) {
1532 $lb = $this->getDBLoadBalancer();
1533 $dbr = $lb->getConnection( DB_REPLICA
);
1534 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1535 // Try the master if this thread may have just added it.
1536 // This could be abstracted into a Revision method, but we don't want
1537 // to encourage loading of revisions by timestamp.
1539 && $lb->getServerCount() > 1
1540 && $lb->hasOrMadeRecentMasterChanges()
1542 $dbw = $lb->getConnection( DB_MASTER
);
1543 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1546 $baseRevId = $rev->getId();
1550 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1554 * @param string|int|null|bool $sectionId Section identifier as a number or string
1555 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1556 * or 'new' for a new section.
1557 * @param Content $sectionContent New content of the section.
1558 * @param string $sectionTitle New section's subject, only if $section is "new".
1559 * @param int|null $baseRevId
1561 * @throws MWException
1562 * @return Content|null New complete article content, or null if error.
1566 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1567 $sectionTitle = '', $baseRevId = null
1569 if ( strval( $sectionId ) === '' ) {
1570 // Whole-page edit; let the whole text through
1571 $newContent = $sectionContent;
1573 if ( !$this->supportsSections() ) {
1574 throw new MWException( "sections not supported for content model " .
1575 $this->getContentHandler()->getModelID() );
1578 // T32711: always use current version when adding a new section
1579 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1580 $oldContent = $this->getContent();
1582 $rev = Revision
::newFromId( $baseRevId );
1584 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1585 $this->getId() . "; section: $sectionId)\n" );
1589 $oldContent = $rev->getContent();
1592 if ( !$oldContent ) {
1593 wfDebug( __METHOD__
. ": no page text\n" );
1597 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1604 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1606 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1607 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1610 * @return int Updated $flags
1612 public function checkFlags( $flags ) {
1613 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1614 if ( $this->exists() ) {
1615 $flags |
= EDIT_UPDATE
;
1625 * @return DerivedPageDataUpdater
1627 private function newDerivedDataUpdater() {
1628 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1630 $derivedDataUpdater = new DerivedPageDataUpdater(
1631 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1632 $this->getRevisionStore(),
1633 $this->getParserCache(),
1634 JobQueueGroup
::singleton(),
1635 MessageCache
::singleton(),
1636 MediaWikiServices
::getInstance()->getContentLanguage(),
1637 LoggerFactory
::getInstance( 'SaveParse' )
1640 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1641 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1643 return $derivedDataUpdater;
1647 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1648 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1649 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1650 * returned matches that caller's expectations, allowing an existing instance to be re-used
1651 * if the given parameters match that instance's internal state according to
1652 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1653 * match the existign one.
1655 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1656 * created, replacing any DerivedPageDataUpdater currently cached.
1658 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1662 * @param User|null $forUser The user that will be used for, or was used for, PST.
1663 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1664 * to perform updates, if the edit was already saved.
1665 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1666 * if the edit was not yet saved.
1667 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1668 * revision as the edit's parent revision. This ensures that the same
1669 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1671 * @return DerivedPageDataUpdater
1673 private function getDerivedDataUpdater(
1674 User
$forUser = null,
1675 RevisionRecord
$forRevision = null,
1676 RevisionSlotsUpdate
$forUpdate = null,
1679 if ( !$forRevision && !$forUpdate ) {
1680 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1681 // going to use it with.
1682 $this->derivedDataUpdater
= null;
1685 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1686 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1687 // to it did not yet initialize it, because we don't know what data it will be
1688 // initialized with.
1689 $this->derivedDataUpdater
= null;
1692 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1693 // However, there is no good way to construct a cache key. We'd need to check against all
1694 // cached instances.
1696 if ( $this->derivedDataUpdater
1697 && !$this->derivedDataUpdater
->isReusableFor(
1701 $forEdit ?
$this->getLatest() : null
1704 $this->derivedDataUpdater
= null;
1707 if ( !$this->derivedDataUpdater
) {
1708 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1711 return $this->derivedDataUpdater
;
1715 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1717 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1718 * and to protected such conflict resolution from concurrent edits using a check-and-set
1724 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1725 * that may already have been returned via getDerivedDataUpdater to be re-used.
1727 * @return PageUpdater
1729 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1730 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1732 $pageUpdater = new PageUpdater(
1734 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1735 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1736 $this->getDBLoadBalancer(),
1737 $this->getRevisionStore()
1740 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1741 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1742 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1744 return $pageUpdater;
1748 * Change an existing article or create a new article. Updates RC and all necessary caches,
1749 * optionally via the deferred update array.
1751 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1752 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1753 * apply the autopatrol right as appropriate.
1755 * @param Content $content New content
1756 * @param string|CommentStoreComment $summary Edit summary
1757 * @param int $flags Bitfield:
1759 * Article is known or assumed to be non-existent, create a new one
1761 * Article is known or assumed to be pre-existing, update it
1763 * Mark this edit minor, if the user is allowed to do so
1765 * Do not log the change in recentchanges
1767 * Mark the edit a "bot" edit regardless of user rights
1769 * Fill in blank summaries with generated text where possible
1771 * Signal that the page retrieve/save cycle happened entirely in this request.
1773 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1774 * article will be detected. If EDIT_UPDATE is specified and the article
1775 * doesn't exist, the function will return an edit-gone-missing error. If
1776 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1777 * error will be returned. These two conditions are also possible with
1778 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1780 * @param bool|int $originalRevId: The ID of an original revision that the edit
1781 * restores or repeats. The new revision is expected to have the exact same content as
1782 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1783 * which are created to record things like page moves.
1784 * @param User|null $user The user doing the edit
1785 * @param string|null $serialFormat IGNORED.
1786 * @param array|null $tags Change tags to apply to this edit
1787 * Callers are responsible for permission checks
1788 * (with ChangeTags::canAddTagsAccompanyingChange)
1789 * @param Int $undidRevId Id of revision that was undone or 0
1791 * @throws MWException
1792 * @return Status Possible errors:
1793 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1794 * set the fatal flag of $status.
1795 * edit-gone-missing: In update mode, but the article didn't exist.
1796 * edit-conflict: In update mode, the article changed unexpectedly.
1797 * edit-no-change: Warning that the text was the same as before.
1798 * edit-already-exists: In creation mode, but the article already exists.
1800 * Extensions may define additional errors.
1802 * $return->value will contain an associative array with members as follows:
1803 * new: Boolean indicating if the function attempted to create a new article.
1804 * revision: The revision object for the inserted revision, or null.
1807 * @throws MWException
1809 public function doEditContent(
1810 Content
$content, $summary, $flags = 0, $originalRevId = false,
1811 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1813 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1815 if ( !( $summary instanceof CommentStoreComment
) ) {
1816 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1823 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1824 // Checking the minoredit right should be done in the same place the 'bot' right is
1825 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1826 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1827 $flags = ( $flags & ~EDIT_MINOR
);
1830 $slotsUpdate = new RevisionSlotsUpdate();
1831 $slotsUpdate->modifyContent( 'main', $content );
1833 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1834 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1835 // used by this PageUpdater. However, there is no guarantee for this.
1836 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1837 $updater->setContent( 'main', $content );
1838 $updater->setOriginalRevisionId( $originalRevId );
1839 $updater->setUndidRevisionId( $undidRevId );
1841 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1843 // TODO: this logic should not be in the storage layer, it's here for compatibility
1844 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1845 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1846 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1847 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1850 $updater->addTags( $tags );
1852 $revRec = $updater->saveRevision(
1857 // $revRec will be null if the edit failed, or if no new revision was created because
1858 // the content did not change.
1860 // update cached fields
1861 // TODO: this is currently redundant to what is done in updateRevisionOn.
1862 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1863 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1864 $this->mLatest
= $revRec->getId();
1867 return $updater->getStatus();
1871 * Get parser options suitable for rendering the primary article wikitext
1873 * @see ParserOptions::newCanonical
1875 * @param IContextSource|User|string $context One of the following:
1876 * - IContextSource: Use the User and the Language of the provided
1878 * - User: Use the provided User object and $wgLang for the language,
1879 * so use an IContextSource object if possible.
1880 * - 'canonical': Canonical options (anonymous user with default
1881 * preferences and content language).
1882 * @return ParserOptions
1884 public function makeParserOptions( $context ) {
1885 $options = ParserOptions
::newCanonical( $context );
1887 if ( $this->getTitle()->isConversionTable() ) {
1888 // @todo ConversionTable should become a separate content model, so
1889 // we don't need special cases like this one.
1890 $options->disableContentConversion();
1897 * Prepare content which is about to be saved.
1899 * Prior to 1.30, this returned a stdClass.
1901 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1903 * @param Content $content
1904 * @param Revision|RevisionRecord|int|null $revision Revision object.
1905 * For backwards compatibility, a revision ID is also accepted,
1906 * but this is deprecated.
1907 * Used with vary-revision or vary-revision-id.
1908 * @param User|null $user
1909 * @param string|null $serialFormat IGNORED
1910 * @param bool $useCache Check shared prepared edit cache
1912 * @return PreparedEdit
1916 public function prepareContentForEdit(
1920 $serialFormat = null,
1929 if ( !is_object( $revision ) ) {
1931 // This code path is deprecated, and nothing is known to
1932 // use it, so performance here shouldn't be a worry.
1933 if ( $revid !== null ) {
1934 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1935 $store = $this->getRevisionStore();
1936 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1940 } elseif ( $revision instanceof Revision
) {
1941 $revision = $revision->getRevisionRecord();
1944 $slots = RevisionSlotsUpdate
::newFromContent( [ 'main' => $content ] );
1945 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1947 if ( !$updater->isUpdatePrepared() ) {
1948 $updater->prepareContent( $user, $slots, $useCache );
1951 $updater->prepareUpdate( $revision );
1955 return $updater->getPreparedEdit();
1959 * Do standard deferred updates after page edit.
1960 * Update links tables, site stats, search index and message cache.
1961 * Purges pages that include this page if the text was changed here.
1962 * Every 100th edit, prune the recent changes table.
1964 * @deprecated since 1.32, use PageUpdater::doEditUpdates instead.
1966 * @param Revision $revision
1967 * @param User $user User object that did the revision
1968 * @param array $options Array of options, following indexes are used:
1969 * - changed: bool, whether the revision changed the content (default true)
1970 * - created: bool, whether the revision created the page (default false)
1971 * - moved: bool, whether the page was moved (default false)
1972 * - restored: bool, whether the page was undeleted (default false)
1973 * - oldrevision: Revision object for the pre-update revision (default null)
1974 * - oldcountable: bool, null, or string 'no-change' (default null):
1975 * - bool: whether the page was counted as an article before that
1976 * revision, only used in changed is true and created is false
1977 * - null: if created is false, don't update the article count; if created
1978 * is true, do update the article count
1979 * - 'no-change': don't update the article count, ever
1981 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
1982 $revision = $revision->getRevisionRecord();
1984 $updater = $this->getDerivedDataUpdater( $user, $revision );
1986 $updater->prepareUpdate( $revision, $options );
1988 $updater->doUpdates();
1992 * Update the article's restriction field, and leave a log entry.
1993 * This works for protection both existing and non-existing pages.
1995 * @param array $limit Set of restriction keys
1996 * @param array $expiry Per restriction type expiration
1997 * @param int &$cascade Set to false if cascading protection isn't allowed.
1998 * @param string $reason
1999 * @param User $user The user updating the restrictions
2000 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2001 * ($user should be able to add the specified tags before this is called)
2002 * @return Status Status object; if action is taken, $status->value is the log_id of the
2003 * protection log entry.
2005 public function doUpdateRestrictions( array $limit, array $expiry,
2006 &$cascade, $reason, User
$user, $tags = null
2008 global $wgCascadingRestrictionLevels;
2010 if ( wfReadOnly() ) {
2011 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2014 $this->loadPageData( 'fromdbmaster' );
2015 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2016 $id = $this->getId();
2022 // Take this opportunity to purge out expired restrictions
2023 Title
::purgeExpiredRestrictions();
2025 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2026 // we expect a single selection, but the schema allows otherwise.
2027 $isProtected = false;
2031 $dbw = wfGetDB( DB_MASTER
);
2033 foreach ( $restrictionTypes as $action ) {
2034 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2035 $expiry[$action] = 'infinity';
2037 if ( !isset( $limit[$action] ) ) {
2038 $limit[$action] = '';
2039 } elseif ( $limit[$action] != '' ) {
2043 // Get current restrictions on $action
2044 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2045 if ( $current != '' ) {
2046 $isProtected = true;
2049 if ( $limit[$action] != $current ) {
2051 } elseif ( $limit[$action] != '' ) {
2052 // Only check expiry change if the action is actually being
2053 // protected, since expiry does nothing on an not-protected
2055 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2061 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2065 // If nothing has changed, do nothing
2067 return Status
::newGood();
2070 if ( !$protect ) { // No protection at all means unprotection
2071 $revCommentMsg = 'unprotectedarticle-comment';
2072 $logAction = 'unprotect';
2073 } elseif ( $isProtected ) {
2074 $revCommentMsg = 'modifiedarticleprotection-comment';
2075 $logAction = 'modify';
2077 $revCommentMsg = 'protectedarticle-comment';
2078 $logAction = 'protect';
2081 $logRelationsValues = [];
2082 $logRelationsField = null;
2083 $logParamsDetails = [];
2085 // Null revision (used for change tag insertion)
2086 $nullRevision = null;
2088 if ( $id ) { // Protection of existing page
2089 // Avoid PHP 7.1 warning of passing $this by reference
2092 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2093 return Status
::newGood();
2096 // Only certain restrictions can cascade...
2097 $editrestriction = isset( $limit['edit'] )
2098 ?
[ $limit['edit'] ]
2099 : $this->mTitle
->getRestrictions( 'edit' );
2100 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2101 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2103 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2104 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2107 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2108 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2109 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2111 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2112 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2115 // The schema allows multiple restrictions
2116 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2120 // insert null revision to identify the page protection change as edit summary
2121 $latest = $this->getLatest();
2122 $nullRevision = $this->insertProtectNullRevision(
2131 if ( $nullRevision === null ) {
2132 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2135 $logRelationsField = 'pr_id';
2137 // Update restrictions table
2138 foreach ( $limit as $action => $restrictions ) {
2140 'page_restrictions',
2143 'pr_type' => $action
2147 if ( $restrictions != '' ) {
2148 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2150 'page_restrictions',
2153 'pr_type' => $action,
2154 'pr_level' => $restrictions,
2155 'pr_cascade' => $cascadeValue,
2156 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2160 $logRelationsValues[] = $dbw->insertId();
2161 $logParamsDetails[] = [
2163 'level' => $restrictions,
2164 'expiry' => $expiry[$action],
2165 'cascade' => (bool)$cascadeValue,
2170 // Clear out legacy restriction fields
2173 [ 'page_restrictions' => '' ],
2174 [ 'page_id' => $id ],
2178 // Avoid PHP 7.1 warning of passing $this by reference
2181 Hooks
::run( 'NewRevisionFromEditComplete',
2182 [ $this, $nullRevision, $latest, $user ] );
2183 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2184 } else { // Protection of non-existing page (also known as "title protection")
2185 // Cascade protection is meaningless in this case
2188 if ( $limit['create'] != '' ) {
2189 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2190 $dbw->replace( 'protected_titles',
2191 [ [ 'pt_namespace', 'pt_title' ] ],
2193 'pt_namespace' => $this->mTitle
->getNamespace(),
2194 'pt_title' => $this->mTitle
->getDBkey(),
2195 'pt_create_perm' => $limit['create'],
2196 'pt_timestamp' => $dbw->timestamp(),
2197 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2198 'pt_user' => $user->getId(),
2199 ] +
$commentFields, __METHOD__
2201 $logParamsDetails[] = [
2203 'level' => $limit['create'],
2204 'expiry' => $expiry['create'],
2207 $dbw->delete( 'protected_titles',
2209 'pt_namespace' => $this->mTitle
->getNamespace(),
2210 'pt_title' => $this->mTitle
->getDBkey()
2216 $this->mTitle
->flushRestrictions();
2217 InfoAction
::invalidateCache( $this->mTitle
);
2219 if ( $logAction == 'unprotect' ) {
2222 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2224 '4::description' => $protectDescriptionLog, // parameter for IRC
2225 '5:bool:cascade' => $cascade,
2226 'details' => $logParamsDetails, // parameter for localize and api
2230 // Update the protection log
2231 $logEntry = new ManualLogEntry( 'protect', $logAction );
2232 $logEntry->setTarget( $this->mTitle
);
2233 $logEntry->setComment( $reason );
2234 $logEntry->setPerformer( $user );
2235 $logEntry->setParameters( $params );
2236 if ( !is_null( $nullRevision ) ) {
2237 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2239 $logEntry->setTags( $tags );
2240 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2241 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2243 $logId = $logEntry->insert();
2244 $logEntry->publish( $logId );
2246 return Status
::newGood( $logId );
2250 * Insert a new null revision for this page.
2252 * @param string $revCommentMsg Comment message key for the revision
2253 * @param array $limit Set of restriction keys
2254 * @param array $expiry Per restriction type expiration
2255 * @param int $cascade Set to false if cascading protection isn't allowed.
2256 * @param string $reason
2257 * @param User|null $user
2258 * @return Revision|null Null on error
2260 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2261 array $expiry, $cascade, $reason, $user = null
2263 $dbw = wfGetDB( DB_MASTER
);
2265 // Prepare a null revision to be added to the history
2266 $editComment = wfMessage(
2268 $this->mTitle
->getPrefixedText(),
2269 $user ?
$user->getName() : ''
2270 )->inContentLanguage()->text();
2272 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2274 $protectDescription = $this->protectDescription( $limit, $expiry );
2275 if ( $protectDescription ) {
2276 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2277 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2278 ->inContentLanguage()->text();
2281 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2282 $editComment .= wfMessage( 'brackets' )->params(
2283 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2284 )->inContentLanguage()->text();
2287 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2289 $nullRev->insertOn( $dbw );
2291 // Update page record and touch page
2292 $oldLatest = $nullRev->getParentId();
2293 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2300 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2303 protected function formatExpiry( $expiry ) {
2304 if ( $expiry != 'infinity' ) {
2305 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2308 $contLang->timeanddate( $expiry, false, false ),
2309 $contLang->date( $expiry, false, false ),
2310 $contLang->time( $expiry, false, false )
2311 )->inContentLanguage()->text();
2313 return wfMessage( 'protect-expiry-indefinite' )
2314 ->inContentLanguage()->text();
2319 * Builds the description to serve as comment for the edit.
2321 * @param array $limit Set of restriction keys
2322 * @param array $expiry Per restriction type expiration
2325 public function protectDescription( array $limit, array $expiry ) {
2326 $protectDescription = '';
2328 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2329 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2330 # All possible message keys are listed here for easier grepping:
2331 # * restriction-create
2332 # * restriction-edit
2333 # * restriction-move
2334 # * restriction-upload
2335 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2336 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2337 # with '' filtered out. All possible message keys are listed below:
2338 # * protect-level-autoconfirmed
2339 # * protect-level-sysop
2340 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2341 ->inContentLanguage()->text();
2343 $expiryText = $this->formatExpiry( $expiry[$action] );
2345 if ( $protectDescription !== '' ) {
2346 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2348 $protectDescription .= wfMessage( 'protect-summary-desc' )
2349 ->params( $actionText, $restrictionsText, $expiryText )
2350 ->inContentLanguage()->text();
2353 return $protectDescription;
2357 * Builds the description to serve as comment for the log entry.
2359 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2360 * protect description text. Keep them in old format to avoid breaking compatibility.
2361 * TODO: Fix protection log to store structured description and format it on-the-fly.
2363 * @param array $limit Set of restriction keys
2364 * @param array $expiry Per restriction type expiration
2367 public function protectDescriptionLog( array $limit, array $expiry ) {
2368 $protectDescriptionLog = '';
2370 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2371 $expiryText = $this->formatExpiry( $expiry[$action] );
2372 $protectDescriptionLog .=
2373 MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark() .
2374 "[$action=$restrictions] ($expiryText)";
2377 return trim( $protectDescriptionLog );
2381 * Take an array of page restrictions and flatten it to a string
2382 * suitable for insertion into the page_restrictions field.
2384 * @param string[] $limit
2386 * @throws MWException
2389 protected static function flattenRestrictions( $limit ) {
2390 if ( !is_array( $limit ) ) {
2391 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2397 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2398 $bits[] = "$action=$restrictions";
2401 return implode( ':', $bits );
2405 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2406 * backwards compatibility, if you care about error reporting you should use
2407 * doDeleteArticleReal() instead.
2409 * Deletes the article with database consistency, writes logs, purges caches
2411 * @param string $reason Delete reason for deletion log
2412 * @param bool $suppress Suppress all revisions and log the deletion in
2413 * the suppression log instead of the deletion log
2414 * @param int|null $u1 Unused
2415 * @param bool|null $u2 Unused
2416 * @param array|string &$error Array of errors to append to
2417 * @param User|null $user The deleting user
2418 * @return bool True if successful
2420 public function doDeleteArticle(
2421 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2423 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2424 return $status->isGood();
2428 * Back-end article deletion
2429 * Deletes the article with database consistency, writes logs, purges caches
2433 * @param string $reason Delete reason for deletion log
2434 * @param bool $suppress Suppress all revisions and log the deletion in
2435 * the suppression log instead of the deletion log
2436 * @param int|null $u1 Unused
2437 * @param bool|null $u2 Unused
2438 * @param array|string &$error Array of errors to append to
2439 * @param User|null $deleter The deleting user
2440 * @param array $tags Tags to apply to the deletion action
2441 * @param string $logsubtype
2442 * @return Status Status object; if successful, $status->value is the log_id of the
2443 * deletion log entry. If the page couldn't be deleted because it wasn't
2444 * found, $status is a non-fatal 'cannotdelete' error
2446 public function doDeleteArticleReal(
2447 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2448 $tags = [], $logsubtype = 'delete'
2450 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage,
2451 $wgActorTableSchemaMigrationStage, $wgMultiContentRevisionSchemaMigrationStage;
2453 wfDebug( __METHOD__
. "\n" );
2455 $status = Status
::newGood();
2457 if ( $this->mTitle
->getDBkey() === '' ) {
2458 $status->error( 'cannotdelete',
2459 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2463 // Avoid PHP 7.1 warning of passing $this by reference
2466 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2467 if ( !Hooks
::run( 'ArticleDelete',
2468 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2470 if ( $status->isOK() ) {
2471 // Hook aborted but didn't set a fatal status
2472 $status->fatal( 'delete-hook-aborted' );
2477 $dbw = wfGetDB( DB_MASTER
);
2478 $dbw->startAtomic( __METHOD__
);
2480 $this->loadPageData( self
::READ_LATEST
);
2481 $id = $this->getId();
2482 // T98706: lock the page from various other updates but avoid using
2483 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2484 // the revisions queries (which also JOIN on user). Only lock the page
2485 // row and CAS check on page_latest to see if the trx snapshot matches.
2486 $lockedLatest = $this->lockAndGetLatest();
2487 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2488 $dbw->endAtomic( __METHOD__
);
2489 // Page not there or trx snapshot is stale
2490 $status->error( 'cannotdelete',
2491 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2495 // Given the lock above, we can be confident in the title and page ID values
2496 $namespace = $this->getTitle()->getNamespace();
2497 $dbKey = $this->getTitle()->getDBkey();
2499 // At this point we are now comitted to returning an OK
2500 // status unless some DB query error or other exception comes up.
2501 // This way callers don't have to call rollback() if $status is bad
2502 // unless they actually try to catch exceptions (which is rare).
2504 // we need to remember the old content so we can use it to generate all deletion updates.
2505 $revision = $this->getRevision();
2507 $content = $this->getContent( Revision
::RAW
);
2508 } catch ( Exception
$ex ) {
2509 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2510 . $ex->getMessage() );
2515 $commentStore = CommentStore
::getStore();
2516 $actorMigration = ActorMigration
::newMigration();
2518 $revQuery = Revision
::getQueryInfo();
2521 // Bitfields to further suppress the content
2523 $bitfield = Revision
::SUPPRESSED_ALL
;
2524 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2527 // For now, shunt the revision data into the archive table.
2528 // Text is *not* removed from the text table; bulk storage
2529 // is left intact to avoid breaking block-compression or
2530 // immutable storage schemes.
2531 // In the future, we may keep revisions and mark them with
2532 // the rev_deleted field, which is reserved for this purpose.
2534 // Lock rows in `revision` and its temp tables, but not any others.
2535 // Note array_intersect() preserves keys from the first arg, and we're
2536 // assuming $revQuery has `revision` primary and isn't using subtables
2537 // for anything we care about.
2538 $dbw->lockForUpdate(
2540 $revQuery['tables'],
2541 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2543 [ 'rev_page' => $id ],
2549 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2550 // so we can copy it to the archive table.
2551 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2552 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2553 $revQuery['fields'][] = 'rev_text_id';
2555 if ( $wgContentHandlerUseDB ) {
2556 $revQuery['fields'][] = 'rev_content_model';
2557 $revQuery['fields'][] = 'rev_content_format';
2561 // Get all of the page revisions
2562 $res = $dbw->select(
2563 $revQuery['tables'],
2564 $revQuery['fields'],
2565 [ 'rev_page' => $id ],
2571 // Build their equivalent archive rows
2575 /** @var int[] Revision IDs of edits that were made by IPs */
2578 foreach ( $res as $row ) {
2579 $comment = $commentStore->getComment( 'rev_comment', $row );
2580 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2582 'ar_namespace' => $namespace,
2583 'ar_title' => $dbKey,
2584 'ar_timestamp' => $row->rev_timestamp
,
2585 'ar_minor_edit' => $row->rev_minor_edit
,
2586 'ar_rev_id' => $row->rev_id
,
2587 'ar_parent_id' => $row->rev_parent_id
,
2589 * ar_text_id should probably not be written to when the multi content schema has
2590 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2591 * default for the field in WMF production currently so we must keep writing
2592 * writing until a default of 0 is set.
2593 * Task: https://phabricator.wikimedia.org/T190148
2594 * Copying the value from the revision table should not lead to any issues for now.
2596 'ar_len' => $row->rev_len
,
2597 'ar_page_id' => $id,
2598 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2599 'ar_sha1' => $row->rev_sha1
,
2600 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2601 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2603 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2604 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2606 if ( $wgContentHandlerUseDB ) {
2607 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2608 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2612 $rowsInsert[] = $rowInsert;
2613 $revids[] = $row->rev_id
;
2615 // Keep track of IP edits, so that the corresponding rows can
2616 // be deleted in the ip_changes table.
2617 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2618 $ipRevIds[] = $row->rev_id
;
2621 // Copy them into the archive table
2622 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2623 // Save this so we can pass it to the ArticleDeleteComplete hook.
2624 $archivedRevisionCount = $dbw->affectedRows();
2626 // Clone the title and wikiPage, so we have the information we need when
2627 // we log and run the ArticleDeleteComplete hook.
2628 $logTitle = clone $this->mTitle
;
2629 $wikiPageBeforeDelete = clone $this;
2631 // Now that it's safely backed up, delete it
2632 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2633 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2634 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2635 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2637 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
2638 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2641 // Also delete records from ip_changes as applicable.
2642 if ( count( $ipRevIds ) > 0 ) {
2643 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2646 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2647 $logtype = $suppress ?
'suppress' : 'delete';
2649 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2650 $logEntry->setPerformer( $deleter );
2651 $logEntry->setTarget( $logTitle );
2652 $logEntry->setComment( $reason );
2653 $logEntry->setTags( $tags );
2654 $logid = $logEntry->insert();
2656 $dbw->onTransactionPreCommitOrIdle(
2657 function () use ( $logEntry, $logid ) {
2658 // T58776: avoid deadlocks (especially from FileDeleteForm)
2659 $logEntry->publish( $logid );
2664 $dbw->endAtomic( __METHOD__
);
2666 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2668 Hooks
::run( 'ArticleDeleteComplete', [
2669 &$wikiPageBeforeDelete,
2675 $archivedRevisionCount
2677 $status->value
= $logid;
2679 // Show log excerpt on 404 pages rather than just a link
2680 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2681 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2682 $cache->set( $key, 1, $cache::TTL_DAY
);
2688 * Lock the page row for this title+id and return page_latest (or 0)
2690 * @return int Returns 0 if no row was found with this title+id
2693 public function lockAndGetLatest() {
2694 return (int)wfGetDB( DB_MASTER
)->selectField(
2698 'page_id' => $this->getId(),
2699 // Typically page_id is enough, but some code might try to do
2700 // updates assuming the title is the same, so verify that
2701 'page_namespace' => $this->getTitle()->getNamespace(),
2702 'page_title' => $this->getTitle()->getDBkey()
2710 * Do some database updates after deletion
2712 * @param int $id The page_id value of the page being deleted
2713 * @param Content|null $content Optional page content to be used when determining
2714 * the required updates. This may be needed because $this->getContent()
2715 * may already return null when the page proper was deleted.
2716 * @param Revision|null $revision The latest page revision
2717 * @param User|null $user The user that caused the deletion
2719 public function doDeleteUpdates(
2720 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2723 $countable = $this->isCountable();
2724 } catch ( Exception
$ex ) {
2725 // fallback for deleting broken pages for which we cannot load the content for
2726 // some reason. Note that doDeleteArticleReal() already logged this problem.
2730 // Update site status
2731 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2732 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2735 // Delete pagelinks, update secondary indexes, etc
2736 $updates = $this->getDeletionUpdates( $content );
2737 foreach ( $updates as $update ) {
2738 DeferredUpdates
::addUpdate( $update );
2741 $causeAgent = $user ?
$user->getName() : 'unknown';
2742 // Reparse any pages transcluding this page
2743 LinksUpdate
::queueRecursiveJobsForTable(
2744 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
2745 // Reparse any pages including this image
2746 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2747 LinksUpdate
::queueRecursiveJobsForTable(
2748 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
2752 self
::onArticleDelete( $this->mTitle
);
2753 ResourceLoaderWikiModule
::invalidateModuleCache(
2754 $this->mTitle
, $revision, null, wfWikiID()
2757 // Reset this object and the Title object
2758 $this->loadFromRow( false, self
::READ_LATEST
);
2761 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2765 * Roll back the most recent consecutive set of edits to a page
2766 * from the same user; fails if there are no eligible edits to
2767 * roll back to, e.g. user is the sole contributor. This function
2768 * performs permissions checks on $user, then calls commitRollback()
2769 * to do the dirty work
2771 * @todo Separate the business/permission stuff out from backend code
2772 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2774 * @param string $fromP Name of the user whose edits to rollback.
2775 * @param string $summary Custom summary. Set to default summary if empty.
2776 * @param string $token Rollback token.
2777 * @param bool $bot If true, mark all reverted edits as bot.
2779 * @param array &$resultDetails Array contains result-specific array of additional values
2780 * 'alreadyrolled' : 'current' (rev)
2781 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2783 * @param User $user The user performing the rollback
2784 * @param array|null $tags Change tags to apply to the rollback
2785 * Callers are responsible for permission checks
2786 * (with ChangeTags::canAddTagsAccompanyingChange)
2788 * @return array Array of errors, each error formatted as
2789 * array(messagekey, param1, param2, ...).
2790 * On success, the array is empty. This array can also be passed to
2791 * OutputPage::showPermissionsErrorPage().
2793 public function doRollback(
2794 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
2796 $resultDetails = null;
2798 // Check permissions
2799 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2800 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2801 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2803 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
2804 $errors[] = [ 'sessionfailure' ];
2807 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2808 $errors[] = [ 'actionthrottledtext' ];
2811 // If there were errors, bail out now
2812 if ( !empty( $errors ) ) {
2816 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
2820 * Backend implementation of doRollback(), please refer there for parameter
2821 * and return value documentation
2823 * NOTE: This function does NOT check ANY permissions, it just commits the
2824 * rollback to the DB. Therefore, you should only call this function direct-
2825 * ly if you want to use custom permissions checks. If you don't, use
2826 * doRollback() instead.
2827 * @param string $fromP Name of the user whose edits to rollback.
2828 * @param string $summary Custom summary. Set to default summary if empty.
2829 * @param bool $bot If true, mark all reverted edits as bot.
2831 * @param array &$resultDetails Contains result-specific array of additional values
2832 * @param User $guser The user performing the rollback
2833 * @param array|null $tags Change tags to apply to the rollback
2834 * Callers are responsible for permission checks
2835 * (with ChangeTags::canAddTagsAccompanyingChange)
2837 * @return array An array of error messages, as returned by Status::getErrorsArray()
2839 public function commitRollback( $fromP, $summary, $bot,
2840 &$resultDetails, User
$guser, $tags = null
2842 global $wgUseRCPatrol;
2844 $dbw = wfGetDB( DB_MASTER
);
2846 if ( wfReadOnly() ) {
2847 return [ [ 'readonlytext' ] ];
2850 // Begin revision creation cycle by creating a PageUpdater.
2851 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
2852 $updater = $this->newPageUpdater( $guser );
2853 $current = $updater->grabParentRevision();
2855 if ( is_null( $current ) ) {
2856 // Something wrong... no page?
2857 return [ [ 'notanarticle' ] ];
2860 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
2861 $legacyCurrent = new Revision( $current );
2862 $from = str_replace( '_', ' ', $fromP );
2864 // User name given should match up with the top revision.
2865 // If the revision's user is not visible, then $from should be empty.
2866 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
2867 $resultDetails = [ 'current' => $legacyCurrent ];
2868 return [ [ 'alreadyrolled',
2869 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2870 htmlspecialchars( $fromP ),
2871 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
2875 // Get the last edit not by this person...
2876 // Note: these may not be public values
2877 $actorWhere = ActorMigration
::newMigration()->getWhere(
2880 $current->getUser( RevisionRecord
::RAW
)
2883 $s = $dbw->selectRow(
2884 [ 'revision' ] +
$actorWhere['tables'],
2885 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
2887 'rev_page' => $current->getPageId(),
2888 'NOT(' . $actorWhere['conds'] . ')',
2892 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
2893 'ORDER BY' => 'rev_timestamp DESC'
2895 $actorWhere['joins']
2897 if ( $s === false ) {
2898 // No one else ever edited this page
2899 return [ [ 'cantrollback' ] ];
2900 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
2901 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
2903 // Only admins can see this text
2904 return [ [ 'notvisiblerev' ] ];
2907 // Generate the edit summary if necessary
2908 $target = $this->getRevisionStore()->getRevisionById(
2910 RevisionStore
::READ_LATEST
2912 if ( empty( $summary ) ) {
2913 if ( !$currentEditorForPublic ) { // no public user name
2914 $summary = wfMessage( 'revertpage-nouser' );
2916 $summary = wfMessage( 'revertpage' );
2919 $legacyTarget = new Revision( $target );
2920 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
2922 // Allow the custom summary to use the same args as the default message
2923 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2925 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
2926 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
2928 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2930 $contLang->timeanddate( $current->getTimestamp() )
2932 if ( $summary instanceof Message
) {
2933 $summary = $summary->params( $args )->inContentLanguage()->text();
2935 $summary = wfMsgReplaceArgs( $summary, $args );
2938 // Trim spaces on user supplied text
2939 $summary = trim( $summary );
2942 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
2944 if ( $guser->isAllowed( 'minoredit' ) ) {
2945 $flags |
= EDIT_MINOR
;
2948 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2949 $flags |
= EDIT_FORCE_BOT
;
2952 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
2953 $currentContent = $current->getContent( 'main' );
2954 $targetContent = $target->getContent( 'main' );
2955 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
2957 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
2958 $tags[] = 'mw-rollback';
2961 // Build rollback revision:
2962 // Restore old content
2963 // TODO: MCR: test this once we can store multiple slots
2964 foreach ( $target->getSlots()->getSlots() as $slot ) {
2965 $updater->inheritSlot( $slot );
2968 // Remove extra slots
2969 // TODO: MCR: test this once we can store multiple slots
2970 foreach ( $current->getSlotRoles() as $role ) {
2971 if ( !$target->hasSlot( $role ) ) {
2972 $updater->removeSlot( $role );
2976 $updater->setOriginalRevisionId( $target->getId() );
2977 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
2978 $updater->addTags( $tags );
2980 // TODO: this logic should not be in the storage layer, it's here for compatibility
2981 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
2982 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
2983 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
2984 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
2987 // Actually store the rollback
2988 $rev = $updater->saveRevision(
2989 CommentStoreComment
::newUnsavedComment( $summary ),
2993 // Set patrolling and bot flag on the edits, which gets rollbacked.
2994 // This is done even on edit failure to have patrolling in that case (T64157).
2996 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2997 // Mark all reverted edits as bot
3001 if ( $wgUseRCPatrol ) {
3002 // Mark all reverted edits as patrolled
3003 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3006 if ( count( $set ) ) {
3007 $actorWhere = ActorMigration
::newMigration()->getWhere(
3010 $current->getUser( RevisionRecord
::RAW
),
3013 $dbw->update( 'recentchanges', $set,
3015 'rc_cur_id' => $current->getPageId(),
3016 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3017 $actorWhere['conds'], // No tables/joins are needed for rc_user
3023 if ( !$updater->wasSuccessful() ) {
3024 return $updater->getStatus()->getErrorsArray();
3027 // Report if the edit was not created because it did not change the content.
3028 if ( $updater->isUnchanged() ) {
3029 $resultDetails = [ 'current' => $legacyCurrent ];
3030 return [ [ 'alreadyrolled',
3031 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3032 htmlspecialchars( $fromP ),
3033 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3037 if ( $changingContentModel ) {
3038 // If the content model changed during the rollback,
3039 // make sure it gets logged to Special:Log/contentmodel
3040 $log = new ManualLogEntry( 'contentmodel', 'change' );
3041 $log->setPerformer( $guser );
3042 $log->setTarget( $this->mTitle
);
3043 $log->setComment( $summary );
3044 $log->setParameters( [
3045 '4::oldmodel' => $currentContent->getModel(),
3046 '5::newmodel' => $targetContent->getModel(),
3049 $logId = $log->insert( $dbw );
3050 $log->publish( $logId );
3053 $revId = $rev->getId();
3055 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3058 'summary' => $summary,
3059 'current' => $legacyCurrent,
3060 'target' => $legacyTarget,
3065 // TODO: make this return a Status object and wrap $resultDetails in that.
3070 * The onArticle*() functions are supposed to be a kind of hooks
3071 * which should be called whenever any of the specified actions
3074 * This is a good place to put code to clear caches, for instance.
3076 * This is called on page move and undelete, as well as edit
3078 * @param Title $title
3080 public static function onArticleCreate( Title
$title ) {
3081 // TODO: move this into a PageEventEmitter service
3083 // Update existence markers on article/talk tabs...
3084 $other = $title->getOtherPage();
3086 $other->purgeSquid();
3088 $title->touchLinks();
3089 $title->purgeSquid();
3090 $title->deleteTitleProtection();
3092 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3094 // Invalidate caches of articles which include this page
3095 DeferredUpdates
::addUpdate(
3096 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3099 if ( $title->getNamespace() == NS_CATEGORY
) {
3100 // Load the Category object, which will schedule a job to create
3101 // the category table row if necessary. Checking a replica DB is ok
3102 // here, in the worst case it'll run an unnecessary recount job on
3103 // a category that probably doesn't have many members.
3104 Category
::newFromTitle( $title )->getID();
3109 * Clears caches when article is deleted
3111 * @param Title $title
3113 public static function onArticleDelete( Title
$title ) {
3114 // TODO: move this into a PageEventEmitter service
3116 // Update existence markers on article/talk tabs...
3117 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3118 BacklinkCache
::get( $title )->clear();
3119 $other = $title->getOtherPage();
3121 $other->purgeSquid();
3123 $title->touchLinks();
3124 $title->purgeSquid();
3126 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3129 HTMLFileCache
::clearFileCache( $title );
3130 InfoAction
::invalidateCache( $title );
3133 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3134 MessageCache
::singleton()->updateMessageOverride( $title, null );
3138 if ( $title->getNamespace() == NS_FILE
) {
3139 DeferredUpdates
::addUpdate(
3140 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3145 if ( $title->getNamespace() == NS_USER_TALK
) {
3146 $user = User
::newFromName( $title->getText(), false );
3148 $user->setNewtalk( false );
3153 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3157 * Purge caches on page update etc
3159 * @param Title $title
3160 * @param Revision|null $revision Revision that was just saved, may be null
3161 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3162 * If not given, all slots are assumed to have changed.
3164 public static function onArticleEdit(
3166 Revision
$revision = null,
3167 $slotsChanged = null
3169 // TODO: move this into a PageEventEmitter service
3171 if ( $slotsChanged === null ||
in_array( 'main', $slotsChanged ) ) {
3172 // Invalidate caches of articles which include this page.
3173 // Only for the main slot, because only the main slot is transcluded.
3174 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3175 DeferredUpdates
::addUpdate(
3176 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3180 // Invalidate the caches of all pages which redirect here
3181 DeferredUpdates
::addUpdate(
3182 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3185 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3187 // Purge CDN for this page only
3188 $title->purgeSquid();
3189 // Clear file cache for this page only
3190 HTMLFileCache
::clearFileCache( $title );
3192 $revid = $revision ?
$revision->getId() : null;
3193 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3194 InfoAction
::invalidateCache( $title, $revid );
3201 * Returns a list of categories this page is a member of.
3202 * Results will include hidden categories
3204 * @return TitleArray
3206 public function getCategories() {
3207 $id = $this->getId();
3209 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3212 $dbr = wfGetDB( DB_REPLICA
);
3213 $res = $dbr->select( 'categorylinks',
3214 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3215 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3216 // as not being aliases, and NS_CATEGORY is numeric
3217 [ 'cl_from' => $id ],
3220 return TitleArray
::newFromResult( $res );
3224 * Returns a list of hidden categories this page is a member of.
3225 * Uses the page_props and categorylinks tables.
3227 * @return array Array of Title objects
3229 public function getHiddenCategories() {
3231 $id = $this->getId();
3237 $dbr = wfGetDB( DB_REPLICA
);
3238 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3240 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3241 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3244 if ( $res !== false ) {
3245 foreach ( $res as $row ) {
3246 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3254 * Auto-generates a deletion reason
3256 * @param bool &$hasHistory Whether the page has a history
3257 * @return string|bool String containing deletion reason or empty string, or boolean false
3258 * if no revision occurred
3260 public function getAutoDeleteReason( &$hasHistory ) {
3261 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3265 * Update all the appropriate counts in the category table, given that
3266 * we've added the categories $added and deleted the categories $deleted.
3268 * This should only be called from deferred updates or jobs to avoid contention.
3270 * @param array $added The names of categories that were added
3271 * @param array $deleted The names of categories that were deleted
3272 * @param int $id Page ID (this should be the original deleted page ID)
3274 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3275 $id = $id ?
: $this->getId();
3276 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3278 $addFields = [ 'cat_pages = cat_pages + 1' ];
3279 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3280 if ( $type !== 'page' ) {
3281 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3282 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3285 $dbw = wfGetDB( DB_MASTER
);
3287 if ( count( $added ) ) {
3288 $existingAdded = $dbw->selectFieldValues(
3291 [ 'cat_title' => $added ],
3295 // For category rows that already exist, do a plain
3296 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3297 // to avoid creating gaps in the cat_id sequence.
3298 if ( count( $existingAdded ) ) {
3302 [ 'cat_title' => $existingAdded ],
3307 $missingAdded = array_diff( $added, $existingAdded );
3308 if ( count( $missingAdded ) ) {
3310 foreach ( $missingAdded as $cat ) {
3312 'cat_title' => $cat,
3314 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3315 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3328 if ( count( $deleted ) ) {
3332 [ 'cat_title' => $deleted ],
3337 foreach ( $added as $catName ) {
3338 $cat = Category
::newFromName( $catName );
3339 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3342 foreach ( $deleted as $catName ) {
3343 $cat = Category
::newFromName( $catName );
3344 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3345 // Refresh counts on categories that should be empty now (after commit, T166757)
3346 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3347 $cat->refreshCountsIfEmpty();
3353 * Opportunistically enqueue link update jobs given fresh parser output if useful
3355 * @param ParserOutput $parserOutput Current version page output
3358 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3359 if ( wfReadOnly() ) {
3363 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3364 [ $this, $this->mTitle
, $parserOutput ]
3369 $config = RequestContext
::getMain()->getConfig();
3372 'isOpportunistic' => true,
3373 'rootJobTimestamp' => $parserOutput->getCacheTime()
3376 if ( $this->mTitle
->areRestrictionsCascading() ) {
3377 // If the page is cascade protecting, the links should really be up-to-date
3378 JobQueueGroup
::singleton()->lazyPush(
3379 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3381 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3382 // Assume the output contains "dynamic" time/random based magic words.
3383 // Only update pages that expired due to dynamic content and NOT due to edits
3384 // to referenced templates/files. When the cache expires due to dynamic content,
3385 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3386 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3387 // template/file edit already triggered recursive RefreshLinksJob jobs.
3388 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3389 // If a page is uncacheable, do not keep spamming a job for it.
3390 // Although it would be de-duplicated, it would still waste I/O.
3391 $cache = ObjectCache
::getLocalClusterInstance();
3392 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3393 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3394 if ( $cache->add( $key, time(), $ttl ) ) {
3395 JobQueueGroup
::singleton()->lazyPush(
3396 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3404 * Returns a list of updates to be performed when this page is deleted. The
3405 * updates should remove any information about this page from secondary data
3406 * stores such as links tables.
3408 * @param Content|null $content Optional Content object for determining the
3409 * necessary updates.
3410 * @return DeferrableUpdate[]
3412 public function getDeletionUpdates( Content
$content = null ) {
3414 // load content object, which may be used to determine the necessary updates.
3415 // XXX: the content may not be needed to determine the updates.
3417 $content = $this->getContent( Revision
::RAW
);
3418 } catch ( Exception
$ex ) {
3419 // If we can't load the content, something is wrong. Perhaps that's why
3420 // the user is trying to delete the page, so let's not fail in that case.
3421 // Note that doDeleteArticleReal() will already have logged an issue with
3422 // loading the content.
3429 $updates = $content->getDeletionUpdates( $this );
3432 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3437 * Whether this content displayed on this page
3438 * comes from the local database
3443 public function isLocal() {
3448 * The display name for the site this content
3449 * come from. If a subclass overrides isLocal(),
3450 * this could return something other than the
3456 public function getWikiDisplayName() {
3462 * Get the source URL for the content on this page,
3463 * typically the canonical URL, but may be a remote
3464 * link if the content comes from another site
3469 public function getSourceURL() {
3470 return $this->getTitle()->getCanonicalURL();
3474 * @param WANObjectCache $cache
3478 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3479 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3481 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );