3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Revision\RevisionRenderer
;
27 use MediaWiki\Storage\DerivedPageDataUpdater
;
28 use MediaWiki\Storage\PageUpdater
;
29 use MediaWiki\Storage\RevisionRecord
;
30 use MediaWiki\Storage\RevisionSlotsUpdate
;
31 use MediaWiki\Storage\RevisionStore
;
32 use Wikimedia\Assert\Assert
;
33 use Wikimedia\Rdbms\FakeResultWrapper
;
34 use Wikimedia\Rdbms\IDatabase
;
35 use Wikimedia\Rdbms\LoadBalancer
;
38 * Class representing a MediaWiki article and history.
40 * Some fields are public only for backwards-compatibility. Use accessors.
41 * In the past, this class was part of Article.php and everything was public.
43 class WikiPage
implements Page
, IDBAccessObject
{
44 // Constants for $mDataLoadedFrom and related
49 public $mTitle = null;
54 public $mDataLoaded = false; // !< Boolean
55 public $mIsRedirect = false; // !< Boolean
56 public $mLatest = false; // !< Integer (false means "not loaded")
59 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
60 public $mPreparedEdit = false;
65 protected $mId = null;
68 * @var int One of the READ_* constants
70 protected $mDataLoadedFrom = self
::READ_NONE
;
75 protected $mRedirectTarget = null;
80 protected $mLastRevision = null;
83 * @var string Timestamp of the current revision or empty string if not loaded
85 protected $mTimestamp = '';
90 protected $mTouched = '19700101000000';
95 protected $mLinksUpdated = '19700101000000';
98 * @var DerivedPageDataUpdater|null
100 private $derivedDataUpdater = null;
103 * Constructor and clear the article
104 * @param Title $title Reference to a Title object.
106 public function __construct( Title
$title ) {
107 $this->mTitle
= $title;
111 * Makes sure that the mTitle object is cloned
112 * to the newly cloned WikiPage.
114 public function __clone() {
115 $this->mTitle
= clone $this->mTitle
;
119 * Create a WikiPage object of the appropriate class for the given title.
121 * @param Title $title
123 * @throws MWException
124 * @return WikiPage|WikiCategoryPage|WikiFilePage
126 public static function factory( Title
$title ) {
127 $ns = $title->getNamespace();
129 if ( $ns == NS_MEDIA
) {
130 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
131 } elseif ( $ns < 0 ) {
132 throw new MWException( "Invalid or virtual namespace $ns given." );
136 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
142 $page = new WikiFilePage( $title );
145 $page = new WikiCategoryPage( $title );
148 $page = new WikiPage( $title );
155 * Constructor from a page id
157 * @param int $id Article ID to load
158 * @param string|int $from One of the following values:
159 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
160 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
162 * @return WikiPage|null
164 public static function newFromID( $id, $from = 'fromdb' ) {
165 // page ids are never 0 or negative, see T63166
170 $from = self
::convertSelectType( $from );
171 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
172 $pageQuery = self
::getQueryInfo();
173 $row = $db->selectRow(
174 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
175 [], $pageQuery['joins']
180 return self
::newFromRow( $row, $from );
184 * Constructor from a database row
187 * @param object $row Database row containing at least fields returned by selectFields().
188 * @param string|int $from Source of $data:
189 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
190 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
191 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
194 public static function newFromRow( $row, $from = 'fromdb' ) {
195 $page = self
::factory( Title
::newFromRow( $row ) );
196 $page->loadFromRow( $row, $from );
201 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
203 * @param object|string|int $type
206 protected static function convertSelectType( $type ) {
209 return self
::READ_NORMAL
;
211 return self
::READ_LATEST
;
213 return self
::READ_LOCKING
;
215 // It may already be an integer or whatever else
221 * @return RevisionStore
223 private function getRevisionStore() {
224 return MediaWikiServices
::getInstance()->getRevisionStore();
228 * @return RevisionRenderer
230 private function getRevisionRenderer() {
231 return MediaWikiServices
::getInstance()->getRevisionRenderer();
235 * @return ParserCache
237 private function getParserCache() {
238 return MediaWikiServices
::getInstance()->getParserCache();
242 * @return LoadBalancer
244 private function getDBLoadBalancer() {
245 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
249 * @todo Move this UI stuff somewhere else
251 * @see ContentHandler::getActionOverrides
254 public function getActionOverrides() {
255 return $this->getContentHandler()->getActionOverrides();
259 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
261 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
263 * @return ContentHandler
267 public function getContentHandler() {
268 return ContentHandler
::getForModelID( $this->getContentModel() );
272 * Get the title object of the article
273 * @return Title Title object of this page
275 public function getTitle() {
276 return $this->mTitle
;
283 public function clear() {
284 $this->mDataLoaded
= false;
285 $this->mDataLoadedFrom
= self
::READ_NONE
;
287 $this->clearCacheFields();
291 * Clear the object cache fields
294 protected function clearCacheFields() {
296 $this->mRedirectTarget
= null; // Title object if set
297 $this->mLastRevision
= null; // Latest revision
298 $this->mTouched
= '19700101000000';
299 $this->mLinksUpdated
= '19700101000000';
300 $this->mTimestamp
= '';
301 $this->mIsRedirect
= false;
302 $this->mLatest
= false;
303 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
304 // checks the requested rev ID and content against the cached one. For most
305 // content types, the output should not change during the lifetime of this cache.
306 // Clearing it can cause extra parses on edit for no reason.
310 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
314 public function clearPreparedEdit() {
315 $this->mPreparedEdit
= false;
319 * Return the list of revision fields that should be selected to create
322 * @deprecated since 1.31, use self::getQueryInfo() instead.
325 public static function selectFields() {
326 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
328 wfDeprecated( __METHOD__
, '1.31' );
339 'page_links_updated',
344 if ( $wgContentHandlerUseDB ) {
345 $fields[] = 'page_content_model';
348 if ( $wgPageLanguageUseDB ) {
349 $fields[] = 'page_lang';
356 * Return the tables, fields, and join conditions to be selected to create
359 * @return array With three keys:
360 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
361 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
362 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
364 public static function getQueryInfo() {
365 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
368 'tables' => [ 'page' ],
378 'page_links_updated',
385 if ( $wgContentHandlerUseDB ) {
386 $ret['fields'][] = 'page_content_model';
389 if ( $wgPageLanguageUseDB ) {
390 $ret['fields'][] = 'page_lang';
397 * Fetch a page record with the given conditions
398 * @param IDatabase $dbr
399 * @param array $conditions
400 * @param array $options
401 * @return object|bool Database result resource, or false on failure
403 protected function pageData( $dbr, $conditions, $options = [] ) {
404 $pageQuery = self
::getQueryInfo();
406 // Avoid PHP 7.1 warning of passing $this by reference
409 Hooks
::run( 'ArticlePageDataBefore', [
410 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
413 $row = $dbr->selectRow(
414 $pageQuery['tables'],
415 $pageQuery['fields'],
422 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
428 * Fetch a page record matching the Title object's namespace and title
429 * using a sanitized title string
431 * @param IDatabase $dbr
432 * @param Title $title
433 * @param array $options
434 * @return object|bool Database result resource, or false on failure
436 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
437 return $this->pageData( $dbr, [
438 'page_namespace' => $title->getNamespace(),
439 'page_title' => $title->getDBkey() ], $options );
443 * Fetch a page record matching the requested ID
445 * @param IDatabase $dbr
447 * @param array $options
448 * @return object|bool Database result resource, or false on failure
450 public function pageDataFromId( $dbr, $id, $options = [] ) {
451 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
455 * Load the object from a given source by title
457 * @param object|string|int $from One of the following:
458 * - A DB query result object.
459 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
460 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
461 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
462 * using SELECT FOR UPDATE.
466 public function loadPageData( $from = 'fromdb' ) {
467 $from = self
::convertSelectType( $from );
468 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
469 // We already have the data from the correct location, no need to load it twice.
473 if ( is_int( $from ) ) {
474 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
475 $loadBalancer = $this->getDBLoadBalancer();
476 $db = $loadBalancer->getConnection( $index );
477 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
480 && $index == DB_REPLICA
481 && $loadBalancer->getServerCount() > 1
482 && $loadBalancer->hasOrMadeRecentMasterChanges()
484 $from = self
::READ_LATEST
;
485 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
486 $db = $loadBalancer->getConnection( $index );
487 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
490 // No idea from where the caller got this data, assume replica DB.
492 $from = self
::READ_NORMAL
;
495 $this->loadFromRow( $data, $from );
499 * Checks whether the page data was loaded using the given database access mode (or better).
503 * @param string|int $from One of the following:
504 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
505 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
506 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
507 * using SELECT FOR UPDATE.
511 public function wasLoadedFrom( $from ) {
512 $from = self
::convertSelectType( $from );
514 if ( !is_int( $from ) ) {
515 // No idea from where the caller got this data, assume replica DB.
516 $from = self
::READ_NORMAL
;
519 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
527 * Load the object from a database row
530 * @param object|bool $data DB row containing fields returned by selectFields() or false
531 * @param string|int $from One of the following:
532 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
533 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
534 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
535 * the master DB using SELECT FOR UPDATE
537 public function loadFromRow( $data, $from ) {
538 $lc = MediaWikiServices
::getInstance()->getLinkCache();
539 $lc->clearLink( $this->mTitle
);
542 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
544 $this->mTitle
->loadFromRow( $data );
546 // Old-fashioned restrictions
547 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
549 $this->mId
= intval( $data->page_id
);
550 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
551 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
552 $this->mIsRedirect
= intval( $data->page_is_redirect
);
553 $this->mLatest
= intval( $data->page_latest
);
554 // T39225: $latest may no longer match the cached latest Revision object.
555 // Double-check the ID of any cached latest Revision object for consistency.
556 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
557 $this->mLastRevision
= null;
558 $this->mTimestamp
= '';
561 $lc->addBadLinkObj( $this->mTitle
);
563 $this->mTitle
->loadFromRow( false );
565 $this->clearCacheFields();
570 $this->mDataLoaded
= true;
571 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
575 * @return int Page ID
577 public function getId() {
578 if ( !$this->mDataLoaded
) {
579 $this->loadPageData();
585 * @return bool Whether or not the page exists in the database
587 public function exists() {
588 if ( !$this->mDataLoaded
) {
589 $this->loadPageData();
591 return $this->mId
> 0;
595 * Check if this page is something we're going to be showing
596 * some sort of sensible content for. If we return false, page
597 * views (plain action=view) will return an HTTP 404 response,
598 * so spiders and robots can know they're following a bad link.
602 public function hasViewableContent() {
603 return $this->mTitle
->isKnown();
607 * Tests if the article content represents a redirect
611 public function isRedirect() {
612 if ( !$this->mDataLoaded
) {
613 $this->loadPageData();
616 return (bool)$this->mIsRedirect
;
620 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
622 * Will use the revisions actual content model if the page exists,
623 * and the page's default if the page doesn't exist yet.
629 public function getContentModel() {
630 if ( $this->exists() ) {
631 $cache = ObjectCache
::getMainWANInstance();
633 return $cache->getWithSetCallback(
634 $cache->makeKey( 'page-content-model', $this->getLatest() ),
637 $rev = $this->getRevision();
639 // Look at the revision's actual content model
640 return $rev->getContentModel();
642 $title = $this->mTitle
->getPrefixedDBkey();
643 wfWarn( "Page $title exists but has no (visible) revisions!" );
644 return $this->mTitle
->getContentModel();
650 // use the default model for this page
651 return $this->mTitle
->getContentModel();
655 * Loads page_touched and returns a value indicating if it should be used
656 * @return bool True if this page exists and is not a redirect
658 public function checkTouched() {
659 if ( !$this->mDataLoaded
) {
660 $this->loadPageData();
662 return ( $this->mId
&& !$this->mIsRedirect
);
666 * Get the page_touched field
667 * @return string Containing GMT timestamp
669 public function getTouched() {
670 if ( !$this->mDataLoaded
) {
671 $this->loadPageData();
673 return $this->mTouched
;
677 * Get the page_links_updated field
678 * @return string|null Containing GMT timestamp
680 public function getLinksTimestamp() {
681 if ( !$this->mDataLoaded
) {
682 $this->loadPageData();
684 return $this->mLinksUpdated
;
688 * Get the page_latest field
689 * @return int The rev_id of current revision
691 public function getLatest() {
692 if ( !$this->mDataLoaded
) {
693 $this->loadPageData();
695 return (int)$this->mLatest
;
699 * Get the Revision object of the oldest revision
700 * @return Revision|null
702 public function getOldestRevision() {
703 // Try using the replica DB first, then try the master
704 $rev = $this->mTitle
->getFirstRevision();
706 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
712 * Loads everything except the text
713 * This isn't necessary for all uses, so it's only done if needed.
715 protected function loadLastEdit() {
716 if ( $this->mLastRevision
!== null ) {
717 return; // already loaded
720 $latest = $this->getLatest();
722 return; // page doesn't exist or is missing page_latest info
725 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
726 // T39225: if session S1 loads the page row FOR UPDATE, the result always
727 // includes the latest changes committed. This is true even within REPEATABLE-READ
728 // transactions, where S1 normally only sees changes committed before the first S1
729 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
730 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
731 // happened after the first S1 SELECT.
732 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
733 $flags = Revision
::READ_LOCKING
;
734 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
735 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
736 // Bug T93976: if page_latest was loaded from the master, fetch the
737 // revision from there as well, as it may not exist yet on a replica DB.
738 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
739 $flags = Revision
::READ_LATEST
;
740 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
742 $dbr = wfGetDB( DB_REPLICA
);
743 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
746 if ( $revision ) { // sanity
747 $this->setLastEdit( $revision );
752 * Set the latest revision
753 * @param Revision $revision
755 protected function setLastEdit( Revision
$revision ) {
756 $this->mLastRevision
= $revision;
757 $this->mTimestamp
= $revision->getTimestamp();
761 * Get the latest revision
762 * @return Revision|null
764 public function getRevision() {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
;
773 * Get the content of the current revision. No side-effects...
775 * @param int $audience One of:
776 * Revision::FOR_PUBLIC to be displayed to all users
777 * Revision::FOR_THIS_USER to be displayed to $wgUser
778 * Revision::RAW get the text regardless of permissions
779 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
780 * to the $audience parameter
781 * @return Content|null The content of the current revision
785 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
786 $this->loadLastEdit();
787 if ( $this->mLastRevision
) {
788 return $this->mLastRevision
->getContent( $audience, $user );
794 * @return string MW timestamp of last article revision
796 public function getTimestamp() {
797 // Check if the field has been filled by WikiPage::setTimestamp()
798 if ( !$this->mTimestamp
) {
799 $this->loadLastEdit();
802 return wfTimestamp( TS_MW
, $this->mTimestamp
);
806 * Set the page timestamp (use only to avoid DB queries)
807 * @param string $ts MW timestamp of last article revision
810 public function setTimestamp( $ts ) {
811 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
815 * @param int $audience One of:
816 * Revision::FOR_PUBLIC to be displayed to all users
817 * Revision::FOR_THIS_USER to be displayed to the given user
818 * Revision::RAW get the text regardless of permissions
819 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
820 * to the $audience parameter
821 * @return int User ID for the user that made the last article revision
823 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
824 $this->loadLastEdit();
825 if ( $this->mLastRevision
) {
826 return $this->mLastRevision
->getUser( $audience, $user );
833 * Get the User object of the user who created the page
834 * @param int $audience One of:
835 * Revision::FOR_PUBLIC to be displayed to all users
836 * Revision::FOR_THIS_USER to be displayed to the given user
837 * Revision::RAW get the text regardless of permissions
838 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
839 * to the $audience parameter
842 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
843 $revision = $this->getOldestRevision();
845 $userName = $revision->getUserText( $audience, $user );
846 return User
::newFromName( $userName, false );
853 * @param int $audience One of:
854 * Revision::FOR_PUBLIC to be displayed to all users
855 * Revision::FOR_THIS_USER to be displayed to the given user
856 * Revision::RAW get the text regardless of permissions
857 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
858 * to the $audience parameter
859 * @return string Username of the user that made the last article revision
861 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
862 $this->loadLastEdit();
863 if ( $this->mLastRevision
) {
864 return $this->mLastRevision
->getUserText( $audience, $user );
871 * @param int $audience One of:
872 * Revision::FOR_PUBLIC to be displayed to all users
873 * Revision::FOR_THIS_USER to be displayed to the given user
874 * Revision::RAW get the text regardless of permissions
875 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
876 * to the $audience parameter
877 * @return string Comment stored for the last article revision
879 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
880 $this->loadLastEdit();
881 if ( $this->mLastRevision
) {
882 return $this->mLastRevision
->getComment( $audience, $user );
889 * Returns true if last revision was marked as "minor edit"
891 * @return bool Minor edit indicator for the last article revision.
893 public function getMinorEdit() {
894 $this->loadLastEdit();
895 if ( $this->mLastRevision
) {
896 return $this->mLastRevision
->isMinor();
903 * Determine whether a page would be suitable for being counted as an
904 * article in the site_stats table based on the title & its content
906 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
907 * if false, the current database state will be used
910 public function isCountable( $editInfo = false ) {
911 global $wgArticleCountMethod;
913 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
915 if ( !$this->mTitle
->isContentPage() ) {
920 // NOTE: only the main slot can make a page a redirect
921 $content = $editInfo->pstContent
;
923 $content = $this->getContent();
926 if ( !$content ||
$content->isRedirect() ) {
932 if ( $wgArticleCountMethod === 'link' ) {
933 // nasty special case to avoid re-parsing to detect links
936 // ParserOutput::getLinks() is a 2D array of page links, so
937 // to be really correct we would need to recurse in the array
938 // but the main array should only have items in it if there are
940 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
942 // NOTE: keep in sync with revisionRenderer::getLinkCount
943 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
944 [ 'pl_from' => $this->getId() ], __METHOD__
);
948 return $content->isCountable( $hasLinks );
952 * If this page is a redirect, get its target
954 * The target will be fetched from the redirect table if possible.
955 * If this page doesn't have an entry there, call insertRedirect()
956 * @return Title|null Title object, or null if this page is not a redirect
958 public function getRedirectTarget() {
959 if ( !$this->mTitle
->isRedirect() ) {
963 if ( $this->mRedirectTarget
!== null ) {
964 return $this->mRedirectTarget
;
967 // Query the redirect table
968 $dbr = wfGetDB( DB_REPLICA
);
969 $row = $dbr->selectRow( 'redirect',
970 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
971 [ 'rd_from' => $this->getId() ],
975 // rd_fragment and rd_interwiki were added later, populate them if empty
976 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
977 $this->mRedirectTarget
= Title
::makeTitle(
978 $row->rd_namespace
, $row->rd_title
,
979 $row->rd_fragment
, $row->rd_interwiki
981 return $this->mRedirectTarget
;
984 // This page doesn't have an entry in the redirect table
985 $this->mRedirectTarget
= $this->insertRedirect();
986 return $this->mRedirectTarget
;
990 * Insert an entry for this page into the redirect table if the content is a redirect
992 * The database update will be deferred via DeferredUpdates
994 * Don't call this function directly unless you know what you're doing.
995 * @return Title|null Title object or null if not a redirect
997 public function insertRedirect() {
998 $content = $this->getContent();
999 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1004 // Update the DB post-send if the page has not cached since now
1005 $latest = $this->getLatest();
1006 DeferredUpdates
::addCallableUpdate(
1007 function () use ( $retval, $latest ) {
1008 $this->insertRedirectEntry( $retval, $latest );
1010 DeferredUpdates
::POSTSEND
,
1011 wfGetDB( DB_MASTER
)
1018 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1019 * @param Title $rt Redirect target
1020 * @param int|null $oldLatest Prior page_latest for check and set
1022 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1023 $dbw = wfGetDB( DB_MASTER
);
1024 $dbw->startAtomic( __METHOD__
);
1026 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1030 'rd_from' => $this->getId(),
1031 'rd_namespace' => $rt->getNamespace(),
1032 'rd_title' => $rt->getDBkey(),
1033 'rd_fragment' => $rt->getFragment(),
1034 'rd_interwiki' => $rt->getInterwiki(),
1038 'rd_namespace' => $rt->getNamespace(),
1039 'rd_title' => $rt->getDBkey(),
1040 'rd_fragment' => $rt->getFragment(),
1041 'rd_interwiki' => $rt->getInterwiki(),
1047 $dbw->endAtomic( __METHOD__
);
1051 * Get the Title object or URL this page redirects to
1053 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1055 public function followRedirect() {
1056 return $this->getRedirectURL( $this->getRedirectTarget() );
1060 * Get the Title object or URL to use for a redirect. We use Title
1061 * objects for same-wiki, non-special redirects and URLs for everything
1063 * @param Title $rt Redirect target
1064 * @return bool|Title|string False, Title object of local target, or string with URL
1066 public function getRedirectURL( $rt ) {
1071 if ( $rt->isExternal() ) {
1072 if ( $rt->isLocal() ) {
1073 // Offsite wikis need an HTTP redirect.
1074 // This can be hard to reverse and may produce loops,
1075 // so they may be disabled in the site configuration.
1076 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1077 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1079 // External pages without "local" bit set are not valid
1085 if ( $rt->isSpecialPage() ) {
1086 // Gotta handle redirects to special pages differently:
1087 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1088 // Some pages are not valid targets.
1089 if ( $rt->isValidRedirectTarget() ) {
1090 return $rt->getFullURL();
1100 * Get a list of users who have edited this article, not including the user who made
1101 * the most recent revision, which you can get from $article->getUser() if you want it
1102 * @return UserArrayFromResult
1104 public function getContributors() {
1105 // @todo: This is expensive; cache this info somewhere.
1107 $dbr = wfGetDB( DB_REPLICA
);
1109 $actorMigration = ActorMigration
::newMigration();
1110 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1112 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1115 'user_id' => $actorQuery['fields']['rev_user'],
1116 'user_name' => $actorQuery['fields']['rev_user_text'],
1117 'actor_id' => $actorQuery['fields']['rev_actor'],
1118 'user_real_name' => 'MIN(user_real_name)',
1119 'timestamp' => 'MAX(rev_timestamp)',
1122 $conds = [ 'rev_page' => $this->getId() ];
1124 // The user who made the top revision gets credited as "this page was last edited by
1125 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1126 $user = $this->getUser()
1127 ? User
::newFromId( $this->getUser() )
1128 : User
::newFromName( $this->getUserText(), false );
1129 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1132 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1135 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1136 ] +
$actorQuery['joins'];
1139 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1140 'ORDER BY' => 'timestamp DESC',
1143 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1144 return new UserArrayFromResult( $res );
1148 * Should the parser cache be used?
1150 * @param ParserOptions $parserOptions ParserOptions to check
1154 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1155 return $parserOptions->getStubThreshold() == 0
1157 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1158 && $this->getContentHandler()->isParserCacheSupported();
1162 * Get a ParserOutput for the given ParserOptions and revision ID.
1164 * The parser cache will be used if possible. Cache misses that result
1165 * in parser runs are debounced with PoolCounter.
1168 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1169 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1170 * get the current revision (default value)
1171 * @param bool $forceParse Force reindexing, regardless of cache settings
1172 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1174 public function getParserOutput(
1175 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1178 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1180 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1181 throw new InvalidArgumentException(
1182 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1186 wfDebug( __METHOD__
.
1187 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1188 if ( $parserOptions->getStubThreshold() ) {
1189 wfIncrStats( 'pcache.miss.stub' );
1192 if ( $useParserCache ) {
1193 $parserOutput = $this->getParserCache()
1194 ->get( $this, $parserOptions );
1195 if ( $parserOutput !== false ) {
1196 return $parserOutput;
1200 if ( $oldid === null ||
$oldid === 0 ) {
1201 $oldid = $this->getLatest();
1204 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1207 return $pool->getParserOutput();
1211 * Do standard deferred updates after page view (existing or missing page)
1212 * @param User $user The relevant user
1213 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1215 public function doViewUpdates( User
$user, $oldid = 0 ) {
1216 if ( wfReadOnly() ) {
1220 // Update newtalk / watchlist notification status;
1221 // Avoid outage if the master is not reachable by using a deferred updated
1222 DeferredUpdates
::addCallableUpdate(
1223 function () use ( $user, $oldid ) {
1224 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1226 $user->clearNotification( $this->mTitle
, $oldid );
1228 DeferredUpdates
::PRESEND
1233 * Perform the actions of a page purging
1235 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1236 * controlled how much purging was done.
1238 public function doPurge() {
1239 // Avoid PHP 7.1 warning of passing $this by reference
1242 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1246 $this->mTitle
->invalidateCache();
1249 HTMLFileCache
::clearFileCache( $this->getTitle() );
1250 // Send purge after above page_touched update was committed
1251 DeferredUpdates
::addUpdate(
1252 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1253 DeferredUpdates
::PRESEND
1256 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1257 $messageCache = MessageCache
::singleton();
1258 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1265 * Insert a new empty page record for this article.
1266 * This *must* be followed up by creating a revision
1267 * and running $this->updateRevisionOn( ... );
1268 * or else the record will be left in a funky state.
1269 * Best if all done inside a transaction.
1271 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1273 * @param IDatabase $dbw
1274 * @param int|null $pageId Custom page ID that will be used for the insert statement
1276 * @return bool|int The newly created page_id key; false if the row was not
1277 * inserted, e.g. because the title already existed or because the specified
1278 * page ID is already in use.
1280 public function insertOn( $dbw, $pageId = null ) {
1281 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1285 'page_namespace' => $this->mTitle
->getNamespace(),
1286 'page_title' => $this->mTitle
->getDBkey(),
1287 'page_restrictions' => '',
1288 'page_is_redirect' => 0, // Will set this shortly...
1290 'page_random' => wfRandom(),
1291 'page_touched' => $dbw->timestamp(),
1292 'page_latest' => 0, // Fill this in shortly...
1293 'page_len' => 0, // Fill this in shortly...
1294 ] +
$pageIdForInsert,
1299 if ( $dbw->affectedRows() > 0 ) {
1300 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1301 $this->mId
= $newid;
1302 $this->mTitle
->resetArticleID( $newid );
1306 return false; // nothing changed
1311 * Update the page record to point to a newly saved revision.
1313 * @todo Factor out into a PageStore service, or move into PageUpdater.
1315 * @param IDatabase $dbw
1316 * @param Revision $revision For ID number, and text used to set
1317 * length and redirect status fields
1318 * @param int|null $lastRevision If given, will not overwrite the page field
1319 * when different from the currently set value.
1320 * Giving 0 indicates the new page flag should be set on.
1321 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1322 * removing rows in redirect table.
1323 * @return bool Success; false if the page row was missing or page_latest changed
1325 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1326 $lastRevIsRedirect = null
1328 global $wgContentHandlerUseDB;
1330 // TODO: move into PageUpdater or PageStore
1331 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1332 // and in the compat stub!
1334 // Assertion to try to catch T92046
1335 if ( (int)$revision->getId() === 0 ) {
1336 throw new InvalidArgumentException(
1337 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1341 $content = $revision->getContent();
1342 $len = $content ?
$content->getSize() : 0;
1343 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1345 $conditions = [ 'page_id' => $this->getId() ];
1347 if ( !is_null( $lastRevision ) ) {
1348 // An extra check against threads stepping on each other
1349 $conditions['page_latest'] = $lastRevision;
1352 $revId = $revision->getId();
1353 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1356 'page_latest' => $revId,
1357 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1358 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1359 'page_is_redirect' => $rt !== null ?
1 : 0,
1363 if ( $wgContentHandlerUseDB ) {
1364 $row['page_content_model'] = $revision->getContentModel();
1367 $dbw->update( 'page',
1372 $result = $dbw->affectedRows() > 0;
1374 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1375 $this->setLastEdit( $revision );
1376 $this->mLatest
= $revision->getId();
1377 $this->mIsRedirect
= (bool)$rt;
1378 // Update the LinkCache.
1379 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1380 $linkCache->addGoodLinkObj(
1386 $revision->getContentModel()
1394 * Add row to the redirect table if this is a redirect, remove otherwise.
1396 * @param IDatabase $dbw
1397 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1398 * or NULL if this is not a redirect
1399 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1400 * removing rows in redirect table.
1401 * @return bool True on success, false on failure
1404 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1405 // Always update redirects (target link might have changed)
1406 // Update/Insert if we don't know if the last revision was a redirect or not
1407 // Delete if changing from redirect to non-redirect
1408 $isRedirect = !is_null( $redirectTitle );
1410 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1414 if ( $isRedirect ) {
1415 $this->insertRedirectEntry( $redirectTitle );
1417 // This is not a redirect, remove row from redirect table
1418 $where = [ 'rd_from' => $this->getId() ];
1419 $dbw->delete( 'redirect', $where, __METHOD__
);
1422 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1423 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1426 return ( $dbw->affectedRows() != 0 );
1430 * If the given revision is newer than the currently set page_latest,
1431 * update the page record. Otherwise, do nothing.
1433 * @deprecated since 1.24, use updateRevisionOn instead
1435 * @param IDatabase $dbw
1436 * @param Revision $revision
1439 public function updateIfNewerOn( $dbw, $revision ) {
1440 $row = $dbw->selectRow(
1441 [ 'revision', 'page' ],
1442 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1444 'page_id' => $this->getId(),
1445 'page_latest=rev_id' ],
1449 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1452 $prev = $row->rev_id
;
1453 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1455 // No or missing previous revision; mark the page as new
1457 $lastRevIsRedirect = null;
1460 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1466 * Helper method for checking whether two revisions have differences that go
1467 * beyond the main slot.
1469 * MCR migration note: this method should go away!
1471 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1473 * @param Revision $a
1474 * @param Revision $b
1477 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1478 $aSlots = $a->getRevisionRecord()->getSlots();
1479 $bSlots = $b->getRevisionRecord()->getSlots();
1480 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1482 return ( $changedRoles !== [ 'main' ] && $changedRoles !== [] );
1486 * Get the content that needs to be saved in order to undo all revisions
1487 * between $undo and $undoafter. Revisions must belong to the same page,
1488 * must exist and must not be deleted
1490 * @param Revision $undo
1491 * @param Revision $undoafter Must be an earlier revision than $undo
1492 * @return Content|bool Content on success, false on failure
1494 * Before we had the Content object, this was done in getUndoText
1496 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1497 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1499 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1500 // Cannot yet undo edits that involve anything other the main slot.
1504 $handler = $undo->getContentHandler();
1505 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1509 * Returns true if this page's content model supports sections.
1513 * @todo The skin should check this and not offer section functionality if
1514 * sections are not supported.
1515 * @todo The EditPage should check this and not offer section functionality
1516 * if sections are not supported.
1518 public function supportsSections() {
1519 return $this->getContentHandler()->supportsSections();
1523 * @param string|int|null|bool $sectionId Section identifier as a number or string
1524 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1525 * or 'new' for a new section.
1526 * @param Content $sectionContent New content of the section.
1527 * @param string $sectionTitle New section's subject, only if $section is "new".
1528 * @param string $edittime Revision timestamp or null to use the current revision.
1530 * @throws MWException
1531 * @return Content|null New complete article content, or null if error.
1534 * @deprecated since 1.24, use replaceSectionAtRev instead
1536 public function replaceSectionContent(
1537 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1540 if ( $edittime && $sectionId !== 'new' ) {
1541 $lb = $this->getDBLoadBalancer();
1542 $dbr = $lb->getConnection( DB_REPLICA
);
1543 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1544 // Try the master if this thread may have just added it.
1545 // This could be abstracted into a Revision method, but we don't want
1546 // to encourage loading of revisions by timestamp.
1548 && $lb->getServerCount() > 1
1549 && $lb->hasOrMadeRecentMasterChanges()
1551 $dbw = $lb->getConnection( DB_MASTER
);
1552 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1555 $baseRevId = $rev->getId();
1559 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1563 * @param string|int|null|bool $sectionId Section identifier as a number or string
1564 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1565 * or 'new' for a new section.
1566 * @param Content $sectionContent New content of the section.
1567 * @param string $sectionTitle New section's subject, only if $section is "new".
1568 * @param int|null $baseRevId
1570 * @throws MWException
1571 * @return Content|null New complete article content, or null if error.
1575 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1576 $sectionTitle = '', $baseRevId = null
1578 if ( strval( $sectionId ) === '' ) {
1579 // Whole-page edit; let the whole text through
1580 $newContent = $sectionContent;
1582 if ( !$this->supportsSections() ) {
1583 throw new MWException( "sections not supported for content model " .
1584 $this->getContentHandler()->getModelID() );
1587 // T32711: always use current version when adding a new section
1588 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1589 $oldContent = $this->getContent();
1591 $rev = Revision
::newFromId( $baseRevId );
1593 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1594 $this->getId() . "; section: $sectionId)\n" );
1598 $oldContent = $rev->getContent();
1601 if ( !$oldContent ) {
1602 wfDebug( __METHOD__
. ": no page text\n" );
1606 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1613 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1615 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1616 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1619 * @return int Updated $flags
1621 public function checkFlags( $flags ) {
1622 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1623 if ( $this->exists() ) {
1624 $flags |
= EDIT_UPDATE
;
1634 * @return DerivedPageDataUpdater
1636 private function newDerivedDataUpdater() {
1637 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1639 $derivedDataUpdater = new DerivedPageDataUpdater(
1640 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1641 $this->getRevisionStore(),
1642 $this->getRevisionRenderer(),
1643 $this->getParserCache(),
1644 JobQueueGroup
::singleton(),
1645 MessageCache
::singleton(),
1646 MediaWikiServices
::getInstance()->getContentLanguage(),
1647 LoggerFactory
::getInstance( 'SaveParse' )
1650 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1651 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1653 return $derivedDataUpdater;
1657 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1658 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1659 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1660 * returned matches that caller's expectations, allowing an existing instance to be re-used
1661 * if the given parameters match that instance's internal state according to
1662 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1663 * match the existign one.
1665 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1666 * created, replacing any DerivedPageDataUpdater currently cached.
1668 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1672 * @param User|null $forUser The user that will be used for, or was used for, PST.
1673 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1674 * to perform updates, if the edit was already saved.
1675 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1676 * if the edit was not yet saved.
1677 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1678 * revision as the edit's parent revision. This ensures that the same
1679 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1681 * @return DerivedPageDataUpdater
1683 private function getDerivedDataUpdater(
1684 User
$forUser = null,
1685 RevisionRecord
$forRevision = null,
1686 RevisionSlotsUpdate
$forUpdate = null,
1689 if ( !$forRevision && !$forUpdate ) {
1690 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1691 // going to use it with.
1692 $this->derivedDataUpdater
= null;
1695 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1696 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1697 // to it did not yet initialize it, because we don't know what data it will be
1698 // initialized with.
1699 $this->derivedDataUpdater
= null;
1702 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1703 // However, there is no good way to construct a cache key. We'd need to check against all
1704 // cached instances.
1706 if ( $this->derivedDataUpdater
1707 && !$this->derivedDataUpdater
->isReusableFor(
1711 $forEdit ?
$this->getLatest() : null
1714 $this->derivedDataUpdater
= null;
1717 if ( !$this->derivedDataUpdater
) {
1718 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1721 return $this->derivedDataUpdater
;
1725 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1727 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1728 * and to protected such conflict resolution from concurrent edits using a check-and-set
1734 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1735 * that may already have been returned via getDerivedDataUpdater to be re-used.
1737 * @return PageUpdater
1739 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1740 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1742 $pageUpdater = new PageUpdater(
1744 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1745 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1746 $this->getDBLoadBalancer(),
1747 $this->getRevisionStore()
1750 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1751 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1752 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1754 return $pageUpdater;
1758 * Change an existing article or create a new article. Updates RC and all necessary caches,
1759 * optionally via the deferred update array.
1761 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1762 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1763 * apply the autopatrol right as appropriate.
1765 * @param Content $content New content
1766 * @param string|CommentStoreComment $summary Edit summary
1767 * @param int $flags Bitfield:
1769 * Article is known or assumed to be non-existent, create a new one
1771 * Article is known or assumed to be pre-existing, update it
1773 * Mark this edit minor, if the user is allowed to do so
1775 * Do not log the change in recentchanges
1777 * Mark the edit a "bot" edit regardless of user rights
1779 * Fill in blank summaries with generated text where possible
1781 * Signal that the page retrieve/save cycle happened entirely in this request.
1783 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1784 * article will be detected. If EDIT_UPDATE is specified and the article
1785 * doesn't exist, the function will return an edit-gone-missing error. If
1786 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1787 * error will be returned. These two conditions are also possible with
1788 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1790 * @param bool|int $originalRevId: The ID of an original revision that the edit
1791 * restores or repeats. The new revision is expected to have the exact same content as
1792 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1793 * which are created to record things like page moves.
1794 * @param User|null $user The user doing the edit
1795 * @param string|null $serialFormat IGNORED.
1796 * @param array|null $tags Change tags to apply to this edit
1797 * Callers are responsible for permission checks
1798 * (with ChangeTags::canAddTagsAccompanyingChange)
1799 * @param Int $undidRevId Id of revision that was undone or 0
1801 * @throws MWException
1802 * @return Status Possible errors:
1803 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1804 * set the fatal flag of $status.
1805 * edit-gone-missing: In update mode, but the article didn't exist.
1806 * edit-conflict: In update mode, the article changed unexpectedly.
1807 * edit-no-change: Warning that the text was the same as before.
1808 * edit-already-exists: In creation mode, but the article already exists.
1810 * Extensions may define additional errors.
1812 * $return->value will contain an associative array with members as follows:
1813 * new: Boolean indicating if the function attempted to create a new article.
1814 * revision: The revision object for the inserted revision, or null.
1817 * @throws MWException
1819 public function doEditContent(
1820 Content
$content, $summary, $flags = 0, $originalRevId = false,
1821 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1823 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1825 if ( !( $summary instanceof CommentStoreComment
) ) {
1826 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1833 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1834 // Checking the minoredit right should be done in the same place the 'bot' right is
1835 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1836 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1837 $flags = ( $flags & ~EDIT_MINOR
);
1840 $slotsUpdate = new RevisionSlotsUpdate();
1841 $slotsUpdate->modifyContent( 'main', $content );
1843 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1844 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1845 // used by this PageUpdater. However, there is no guarantee for this.
1846 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1847 $updater->setContent( 'main', $content );
1848 $updater->setOriginalRevisionId( $originalRevId );
1849 $updater->setUndidRevisionId( $undidRevId );
1851 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1853 // TODO: this logic should not be in the storage layer, it's here for compatibility
1854 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1855 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1856 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1857 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1860 $updater->addTags( $tags );
1862 $revRec = $updater->saveRevision(
1867 // $revRec will be null if the edit failed, or if no new revision was created because
1868 // the content did not change.
1870 // update cached fields
1871 // TODO: this is currently redundant to what is done in updateRevisionOn.
1872 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1873 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1874 $this->mLatest
= $revRec->getId();
1877 return $updater->getStatus();
1881 * Get parser options suitable for rendering the primary article wikitext
1883 * @see ParserOptions::newCanonical
1885 * @param IContextSource|User|string $context One of the following:
1886 * - IContextSource: Use the User and the Language of the provided
1888 * - User: Use the provided User object and $wgLang for the language,
1889 * so use an IContextSource object if possible.
1890 * - 'canonical': Canonical options (anonymous user with default
1891 * preferences and content language).
1892 * @return ParserOptions
1894 public function makeParserOptions( $context ) {
1895 $options = ParserOptions
::newCanonical( $context );
1897 if ( $this->getTitle()->isConversionTable() ) {
1898 // @todo ConversionTable should become a separate content model, so
1899 // we don't need special cases like this one.
1900 $options->disableContentConversion();
1907 * Prepare content which is about to be saved.
1909 * Prior to 1.30, this returned a stdClass.
1911 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1913 * @param Content $content
1914 * @param Revision|RevisionRecord|int|null $revision Revision object.
1915 * For backwards compatibility, a revision ID is also accepted,
1916 * but this is deprecated.
1917 * Used with vary-revision or vary-revision-id.
1918 * @param User|null $user
1919 * @param string|null $serialFormat IGNORED
1920 * @param bool $useCache Check shared prepared edit cache
1922 * @return PreparedEdit
1926 public function prepareContentForEdit(
1930 $serialFormat = null,
1939 if ( !is_object( $revision ) ) {
1941 // This code path is deprecated, and nothing is known to
1942 // use it, so performance here shouldn't be a worry.
1943 if ( $revid !== null ) {
1944 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1945 $store = $this->getRevisionStore();
1946 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1950 } elseif ( $revision instanceof Revision
) {
1951 $revision = $revision->getRevisionRecord();
1954 $slots = RevisionSlotsUpdate
::newFromContent( [ 'main' => $content ] );
1955 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1957 if ( !$updater->isUpdatePrepared() ) {
1958 $updater->prepareContent( $user, $slots, $useCache );
1961 $updater->prepareUpdate( $revision );
1965 return $updater->getPreparedEdit();
1969 * Do standard deferred updates after page edit.
1970 * Update links tables, site stats, search index and message cache.
1971 * Purges pages that include this page if the text was changed here.
1972 * Every 100th edit, prune the recent changes table.
1974 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
1976 * @param Revision $revision
1977 * @param User $user User object that did the revision
1978 * @param array $options Array of options, following indexes are used:
1979 * - changed: bool, whether the revision changed the content (default true)
1980 * - created: bool, whether the revision created the page (default false)
1981 * - moved: bool, whether the page was moved (default false)
1982 * - restored: bool, whether the page was undeleted (default false)
1983 * - oldrevision: Revision object for the pre-update revision (default null)
1984 * - oldcountable: bool, null, or string 'no-change' (default null):
1985 * - bool: whether the page was counted as an article before that
1986 * revision, only used in changed is true and created is false
1987 * - null: if created is false, don't update the article count; if created
1988 * is true, do update the article count
1989 * - 'no-change': don't update the article count, ever
1991 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
1992 $revision = $revision->getRevisionRecord();
1994 $updater = $this->getDerivedDataUpdater( $user, $revision );
1996 $updater->prepareUpdate( $revision, $options );
1998 $updater->doUpdates();
2002 * Update the article's restriction field, and leave a log entry.
2003 * This works for protection both existing and non-existing pages.
2005 * @param array $limit Set of restriction keys
2006 * @param array $expiry Per restriction type expiration
2007 * @param int &$cascade Set to false if cascading protection isn't allowed.
2008 * @param string $reason
2009 * @param User $user The user updating the restrictions
2010 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2011 * ($user should be able to add the specified tags before this is called)
2012 * @return Status Status object; if action is taken, $status->value is the log_id of the
2013 * protection log entry.
2015 public function doUpdateRestrictions( array $limit, array $expiry,
2016 &$cascade, $reason, User
$user, $tags = null
2018 global $wgCascadingRestrictionLevels;
2020 if ( wfReadOnly() ) {
2021 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2024 $this->loadPageData( 'fromdbmaster' );
2025 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2026 $id = $this->getId();
2032 // Take this opportunity to purge out expired restrictions
2033 Title
::purgeExpiredRestrictions();
2035 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2036 // we expect a single selection, but the schema allows otherwise.
2037 $isProtected = false;
2041 $dbw = wfGetDB( DB_MASTER
);
2043 foreach ( $restrictionTypes as $action ) {
2044 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2045 $expiry[$action] = 'infinity';
2047 if ( !isset( $limit[$action] ) ) {
2048 $limit[$action] = '';
2049 } elseif ( $limit[$action] != '' ) {
2053 // Get current restrictions on $action
2054 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2055 if ( $current != '' ) {
2056 $isProtected = true;
2059 if ( $limit[$action] != $current ) {
2061 } elseif ( $limit[$action] != '' ) {
2062 // Only check expiry change if the action is actually being
2063 // protected, since expiry does nothing on an not-protected
2065 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2071 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2075 // If nothing has changed, do nothing
2077 return Status
::newGood();
2080 if ( !$protect ) { // No protection at all means unprotection
2081 $revCommentMsg = 'unprotectedarticle-comment';
2082 $logAction = 'unprotect';
2083 } elseif ( $isProtected ) {
2084 $revCommentMsg = 'modifiedarticleprotection-comment';
2085 $logAction = 'modify';
2087 $revCommentMsg = 'protectedarticle-comment';
2088 $logAction = 'protect';
2091 $logRelationsValues = [];
2092 $logRelationsField = null;
2093 $logParamsDetails = [];
2095 // Null revision (used for change tag insertion)
2096 $nullRevision = null;
2098 if ( $id ) { // Protection of existing page
2099 // Avoid PHP 7.1 warning of passing $this by reference
2102 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2103 return Status
::newGood();
2106 // Only certain restrictions can cascade...
2107 $editrestriction = isset( $limit['edit'] )
2108 ?
[ $limit['edit'] ]
2109 : $this->mTitle
->getRestrictions( 'edit' );
2110 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2111 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2113 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2114 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2117 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2118 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2119 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2121 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2122 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2125 // The schema allows multiple restrictions
2126 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2130 // insert null revision to identify the page protection change as edit summary
2131 $latest = $this->getLatest();
2132 $nullRevision = $this->insertProtectNullRevision(
2141 if ( $nullRevision === null ) {
2142 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2145 $logRelationsField = 'pr_id';
2147 // Update restrictions table
2148 foreach ( $limit as $action => $restrictions ) {
2150 'page_restrictions',
2153 'pr_type' => $action
2157 if ( $restrictions != '' ) {
2158 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2160 'page_restrictions',
2163 'pr_type' => $action,
2164 'pr_level' => $restrictions,
2165 'pr_cascade' => $cascadeValue,
2166 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2170 $logRelationsValues[] = $dbw->insertId();
2171 $logParamsDetails[] = [
2173 'level' => $restrictions,
2174 'expiry' => $expiry[$action],
2175 'cascade' => (bool)$cascadeValue,
2180 // Clear out legacy restriction fields
2183 [ 'page_restrictions' => '' ],
2184 [ 'page_id' => $id ],
2188 // Avoid PHP 7.1 warning of passing $this by reference
2191 Hooks
::run( 'NewRevisionFromEditComplete',
2192 [ $this, $nullRevision, $latest, $user ] );
2193 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2194 } else { // Protection of non-existing page (also known as "title protection")
2195 // Cascade protection is meaningless in this case
2198 if ( $limit['create'] != '' ) {
2199 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2200 $dbw->replace( 'protected_titles',
2201 [ [ 'pt_namespace', 'pt_title' ] ],
2203 'pt_namespace' => $this->mTitle
->getNamespace(),
2204 'pt_title' => $this->mTitle
->getDBkey(),
2205 'pt_create_perm' => $limit['create'],
2206 'pt_timestamp' => $dbw->timestamp(),
2207 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2208 'pt_user' => $user->getId(),
2209 ] +
$commentFields, __METHOD__
2211 $logParamsDetails[] = [
2213 'level' => $limit['create'],
2214 'expiry' => $expiry['create'],
2217 $dbw->delete( 'protected_titles',
2219 'pt_namespace' => $this->mTitle
->getNamespace(),
2220 'pt_title' => $this->mTitle
->getDBkey()
2226 $this->mTitle
->flushRestrictions();
2227 InfoAction
::invalidateCache( $this->mTitle
);
2229 if ( $logAction == 'unprotect' ) {
2232 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2234 '4::description' => $protectDescriptionLog, // parameter for IRC
2235 '5:bool:cascade' => $cascade,
2236 'details' => $logParamsDetails, // parameter for localize and api
2240 // Update the protection log
2241 $logEntry = new ManualLogEntry( 'protect', $logAction );
2242 $logEntry->setTarget( $this->mTitle
);
2243 $logEntry->setComment( $reason );
2244 $logEntry->setPerformer( $user );
2245 $logEntry->setParameters( $params );
2246 if ( !is_null( $nullRevision ) ) {
2247 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2249 $logEntry->setTags( $tags );
2250 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2251 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2253 $logId = $logEntry->insert();
2254 $logEntry->publish( $logId );
2256 return Status
::newGood( $logId );
2260 * Insert a new null revision for this page.
2262 * @param string $revCommentMsg Comment message key for the revision
2263 * @param array $limit Set of restriction keys
2264 * @param array $expiry Per restriction type expiration
2265 * @param int $cascade Set to false if cascading protection isn't allowed.
2266 * @param string $reason
2267 * @param User|null $user
2268 * @return Revision|null Null on error
2270 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2271 array $expiry, $cascade, $reason, $user = null
2273 $dbw = wfGetDB( DB_MASTER
);
2275 // Prepare a null revision to be added to the history
2276 $editComment = wfMessage(
2278 $this->mTitle
->getPrefixedText(),
2279 $user ?
$user->getName() : ''
2280 )->inContentLanguage()->text();
2282 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2284 $protectDescription = $this->protectDescription( $limit, $expiry );
2285 if ( $protectDescription ) {
2286 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2287 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2288 ->inContentLanguage()->text();
2291 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2292 $editComment .= wfMessage( 'brackets' )->params(
2293 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2294 )->inContentLanguage()->text();
2297 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2299 $nullRev->insertOn( $dbw );
2301 // Update page record and touch page
2302 $oldLatest = $nullRev->getParentId();
2303 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2310 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2313 protected function formatExpiry( $expiry ) {
2314 if ( $expiry != 'infinity' ) {
2315 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2318 $contLang->timeanddate( $expiry, false, false ),
2319 $contLang->date( $expiry, false, false ),
2320 $contLang->time( $expiry, false, false )
2321 )->inContentLanguage()->text();
2323 return wfMessage( 'protect-expiry-indefinite' )
2324 ->inContentLanguage()->text();
2329 * Builds the description to serve as comment for the edit.
2331 * @param array $limit Set of restriction keys
2332 * @param array $expiry Per restriction type expiration
2335 public function protectDescription( array $limit, array $expiry ) {
2336 $protectDescription = '';
2338 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2339 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2340 # All possible message keys are listed here for easier grepping:
2341 # * restriction-create
2342 # * restriction-edit
2343 # * restriction-move
2344 # * restriction-upload
2345 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2346 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2347 # with '' filtered out. All possible message keys are listed below:
2348 # * protect-level-autoconfirmed
2349 # * protect-level-sysop
2350 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2351 ->inContentLanguage()->text();
2353 $expiryText = $this->formatExpiry( $expiry[$action] );
2355 if ( $protectDescription !== '' ) {
2356 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2358 $protectDescription .= wfMessage( 'protect-summary-desc' )
2359 ->params( $actionText, $restrictionsText, $expiryText )
2360 ->inContentLanguage()->text();
2363 return $protectDescription;
2367 * Builds the description to serve as comment for the log entry.
2369 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2370 * protect description text. Keep them in old format to avoid breaking compatibility.
2371 * TODO: Fix protection log to store structured description and format it on-the-fly.
2373 * @param array $limit Set of restriction keys
2374 * @param array $expiry Per restriction type expiration
2377 public function protectDescriptionLog( array $limit, array $expiry ) {
2378 $protectDescriptionLog = '';
2380 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2381 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2382 $expiryText = $this->formatExpiry( $expiry[$action] );
2383 $protectDescriptionLog .=
2385 "[$action=$restrictions] ($expiryText)";
2388 return trim( $protectDescriptionLog );
2392 * Take an array of page restrictions and flatten it to a string
2393 * suitable for insertion into the page_restrictions field.
2395 * @param string[] $limit
2397 * @throws MWException
2400 protected static function flattenRestrictions( $limit ) {
2401 if ( !is_array( $limit ) ) {
2402 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2408 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2409 $bits[] = "$action=$restrictions";
2412 return implode( ':', $bits );
2416 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2417 * backwards compatibility, if you care about error reporting you should use
2418 * doDeleteArticleReal() instead.
2420 * Deletes the article with database consistency, writes logs, purges caches
2422 * @param string $reason Delete reason for deletion log
2423 * @param bool $suppress Suppress all revisions and log the deletion in
2424 * the suppression log instead of the deletion log
2425 * @param int|null $u1 Unused
2426 * @param bool|null $u2 Unused
2427 * @param array|string &$error Array of errors to append to
2428 * @param User|null $user The deleting user
2429 * @return bool True if successful
2431 public function doDeleteArticle(
2432 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2434 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2435 return $status->isGood();
2439 * Back-end article deletion
2440 * Deletes the article with database consistency, writes logs, purges caches
2444 * @param string $reason Delete reason for deletion log
2445 * @param bool $suppress Suppress all revisions and log the deletion in
2446 * the suppression log instead of the deletion log
2447 * @param int|null $u1 Unused
2448 * @param bool|null $u2 Unused
2449 * @param array|string &$error Array of errors to append to
2450 * @param User|null $deleter The deleting user
2451 * @param array $tags Tags to apply to the deletion action
2452 * @param string $logsubtype
2453 * @return Status Status object; if successful, $status->value is the log_id of the
2454 * deletion log entry. If the page couldn't be deleted because it wasn't
2455 * found, $status is a non-fatal 'cannotdelete' error
2457 public function doDeleteArticleReal(
2458 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2459 $tags = [], $logsubtype = 'delete'
2461 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage,
2462 $wgActorTableSchemaMigrationStage, $wgMultiContentRevisionSchemaMigrationStage;
2464 wfDebug( __METHOD__
. "\n" );
2466 $status = Status
::newGood();
2468 if ( $this->mTitle
->getDBkey() === '' ) {
2469 $status->error( 'cannotdelete',
2470 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2474 // Avoid PHP 7.1 warning of passing $this by reference
2477 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2478 if ( !Hooks
::run( 'ArticleDelete',
2479 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2481 if ( $status->isOK() ) {
2482 // Hook aborted but didn't set a fatal status
2483 $status->fatal( 'delete-hook-aborted' );
2488 $dbw = wfGetDB( DB_MASTER
);
2489 $dbw->startAtomic( __METHOD__
);
2491 $this->loadPageData( self
::READ_LATEST
);
2492 $id = $this->getId();
2493 // T98706: lock the page from various other updates but avoid using
2494 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2495 // the revisions queries (which also JOIN on user). Only lock the page
2496 // row and CAS check on page_latest to see if the trx snapshot matches.
2497 $lockedLatest = $this->lockAndGetLatest();
2498 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2499 $dbw->endAtomic( __METHOD__
);
2500 // Page not there or trx snapshot is stale
2501 $status->error( 'cannotdelete',
2502 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2506 // Given the lock above, we can be confident in the title and page ID values
2507 $namespace = $this->getTitle()->getNamespace();
2508 $dbKey = $this->getTitle()->getDBkey();
2510 // At this point we are now comitted to returning an OK
2511 // status unless some DB query error or other exception comes up.
2512 // This way callers don't have to call rollback() if $status is bad
2513 // unless they actually try to catch exceptions (which is rare).
2515 // we need to remember the old content so we can use it to generate all deletion updates.
2516 $revision = $this->getRevision();
2518 $content = $this->getContent( Revision
::RAW
);
2519 } catch ( Exception
$ex ) {
2520 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2521 . $ex->getMessage() );
2526 $commentStore = CommentStore
::getStore();
2527 $actorMigration = ActorMigration
::newMigration();
2529 $revQuery = Revision
::getQueryInfo();
2532 // Bitfields to further suppress the content
2534 $bitfield = Revision
::SUPPRESSED_ALL
;
2535 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2538 // For now, shunt the revision data into the archive table.
2539 // Text is *not* removed from the text table; bulk storage
2540 // is left intact to avoid breaking block-compression or
2541 // immutable storage schemes.
2542 // In the future, we may keep revisions and mark them with
2543 // the rev_deleted field, which is reserved for this purpose.
2545 // Lock rows in `revision` and its temp tables, but not any others.
2546 // Note array_intersect() preserves keys from the first arg, and we're
2547 // assuming $revQuery has `revision` primary and isn't using subtables
2548 // for anything we care about.
2549 $dbw->lockForUpdate(
2551 $revQuery['tables'],
2552 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2554 [ 'rev_page' => $id ],
2560 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2561 // so we can copy it to the archive table.
2562 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2563 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2564 $revQuery['fields'][] = 'rev_text_id';
2566 if ( $wgContentHandlerUseDB ) {
2567 $revQuery['fields'][] = 'rev_content_model';
2568 $revQuery['fields'][] = 'rev_content_format';
2572 // Get all of the page revisions
2573 $res = $dbw->select(
2574 $revQuery['tables'],
2575 $revQuery['fields'],
2576 [ 'rev_page' => $id ],
2582 // Build their equivalent archive rows
2586 /** @var int[] Revision IDs of edits that were made by IPs */
2589 foreach ( $res as $row ) {
2590 $comment = $commentStore->getComment( 'rev_comment', $row );
2591 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2593 'ar_namespace' => $namespace,
2594 'ar_title' => $dbKey,
2595 'ar_timestamp' => $row->rev_timestamp
,
2596 'ar_minor_edit' => $row->rev_minor_edit
,
2597 'ar_rev_id' => $row->rev_id
,
2598 'ar_parent_id' => $row->rev_parent_id
,
2600 * ar_text_id should probably not be written to when the multi content schema has
2601 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2602 * default for the field in WMF production currently so we must keep writing
2603 * writing until a default of 0 is set.
2604 * Task: https://phabricator.wikimedia.org/T190148
2605 * Copying the value from the revision table should not lead to any issues for now.
2607 'ar_len' => $row->rev_len
,
2608 'ar_page_id' => $id,
2609 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2610 'ar_sha1' => $row->rev_sha1
,
2611 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2612 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2614 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2615 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2617 if ( $wgContentHandlerUseDB ) {
2618 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2619 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2623 $rowsInsert[] = $rowInsert;
2624 $revids[] = $row->rev_id
;
2626 // Keep track of IP edits, so that the corresponding rows can
2627 // be deleted in the ip_changes table.
2628 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2629 $ipRevIds[] = $row->rev_id
;
2632 // Copy them into the archive table
2633 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2634 // Save this so we can pass it to the ArticleDeleteComplete hook.
2635 $archivedRevisionCount = $dbw->affectedRows();
2637 // Clone the title and wikiPage, so we have the information we need when
2638 // we log and run the ArticleDeleteComplete hook.
2639 $logTitle = clone $this->mTitle
;
2640 $wikiPageBeforeDelete = clone $this;
2642 // Now that it's safely backed up, delete it
2643 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2644 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2645 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2646 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2648 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
2649 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2652 // Also delete records from ip_changes as applicable.
2653 if ( count( $ipRevIds ) > 0 ) {
2654 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2657 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2658 $logtype = $suppress ?
'suppress' : 'delete';
2660 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2661 $logEntry->setPerformer( $deleter );
2662 $logEntry->setTarget( $logTitle );
2663 $logEntry->setComment( $reason );
2664 $logEntry->setTags( $tags );
2665 $logid = $logEntry->insert();
2667 $dbw->onTransactionPreCommitOrIdle(
2668 function () use ( $logEntry, $logid ) {
2669 // T58776: avoid deadlocks (especially from FileDeleteForm)
2670 $logEntry->publish( $logid );
2675 $dbw->endAtomic( __METHOD__
);
2677 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2679 Hooks
::run( 'ArticleDeleteComplete', [
2680 &$wikiPageBeforeDelete,
2686 $archivedRevisionCount
2688 $status->value
= $logid;
2690 // Show log excerpt on 404 pages rather than just a link
2691 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2692 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2693 $cache->set( $key, 1, $cache::TTL_DAY
);
2699 * Lock the page row for this title+id and return page_latest (or 0)
2701 * @return int Returns 0 if no row was found with this title+id
2704 public function lockAndGetLatest() {
2705 return (int)wfGetDB( DB_MASTER
)->selectField(
2709 'page_id' => $this->getId(),
2710 // Typically page_id is enough, but some code might try to do
2711 // updates assuming the title is the same, so verify that
2712 'page_namespace' => $this->getTitle()->getNamespace(),
2713 'page_title' => $this->getTitle()->getDBkey()
2721 * Do some database updates after deletion
2723 * @param int $id The page_id value of the page being deleted
2724 * @param Content|null $content Optional page content to be used when determining
2725 * the required updates. This may be needed because $this->getContent()
2726 * may already return null when the page proper was deleted.
2727 * @param Revision|null $revision The latest page revision
2728 * @param User|null $user The user that caused the deletion
2730 public function doDeleteUpdates(
2731 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2734 $countable = $this->isCountable();
2735 } catch ( Exception
$ex ) {
2736 // fallback for deleting broken pages for which we cannot load the content for
2737 // some reason. Note that doDeleteArticleReal() already logged this problem.
2741 // Update site status
2742 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
2743 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
2746 // Delete pagelinks, update secondary indexes, etc
2747 $updates = $this->getDeletionUpdates( $content );
2748 foreach ( $updates as $update ) {
2749 DeferredUpdates
::addUpdate( $update );
2752 $causeAgent = $user ?
$user->getName() : 'unknown';
2753 // Reparse any pages transcluding this page
2754 LinksUpdate
::queueRecursiveJobsForTable(
2755 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
2756 // Reparse any pages including this image
2757 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2758 LinksUpdate
::queueRecursiveJobsForTable(
2759 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
2763 self
::onArticleDelete( $this->mTitle
);
2764 ResourceLoaderWikiModule
::invalidateModuleCache(
2765 $this->mTitle
, $revision, null, wfWikiID()
2768 // Reset this object and the Title object
2769 $this->loadFromRow( false, self
::READ_LATEST
);
2772 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2776 * Roll back the most recent consecutive set of edits to a page
2777 * from the same user; fails if there are no eligible edits to
2778 * roll back to, e.g. user is the sole contributor. This function
2779 * performs permissions checks on $user, then calls commitRollback()
2780 * to do the dirty work
2782 * @todo Separate the business/permission stuff out from backend code
2783 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2785 * @param string $fromP Name of the user whose edits to rollback.
2786 * @param string $summary Custom summary. Set to default summary if empty.
2787 * @param string $token Rollback token.
2788 * @param bool $bot If true, mark all reverted edits as bot.
2790 * @param array &$resultDetails Array contains result-specific array of additional values
2791 * 'alreadyrolled' : 'current' (rev)
2792 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2794 * @param User $user The user performing the rollback
2795 * @param array|null $tags Change tags to apply to the rollback
2796 * Callers are responsible for permission checks
2797 * (with ChangeTags::canAddTagsAccompanyingChange)
2799 * @return array Array of errors, each error formatted as
2800 * array(messagekey, param1, param2, ...).
2801 * On success, the array is empty. This array can also be passed to
2802 * OutputPage::showPermissionsErrorPage().
2804 public function doRollback(
2805 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
2807 $resultDetails = null;
2809 // Check permissions
2810 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2811 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2812 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2814 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
2815 $errors[] = [ 'sessionfailure' ];
2818 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2819 $errors[] = [ 'actionthrottledtext' ];
2822 // If there were errors, bail out now
2823 if ( !empty( $errors ) ) {
2827 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
2831 * Backend implementation of doRollback(), please refer there for parameter
2832 * and return value documentation
2834 * NOTE: This function does NOT check ANY permissions, it just commits the
2835 * rollback to the DB. Therefore, you should only call this function direct-
2836 * ly if you want to use custom permissions checks. If you don't, use
2837 * doRollback() instead.
2838 * @param string $fromP Name of the user whose edits to rollback.
2839 * @param string $summary Custom summary. Set to default summary if empty.
2840 * @param bool $bot If true, mark all reverted edits as bot.
2842 * @param array &$resultDetails Contains result-specific array of additional values
2843 * @param User $guser The user performing the rollback
2844 * @param array|null $tags Change tags to apply to the rollback
2845 * Callers are responsible for permission checks
2846 * (with ChangeTags::canAddTagsAccompanyingChange)
2848 * @return array An array of error messages, as returned by Status::getErrorsArray()
2850 public function commitRollback( $fromP, $summary, $bot,
2851 &$resultDetails, User
$guser, $tags = null
2853 global $wgUseRCPatrol;
2855 $dbw = wfGetDB( DB_MASTER
);
2857 if ( wfReadOnly() ) {
2858 return [ [ 'readonlytext' ] ];
2861 // Begin revision creation cycle by creating a PageUpdater.
2862 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
2863 $updater = $this->newPageUpdater( $guser );
2864 $current = $updater->grabParentRevision();
2866 if ( is_null( $current ) ) {
2867 // Something wrong... no page?
2868 return [ [ 'notanarticle' ] ];
2871 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
2872 $legacyCurrent = new Revision( $current );
2873 $from = str_replace( '_', ' ', $fromP );
2875 // User name given should match up with the top revision.
2876 // If the revision's user is not visible, then $from should be empty.
2877 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
2878 $resultDetails = [ 'current' => $legacyCurrent ];
2879 return [ [ 'alreadyrolled',
2880 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2881 htmlspecialchars( $fromP ),
2882 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
2886 // Get the last edit not by this person...
2887 // Note: these may not be public values
2888 $actorWhere = ActorMigration
::newMigration()->getWhere(
2891 $current->getUser( RevisionRecord
::RAW
)
2894 $s = $dbw->selectRow(
2895 [ 'revision' ] +
$actorWhere['tables'],
2896 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
2898 'rev_page' => $current->getPageId(),
2899 'NOT(' . $actorWhere['conds'] . ')',
2903 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
2904 'ORDER BY' => 'rev_timestamp DESC'
2906 $actorWhere['joins']
2908 if ( $s === false ) {
2909 // No one else ever edited this page
2910 return [ [ 'cantrollback' ] ];
2911 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
2912 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
2914 // Only admins can see this text
2915 return [ [ 'notvisiblerev' ] ];
2918 // Generate the edit summary if necessary
2919 $target = $this->getRevisionStore()->getRevisionById(
2921 RevisionStore
::READ_LATEST
2923 if ( empty( $summary ) ) {
2924 if ( !$currentEditorForPublic ) { // no public user name
2925 $summary = wfMessage( 'revertpage-nouser' );
2927 $summary = wfMessage( 'revertpage' );
2930 $legacyTarget = new Revision( $target );
2931 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
2933 // Allow the custom summary to use the same args as the default message
2934 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2936 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
2937 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
2939 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2941 $contLang->timeanddate( $current->getTimestamp() )
2943 if ( $summary instanceof Message
) {
2944 $summary = $summary->params( $args )->inContentLanguage()->text();
2946 $summary = wfMsgReplaceArgs( $summary, $args );
2949 // Trim spaces on user supplied text
2950 $summary = trim( $summary );
2953 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
2955 if ( $guser->isAllowed( 'minoredit' ) ) {
2956 $flags |
= EDIT_MINOR
;
2959 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2960 $flags |
= EDIT_FORCE_BOT
;
2963 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
2964 $currentContent = $current->getContent( 'main' );
2965 $targetContent = $target->getContent( 'main' );
2966 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
2968 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
2969 $tags[] = 'mw-rollback';
2972 // Build rollback revision:
2973 // Restore old content
2974 // TODO: MCR: test this once we can store multiple slots
2975 foreach ( $target->getSlots()->getSlots() as $slot ) {
2976 $updater->inheritSlot( $slot );
2979 // Remove extra slots
2980 // TODO: MCR: test this once we can store multiple slots
2981 foreach ( $current->getSlotRoles() as $role ) {
2982 if ( !$target->hasSlot( $role ) ) {
2983 $updater->removeSlot( $role );
2987 $updater->setOriginalRevisionId( $target->getId() );
2988 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
2989 $updater->addTags( $tags );
2991 // TODO: this logic should not be in the storage layer, it's here for compatibility
2992 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
2993 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
2994 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
2995 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
2998 // Actually store the rollback
2999 $rev = $updater->saveRevision(
3000 CommentStoreComment
::newUnsavedComment( $summary ),
3004 // Set patrolling and bot flag on the edits, which gets rollbacked.
3005 // This is done even on edit failure to have patrolling in that case (T64157).
3007 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3008 // Mark all reverted edits as bot
3012 if ( $wgUseRCPatrol ) {
3013 // Mark all reverted edits as patrolled
3014 $set['rc_patrolled'] = RecentChange
::PRC_PATROLLED
;
3017 if ( count( $set ) ) {
3018 $actorWhere = ActorMigration
::newMigration()->getWhere(
3021 $current->getUser( RevisionRecord
::RAW
),
3024 $dbw->update( 'recentchanges', $set,
3026 'rc_cur_id' => $current->getPageId(),
3027 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3028 $actorWhere['conds'], // No tables/joins are needed for rc_user
3034 if ( !$updater->wasSuccessful() ) {
3035 return $updater->getStatus()->getErrorsArray();
3038 // Report if the edit was not created because it did not change the content.
3039 if ( $updater->isUnchanged() ) {
3040 $resultDetails = [ 'current' => $legacyCurrent ];
3041 return [ [ 'alreadyrolled',
3042 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3043 htmlspecialchars( $fromP ),
3044 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3048 if ( $changingContentModel ) {
3049 // If the content model changed during the rollback,
3050 // make sure it gets logged to Special:Log/contentmodel
3051 $log = new ManualLogEntry( 'contentmodel', 'change' );
3052 $log->setPerformer( $guser );
3053 $log->setTarget( $this->mTitle
);
3054 $log->setComment( $summary );
3055 $log->setParameters( [
3056 '4::oldmodel' => $currentContent->getModel(),
3057 '5::newmodel' => $targetContent->getModel(),
3060 $logId = $log->insert( $dbw );
3061 $log->publish( $logId );
3064 $revId = $rev->getId();
3066 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3069 'summary' => $summary,
3070 'current' => $legacyCurrent,
3071 'target' => $legacyTarget,
3076 // TODO: make this return a Status object and wrap $resultDetails in that.
3081 * The onArticle*() functions are supposed to be a kind of hooks
3082 * which should be called whenever any of the specified actions
3085 * This is a good place to put code to clear caches, for instance.
3087 * This is called on page move and undelete, as well as edit
3089 * @param Title $title
3091 public static function onArticleCreate( Title
$title ) {
3092 // TODO: move this into a PageEventEmitter service
3094 // Update existence markers on article/talk tabs...
3095 $other = $title->getOtherPage();
3097 $other->purgeSquid();
3099 $title->touchLinks();
3100 $title->purgeSquid();
3101 $title->deleteTitleProtection();
3103 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3105 // Invalidate caches of articles which include this page
3106 DeferredUpdates
::addUpdate(
3107 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3110 if ( $title->getNamespace() == NS_CATEGORY
) {
3111 // Load the Category object, which will schedule a job to create
3112 // the category table row if necessary. Checking a replica DB is ok
3113 // here, in the worst case it'll run an unnecessary recount job on
3114 // a category that probably doesn't have many members.
3115 Category
::newFromTitle( $title )->getID();
3120 * Clears caches when article is deleted
3122 * @param Title $title
3124 public static function onArticleDelete( Title
$title ) {
3125 // TODO: move this into a PageEventEmitter service
3127 // Update existence markers on article/talk tabs...
3128 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3129 BacklinkCache
::get( $title )->clear();
3130 $other = $title->getOtherPage();
3132 $other->purgeSquid();
3134 $title->touchLinks();
3135 $title->purgeSquid();
3137 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3140 HTMLFileCache
::clearFileCache( $title );
3141 InfoAction
::invalidateCache( $title );
3144 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3145 MessageCache
::singleton()->updateMessageOverride( $title, null );
3149 if ( $title->getNamespace() == NS_FILE
) {
3150 DeferredUpdates
::addUpdate(
3151 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3156 if ( $title->getNamespace() == NS_USER_TALK
) {
3157 $user = User
::newFromName( $title->getText(), false );
3159 $user->setNewtalk( false );
3164 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3166 // Purge cross-wiki cache entities referencing this page
3167 self
::purgeInterwikiCheckKey( $title );
3171 * Purge caches on page update etc
3173 * @param Title $title
3174 * @param Revision|null $revision Revision that was just saved, may be null
3175 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3176 * If not given, all slots are assumed to have changed.
3178 public static function onArticleEdit(
3180 Revision
$revision = null,
3181 $slotsChanged = null
3183 // TODO: move this into a PageEventEmitter service
3185 if ( $slotsChanged === null ||
in_array( 'main', $slotsChanged ) ) {
3186 // Invalidate caches of articles which include this page.
3187 // Only for the main slot, because only the main slot is transcluded.
3188 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3189 DeferredUpdates
::addUpdate(
3190 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3194 // Invalidate the caches of all pages which redirect here
3195 DeferredUpdates
::addUpdate(
3196 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3199 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3201 // Purge CDN for this page only
3202 $title->purgeSquid();
3203 // Clear file cache for this page only
3204 HTMLFileCache
::clearFileCache( $title );
3206 // Purge ?action=info cache
3207 $revid = $revision ?
$revision->getId() : null;
3208 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3209 InfoAction
::invalidateCache( $title, $revid );
3212 // Purge cross-wiki cache entities referencing this page
3213 self
::purgeInterwikiCheckKey( $title );
3219 * Purge the check key for cross-wiki cache entries referencing this page
3221 * @param Title $title
3223 private static function purgeInterwikiCheckKey( Title
$title ) {
3224 global $wgEnableScaryTranscluding;
3226 if ( !$wgEnableScaryTranscluding ) {
3227 return; // @todo: perhaps this wiki is only used as a *source* for content?
3230 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3231 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3232 $cache->resetCheckKey(
3233 // Do not include the namespace since there can be multiple aliases to it
3234 // due to different namespace text definitions on different wikis. This only
3235 // means that some cache invalidations happen that are not strictly needed.
3236 $cache->makeGlobalKey( 'interwiki-page', wfWikiID(), $title->getDBkey() )
3242 * Returns a list of categories this page is a member of.
3243 * Results will include hidden categories
3245 * @return TitleArray
3247 public function getCategories() {
3248 $id = $this->getId();
3250 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3253 $dbr = wfGetDB( DB_REPLICA
);
3254 $res = $dbr->select( 'categorylinks',
3255 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3256 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3257 // as not being aliases, and NS_CATEGORY is numeric
3258 [ 'cl_from' => $id ],
3261 return TitleArray
::newFromResult( $res );
3265 * Returns a list of hidden categories this page is a member of.
3266 * Uses the page_props and categorylinks tables.
3268 * @return array Array of Title objects
3270 public function getHiddenCategories() {
3272 $id = $this->getId();
3278 $dbr = wfGetDB( DB_REPLICA
);
3279 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3281 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3282 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3285 if ( $res !== false ) {
3286 foreach ( $res as $row ) {
3287 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3295 * Auto-generates a deletion reason
3297 * @param bool &$hasHistory Whether the page has a history
3298 * @return string|bool String containing deletion reason or empty string, or boolean false
3299 * if no revision occurred
3301 public function getAutoDeleteReason( &$hasHistory ) {
3302 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3306 * Update all the appropriate counts in the category table, given that
3307 * we've added the categories $added and deleted the categories $deleted.
3309 * This should only be called from deferred updates or jobs to avoid contention.
3311 * @param array $added The names of categories that were added
3312 * @param array $deleted The names of categories that were deleted
3313 * @param int $id Page ID (this should be the original deleted page ID)
3315 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3316 $id = $id ?
: $this->getId();
3317 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3319 $addFields = [ 'cat_pages = cat_pages + 1' ];
3320 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3321 if ( $type !== 'page' ) {
3322 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3323 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3326 $dbw = wfGetDB( DB_MASTER
);
3328 if ( count( $added ) ) {
3329 $existingAdded = $dbw->selectFieldValues(
3332 [ 'cat_title' => $added ],
3336 // For category rows that already exist, do a plain
3337 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3338 // to avoid creating gaps in the cat_id sequence.
3339 if ( count( $existingAdded ) ) {
3343 [ 'cat_title' => $existingAdded ],
3348 $missingAdded = array_diff( $added, $existingAdded );
3349 if ( count( $missingAdded ) ) {
3351 foreach ( $missingAdded as $cat ) {
3353 'cat_title' => $cat,
3355 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3356 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3369 if ( count( $deleted ) ) {
3373 [ 'cat_title' => $deleted ],
3378 foreach ( $added as $catName ) {
3379 $cat = Category
::newFromName( $catName );
3380 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3383 foreach ( $deleted as $catName ) {
3384 $cat = Category
::newFromName( $catName );
3385 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3386 // Refresh counts on categories that should be empty now (after commit, T166757)
3387 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3388 $cat->refreshCountsIfEmpty();
3394 * Opportunistically enqueue link update jobs given fresh parser output if useful
3396 * @param ParserOutput $parserOutput Current version page output
3399 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3400 if ( wfReadOnly() ) {
3404 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3405 [ $this, $this->mTitle
, $parserOutput ]
3410 $config = RequestContext
::getMain()->getConfig();
3413 'isOpportunistic' => true,
3414 'rootJobTimestamp' => $parserOutput->getCacheTime()
3417 if ( $this->mTitle
->areRestrictionsCascading() ) {
3418 // If the page is cascade protecting, the links should really be up-to-date
3419 JobQueueGroup
::singleton()->lazyPush(
3420 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3422 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3423 // Assume the output contains "dynamic" time/random based magic words.
3424 // Only update pages that expired due to dynamic content and NOT due to edits
3425 // to referenced templates/files. When the cache expires due to dynamic content,
3426 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3427 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3428 // template/file edit already triggered recursive RefreshLinksJob jobs.
3429 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3430 // If a page is uncacheable, do not keep spamming a job for it.
3431 // Although it would be de-duplicated, it would still waste I/O.
3432 $cache = ObjectCache
::getLocalClusterInstance();
3433 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3434 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3435 if ( $cache->add( $key, time(), $ttl ) ) {
3436 JobQueueGroup
::singleton()->lazyPush(
3437 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3445 * Returns a list of updates to be performed when this page is deleted. The
3446 * updates should remove any information about this page from secondary data
3447 * stores such as links tables.
3449 * @param Content|null $content Optional Content object for determining the
3450 * necessary updates.
3451 * @return DeferrableUpdate[]
3453 public function getDeletionUpdates( Content
$content = null ) {
3455 // load content object, which may be used to determine the necessary updates.
3456 // XXX: the content may not be needed to determine the updates.
3458 $content = $this->getContent( Revision
::RAW
);
3459 } catch ( Exception
$ex ) {
3460 // If we can't load the content, something is wrong. Perhaps that's why
3461 // the user is trying to delete the page, so let's not fail in that case.
3462 // Note that doDeleteArticleReal() will already have logged an issue with
3463 // loading the content.
3470 $updates = $content->getDeletionUpdates( $this );
3473 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3478 * Whether this content displayed on this page
3479 * comes from the local database
3484 public function isLocal() {
3489 * The display name for the site this content
3490 * come from. If a subclass overrides isLocal(),
3491 * this could return something other than the
3497 public function getWikiDisplayName() {
3503 * Get the source URL for the content on this page,
3504 * typically the canonical URL, but may be a remote
3505 * link if the content comes from another site
3510 public function getSourceURL() {
3511 return $this->getTitle()->getCanonicalURL();
3515 * @param WANObjectCache $cache
3519 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3520 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3522 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );