3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\RevisionRenderer
;
28 use MediaWiki\Revision\RevisionStore
;
29 use MediaWiki\Revision\SlotRoleRegistry
;
30 use MediaWiki\Revision\SlotRecord
;
31 use MediaWiki\Storage\DerivedPageDataUpdater
;
32 use MediaWiki\Storage\PageUpdater
;
33 use MediaWiki\Storage\RevisionSlotsUpdate
;
34 use Wikimedia\Assert\Assert
;
35 use Wikimedia\Rdbms\FakeResultWrapper
;
36 use Wikimedia\Rdbms\IDatabase
;
37 use Wikimedia\Rdbms\LoadBalancer
;
40 * Class representing a MediaWiki article and history.
42 * Some fields are public only for backwards-compatibility. Use accessors.
43 * In the past, this class was part of Article.php and everything was public.
45 class WikiPage
implements Page
, IDBAccessObject
{
46 // Constants for $mDataLoadedFrom and related
51 public $mTitle = null;
56 public $mDataLoaded = false; // !< Boolean
57 public $mIsRedirect = false; // !< Boolean
58 public $mLatest = false; // !< Integer (false means "not loaded")
61 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
62 public $mPreparedEdit = false;
67 protected $mId = null;
70 * @var int One of the READ_* constants
72 protected $mDataLoadedFrom = self
::READ_NONE
;
77 protected $mRedirectTarget = null;
82 protected $mLastRevision = null;
85 * @var string Timestamp of the current revision or empty string if not loaded
87 protected $mTimestamp = '';
92 protected $mTouched = '19700101000000';
97 protected $mLinksUpdated = '19700101000000';
100 * @var DerivedPageDataUpdater|null
102 private $derivedDataUpdater = null;
105 * Constructor and clear the article
106 * @param Title $title Reference to a Title object.
108 public function __construct( Title
$title ) {
109 $this->mTitle
= $title;
113 * Makes sure that the mTitle object is cloned
114 * to the newly cloned WikiPage.
116 public function __clone() {
117 $this->mTitle
= clone $this->mTitle
;
121 * Create a WikiPage object of the appropriate class for the given title.
123 * @param Title $title
125 * @throws MWException
126 * @return WikiPage|WikiCategoryPage|WikiFilePage
128 public static function factory( Title
$title ) {
129 $ns = $title->getNamespace();
131 if ( $ns == NS_MEDIA
) {
132 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
133 } elseif ( $ns < 0 ) {
134 throw new MWException( "Invalid or virtual namespace $ns given." );
138 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
144 $page = new WikiFilePage( $title );
147 $page = new WikiCategoryPage( $title );
150 $page = new WikiPage( $title );
157 * Constructor from a page id
159 * @param int $id Article ID to load
160 * @param string|int $from One of the following values:
161 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
162 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
164 * @return WikiPage|null
166 public static function newFromID( $id, $from = 'fromdb' ) {
167 // page ids are never 0 or negative, see T63166
172 $from = self
::convertSelectType( $from );
173 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
174 $pageQuery = self
::getQueryInfo();
175 $row = $db->selectRow(
176 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
177 [], $pageQuery['joins']
182 return self
::newFromRow( $row, $from );
186 * Constructor from a database row
189 * @param object $row Database row containing at least fields returned by selectFields().
190 * @param string|int $from Source of $data:
191 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
192 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
193 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
196 public static function newFromRow( $row, $from = 'fromdb' ) {
197 $page = self
::factory( Title
::newFromRow( $row ) );
198 $page->loadFromRow( $row, $from );
203 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
205 * @param object|string|int $type
208 protected static function convertSelectType( $type ) {
211 return self
::READ_NORMAL
;
213 return self
::READ_LATEST
;
215 return self
::READ_LOCKING
;
217 // It may already be an integer or whatever else
223 * @return RevisionStore
225 private function getRevisionStore() {
226 return MediaWikiServices
::getInstance()->getRevisionStore();
230 * @return RevisionRenderer
232 private function getRevisionRenderer() {
233 return MediaWikiServices
::getInstance()->getRevisionRenderer();
237 * @return SlotRoleRegistry
239 private function getSlotRoleRegistry() {
240 return MediaWikiServices
::getInstance()->getSlotRoleRegistry();
244 * @return ParserCache
246 private function getParserCache() {
247 return MediaWikiServices
::getInstance()->getParserCache();
251 * @return LoadBalancer
253 private function getDBLoadBalancer() {
254 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
258 * @todo Move this UI stuff somewhere else
260 * @see ContentHandler::getActionOverrides
263 public function getActionOverrides() {
264 return $this->getContentHandler()->getActionOverrides();
268 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
270 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
272 * @return ContentHandler
276 public function getContentHandler() {
277 return ContentHandler
::getForModelID( $this->getContentModel() );
281 * Get the title object of the article
282 * @return Title Title object of this page
284 public function getTitle() {
285 return $this->mTitle
;
292 public function clear() {
293 $this->mDataLoaded
= false;
294 $this->mDataLoadedFrom
= self
::READ_NONE
;
296 $this->clearCacheFields();
300 * Clear the object cache fields
303 protected function clearCacheFields() {
305 $this->mRedirectTarget
= null; // Title object if set
306 $this->mLastRevision
= null; // Latest revision
307 $this->mTouched
= '19700101000000';
308 $this->mLinksUpdated
= '19700101000000';
309 $this->mTimestamp
= '';
310 $this->mIsRedirect
= false;
311 $this->mLatest
= false;
312 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
313 // checks the requested rev ID and content against the cached one. For most
314 // content types, the output should not change during the lifetime of this cache.
315 // Clearing it can cause extra parses on edit for no reason.
319 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
323 public function clearPreparedEdit() {
324 $this->mPreparedEdit
= false;
328 * Return the list of revision fields that should be selected to create
331 * @deprecated since 1.31, use self::getQueryInfo() instead.
334 public static function selectFields() {
335 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
337 wfDeprecated( __METHOD__
, '1.31' );
348 'page_links_updated',
353 if ( $wgContentHandlerUseDB ) {
354 $fields[] = 'page_content_model';
357 if ( $wgPageLanguageUseDB ) {
358 $fields[] = 'page_lang';
365 * Return the tables, fields, and join conditions to be selected to create
368 * @return array With three keys:
369 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
370 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
371 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
373 public static function getQueryInfo() {
374 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
377 'tables' => [ 'page' ],
387 'page_links_updated',
394 if ( $wgContentHandlerUseDB ) {
395 $ret['fields'][] = 'page_content_model';
398 if ( $wgPageLanguageUseDB ) {
399 $ret['fields'][] = 'page_lang';
406 * Fetch a page record with the given conditions
407 * @param IDatabase $dbr
408 * @param array $conditions
409 * @param array $options
410 * @return object|bool Database result resource, or false on failure
412 protected function pageData( $dbr, $conditions, $options = [] ) {
413 $pageQuery = self
::getQueryInfo();
415 // Avoid PHP 7.1 warning of passing $this by reference
418 Hooks
::run( 'ArticlePageDataBefore', [
419 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
422 $row = $dbr->selectRow(
423 $pageQuery['tables'],
424 $pageQuery['fields'],
431 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
437 * Fetch a page record matching the Title object's namespace and title
438 * using a sanitized title string
440 * @param IDatabase $dbr
441 * @param Title $title
442 * @param array $options
443 * @return object|bool Database result resource, or false on failure
445 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
446 return $this->pageData( $dbr, [
447 'page_namespace' => $title->getNamespace(),
448 'page_title' => $title->getDBkey() ], $options );
452 * Fetch a page record matching the requested ID
454 * @param IDatabase $dbr
456 * @param array $options
457 * @return object|bool Database result resource, or false on failure
459 public function pageDataFromId( $dbr, $id, $options = [] ) {
460 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
464 * Load the object from a given source by title
466 * @param object|string|int $from One of the following:
467 * - A DB query result object.
468 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
469 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
470 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
471 * using SELECT FOR UPDATE.
475 public function loadPageData( $from = 'fromdb' ) {
476 $from = self
::convertSelectType( $from );
477 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
478 // We already have the data from the correct location, no need to load it twice.
482 if ( is_int( $from ) ) {
483 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
484 $loadBalancer = $this->getDBLoadBalancer();
485 $db = $loadBalancer->getConnection( $index );
486 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
489 && $index == DB_REPLICA
490 && $loadBalancer->getServerCount() > 1
491 && $loadBalancer->hasOrMadeRecentMasterChanges()
493 $from = self
::READ_LATEST
;
494 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
495 $db = $loadBalancer->getConnection( $index );
496 $data = $this->pageDataFromTitle( $db, $this->mTitle
, $opts );
499 // No idea from where the caller got this data, assume replica DB.
501 $from = self
::READ_NORMAL
;
504 $this->loadFromRow( $data, $from );
508 * Checks whether the page data was loaded using the given database access mode (or better).
512 * @param string|int $from One of the following:
513 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
514 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
515 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
516 * using SELECT FOR UPDATE.
520 public function wasLoadedFrom( $from ) {
521 $from = self
::convertSelectType( $from );
523 if ( !is_int( $from ) ) {
524 // No idea from where the caller got this data, assume replica DB.
525 $from = self
::READ_NORMAL
;
528 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
536 * Load the object from a database row
539 * @param object|bool $data DB row containing fields returned by selectFields() or false
540 * @param string|int $from One of the following:
541 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
542 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
543 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
544 * the master DB using SELECT FOR UPDATE
546 public function loadFromRow( $data, $from ) {
547 $lc = MediaWikiServices
::getInstance()->getLinkCache();
548 $lc->clearLink( $this->mTitle
);
551 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
553 $this->mTitle
->loadFromRow( $data );
555 // Old-fashioned restrictions
556 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
558 $this->mId
= intval( $data->page_id
);
559 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
560 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
561 $this->mIsRedirect
= intval( $data->page_is_redirect
);
562 $this->mLatest
= intval( $data->page_latest
);
563 // T39225: $latest may no longer match the cached latest Revision object.
564 // Double-check the ID of any cached latest Revision object for consistency.
565 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
566 $this->mLastRevision
= null;
567 $this->mTimestamp
= '';
570 $lc->addBadLinkObj( $this->mTitle
);
572 $this->mTitle
->loadFromRow( false );
574 $this->clearCacheFields();
579 $this->mDataLoaded
= true;
580 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
584 * @return int Page ID
586 public function getId() {
587 if ( !$this->mDataLoaded
) {
588 $this->loadPageData();
594 * @return bool Whether or not the page exists in the database
596 public function exists() {
597 if ( !$this->mDataLoaded
) {
598 $this->loadPageData();
600 return $this->mId
> 0;
604 * Check if this page is something we're going to be showing
605 * some sort of sensible content for. If we return false, page
606 * views (plain action=view) will return an HTTP 404 response,
607 * so spiders and robots can know they're following a bad link.
611 public function hasViewableContent() {
612 return $this->mTitle
->isKnown();
616 * Tests if the article content represents a redirect
620 public function isRedirect() {
621 if ( !$this->mDataLoaded
) {
622 $this->loadPageData();
625 return (bool)$this->mIsRedirect
;
629 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
631 * Will use the revisions actual content model if the page exists,
632 * and the page's default if the page doesn't exist yet.
638 public function getContentModel() {
639 if ( $this->exists() ) {
640 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
642 return $cache->getWithSetCallback(
643 $cache->makeKey( 'page-content-model', $this->getLatest() ),
646 $rev = $this->getRevision();
648 // Look at the revision's actual content model
649 return $rev->getContentModel();
651 $title = $this->mTitle
->getPrefixedDBkey();
652 wfWarn( "Page $title exists but has no (visible) revisions!" );
653 return $this->mTitle
->getContentModel();
659 // use the default model for this page
660 return $this->mTitle
->getContentModel();
664 * Loads page_touched and returns a value indicating if it should be used
665 * @return bool True if this page exists and is not a redirect
667 public function checkTouched() {
668 if ( !$this->mDataLoaded
) {
669 $this->loadPageData();
671 return ( $this->mId
&& !$this->mIsRedirect
);
675 * Get the page_touched field
676 * @return string Containing GMT timestamp
678 public function getTouched() {
679 if ( !$this->mDataLoaded
) {
680 $this->loadPageData();
682 return $this->mTouched
;
686 * Get the page_links_updated field
687 * @return string|null Containing GMT timestamp
689 public function getLinksTimestamp() {
690 if ( !$this->mDataLoaded
) {
691 $this->loadPageData();
693 return $this->mLinksUpdated
;
697 * Get the page_latest field
698 * @return int The rev_id of current revision
700 public function getLatest() {
701 if ( !$this->mDataLoaded
) {
702 $this->loadPageData();
704 return (int)$this->mLatest
;
708 * Get the Revision object of the oldest revision
709 * @return Revision|null
711 public function getOldestRevision() {
712 // Try using the replica DB first, then try the master
713 $rev = $this->mTitle
->getFirstRevision();
715 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
721 * Loads everything except the text
722 * This isn't necessary for all uses, so it's only done if needed.
724 protected function loadLastEdit() {
725 if ( $this->mLastRevision
!== null ) {
726 return; // already loaded
729 $latest = $this->getLatest();
731 return; // page doesn't exist or is missing page_latest info
734 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
735 // T39225: if session S1 loads the page row FOR UPDATE, the result always
736 // includes the latest changes committed. This is true even within REPEATABLE-READ
737 // transactions, where S1 normally only sees changes committed before the first S1
738 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
739 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
740 // happened after the first S1 SELECT.
741 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
742 $flags = Revision
::READ_LOCKING
;
743 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
744 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
745 // Bug T93976: if page_latest was loaded from the master, fetch the
746 // revision from there as well, as it may not exist yet on a replica DB.
747 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
748 $flags = Revision
::READ_LATEST
;
749 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
751 $dbr = wfGetDB( DB_REPLICA
);
752 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
755 if ( $revision ) { // sanity
756 $this->setLastEdit( $revision );
761 * Set the latest revision
762 * @param Revision $revision
764 protected function setLastEdit( Revision
$revision ) {
765 $this->mLastRevision
= $revision;
766 $this->mTimestamp
= $revision->getTimestamp();
770 * Get the latest revision
771 * @return Revision|null
773 public function getRevision() {
774 $this->loadLastEdit();
775 if ( $this->mLastRevision
) {
776 return $this->mLastRevision
;
782 * Get the latest revision
783 * @return RevisionRecord|null
785 public function getRevisionRecord() {
786 $this->loadLastEdit();
787 if ( $this->mLastRevision
) {
788 return $this->mLastRevision
->getRevisionRecord();
794 * Get the content of the current revision. No side-effects...
796 * @param int $audience One of:
797 * Revision::FOR_PUBLIC to be displayed to all users
798 * Revision::FOR_THIS_USER to be displayed to $wgUser
799 * Revision::RAW get the text regardless of permissions
800 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
801 * to the $audience parameter
802 * @return Content|null The content of the current revision
806 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
807 $this->loadLastEdit();
808 if ( $this->mLastRevision
) {
809 return $this->mLastRevision
->getContent( $audience, $user );
815 * @return string MW timestamp of last article revision
817 public function getTimestamp() {
818 // Check if the field has been filled by WikiPage::setTimestamp()
819 if ( !$this->mTimestamp
) {
820 $this->loadLastEdit();
823 return wfTimestamp( TS_MW
, $this->mTimestamp
);
827 * Set the page timestamp (use only to avoid DB queries)
828 * @param string $ts MW timestamp of last article revision
831 public function setTimestamp( $ts ) {
832 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
836 * @param int $audience One of:
837 * Revision::FOR_PUBLIC to be displayed to all users
838 * Revision::FOR_THIS_USER to be displayed to the given user
839 * Revision::RAW get the text regardless of permissions
840 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
841 * to the $audience parameter
842 * @return int User ID for the user that made the last article revision
844 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
845 $this->loadLastEdit();
846 if ( $this->mLastRevision
) {
847 return $this->mLastRevision
->getUser( $audience, $user );
854 * Get the User object of the user who created the page
855 * @param int $audience One of:
856 * Revision::FOR_PUBLIC to be displayed to all users
857 * Revision::FOR_THIS_USER to be displayed to the given user
858 * Revision::RAW get the text regardless of permissions
859 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
860 * to the $audience parameter
863 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
864 $revision = $this->getOldestRevision();
866 $userName = $revision->getUserText( $audience, $user );
867 return User
::newFromName( $userName, false );
874 * @param int $audience One of:
875 * Revision::FOR_PUBLIC to be displayed to all users
876 * Revision::FOR_THIS_USER to be displayed to the given user
877 * Revision::RAW get the text regardless of permissions
878 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
879 * to the $audience parameter
880 * @return string Username of the user that made the last article revision
882 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
883 $this->loadLastEdit();
884 if ( $this->mLastRevision
) {
885 return $this->mLastRevision
->getUserText( $audience, $user );
892 * @param int $audience One of:
893 * Revision::FOR_PUBLIC to be displayed to all users
894 * Revision::FOR_THIS_USER to be displayed to the given user
895 * Revision::RAW get the text regardless of permissions
896 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
897 * to the $audience parameter
898 * @return string|null Comment stored for the last article revision, or null if the specified
899 * audience does not have access to the comment.
901 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
902 $this->loadLastEdit();
903 if ( $this->mLastRevision
) {
904 return $this->mLastRevision
->getComment( $audience, $user );
911 * Returns true if last revision was marked as "minor edit"
913 * @return bool Minor edit indicator for the last article revision.
915 public function getMinorEdit() {
916 $this->loadLastEdit();
917 if ( $this->mLastRevision
) {
918 return $this->mLastRevision
->isMinor();
925 * Determine whether a page would be suitable for being counted as an
926 * article in the site_stats table based on the title & its content
928 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
929 * if false, the current database state will be used
932 public function isCountable( $editInfo = false ) {
933 global $wgArticleCountMethod;
935 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
937 if ( !$this->mTitle
->isContentPage() ) {
942 // NOTE: only the main slot can make a page a redirect
943 $content = $editInfo->pstContent
;
945 $content = $this->getContent();
948 if ( !$content ||
$content->isRedirect() ) {
954 if ( $wgArticleCountMethod === 'link' ) {
955 // nasty special case to avoid re-parsing to detect links
958 // ParserOutput::getLinks() is a 2D array of page links, so
959 // to be really correct we would need to recurse in the array
960 // but the main array should only have items in it if there are
962 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
964 // NOTE: keep in sync with RevisionRenderer::getLinkCount
965 // NOTE: keep in sync with DerivedPageDataUpdater::isCountable
966 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
967 [ 'pl_from' => $this->getId() ], __METHOD__
);
971 // TODO: MCR: determine $hasLinks for each slot, and use that info
972 // with that slot's Content's isCountable method. That requires per-
973 // slot ParserOutput in the ParserCache, or per-slot info in the
975 return $content->isCountable( $hasLinks );
979 * If this page is a redirect, get its target
981 * The target will be fetched from the redirect table if possible.
982 * If this page doesn't have an entry there, call insertRedirect()
983 * @return Title|null Title object, or null if this page is not a redirect
985 public function getRedirectTarget() {
986 if ( !$this->mTitle
->isRedirect() ) {
990 if ( $this->mRedirectTarget
!== null ) {
991 return $this->mRedirectTarget
;
994 // Query the redirect table
995 $dbr = wfGetDB( DB_REPLICA
);
996 $row = $dbr->selectRow( 'redirect',
997 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
998 [ 'rd_from' => $this->getId() ],
1002 // rd_fragment and rd_interwiki were added later, populate them if empty
1003 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
1004 // (T203942) We can't redirect to Media namespace because it's virtual.
1005 // We don't want to modify Title objects farther down the
1006 // line. So, let's fix this here by changing to File namespace.
1007 if ( $row->rd_namespace
== NS_MEDIA
) {
1008 $namespace = NS_FILE
;
1010 $namespace = $row->rd_namespace
;
1012 $this->mRedirectTarget
= Title
::makeTitle(
1013 $namespace, $row->rd_title
,
1014 $row->rd_fragment
, $row->rd_interwiki
1016 return $this->mRedirectTarget
;
1019 // This page doesn't have an entry in the redirect table
1020 $this->mRedirectTarget
= $this->insertRedirect();
1021 return $this->mRedirectTarget
;
1025 * Insert an entry for this page into the redirect table if the content is a redirect
1027 * The database update will be deferred via DeferredUpdates
1029 * Don't call this function directly unless you know what you're doing.
1030 * @return Title|null Title object or null if not a redirect
1032 public function insertRedirect() {
1033 $content = $this->getContent();
1034 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
1039 // Update the DB post-send if the page has not cached since now
1040 $latest = $this->getLatest();
1041 DeferredUpdates
::addCallableUpdate(
1042 function () use ( $retval, $latest ) {
1043 $this->insertRedirectEntry( $retval, $latest );
1045 DeferredUpdates
::POSTSEND
,
1046 wfGetDB( DB_MASTER
)
1053 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
1054 * @param Title $rt Redirect target
1055 * @param int|null $oldLatest Prior page_latest for check and set
1057 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
1058 $dbw = wfGetDB( DB_MASTER
);
1059 $dbw->startAtomic( __METHOD__
);
1061 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
1062 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1063 $truncatedFragment = $contLang->truncateForDatabase( $rt->getFragment(), 255 );
1067 'rd_from' => $this->getId(),
1068 'rd_namespace' => $rt->getNamespace(),
1069 'rd_title' => $rt->getDBkey(),
1070 'rd_fragment' => $truncatedFragment,
1071 'rd_interwiki' => $rt->getInterwiki(),
1075 'rd_namespace' => $rt->getNamespace(),
1076 'rd_title' => $rt->getDBkey(),
1077 'rd_fragment' => $truncatedFragment,
1078 'rd_interwiki' => $rt->getInterwiki(),
1084 $dbw->endAtomic( __METHOD__
);
1088 * Get the Title object or URL this page redirects to
1090 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1092 public function followRedirect() {
1093 return $this->getRedirectURL( $this->getRedirectTarget() );
1097 * Get the Title object or URL to use for a redirect. We use Title
1098 * objects for same-wiki, non-special redirects and URLs for everything
1100 * @param Title $rt Redirect target
1101 * @return bool|Title|string False, Title object of local target, or string with URL
1103 public function getRedirectURL( $rt ) {
1108 if ( $rt->isExternal() ) {
1109 if ( $rt->isLocal() ) {
1110 // Offsite wikis need an HTTP redirect.
1111 // This can be hard to reverse and may produce loops,
1112 // so they may be disabled in the site configuration.
1113 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1114 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1116 // External pages without "local" bit set are not valid
1122 if ( $rt->isSpecialPage() ) {
1123 // Gotta handle redirects to special pages differently:
1124 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1125 // Some pages are not valid targets.
1126 if ( $rt->isValidRedirectTarget() ) {
1127 return $rt->getFullURL();
1137 * Get a list of users who have edited this article, not including the user who made
1138 * the most recent revision, which you can get from $article->getUser() if you want it
1139 * @return UserArrayFromResult
1141 public function getContributors() {
1142 // @todo: This is expensive; cache this info somewhere.
1144 $dbr = wfGetDB( DB_REPLICA
);
1146 $actorMigration = ActorMigration
::newMigration();
1147 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1149 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1152 'user_id' => $actorQuery['fields']['rev_user'],
1153 'user_name' => $actorQuery['fields']['rev_user_text'],
1154 'actor_id' => $actorQuery['fields']['rev_actor'],
1155 'user_real_name' => 'MIN(user_real_name)',
1156 'timestamp' => 'MAX(rev_timestamp)',
1159 $conds = [ 'rev_page' => $this->getId() ];
1161 // The user who made the top revision gets credited as "this page was last edited by
1162 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1163 $user = $this->getUser()
1164 ? User
::newFromId( $this->getUser() )
1165 : User
::newFromName( $this->getUserText(), false );
1166 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1169 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1172 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1173 ] +
$actorQuery['joins'];
1176 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1177 'ORDER BY' => 'timestamp DESC',
1180 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1181 return new UserArrayFromResult( $res );
1185 * Should the parser cache be used?
1187 * @param ParserOptions $parserOptions ParserOptions to check
1191 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1192 return $parserOptions->getStubThreshold() == 0
1194 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1195 && $this->getContentHandler()->isParserCacheSupported();
1199 * Get a ParserOutput for the given ParserOptions and revision ID.
1201 * The parser cache will be used if possible. Cache misses that result
1202 * in parser runs are debounced with PoolCounter.
1204 * XXX merge this with updateParserCache()?
1207 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1208 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1209 * get the current revision (default value)
1210 * @param bool $forceParse Force reindexing, regardless of cache settings
1211 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1213 public function getParserOutput(
1214 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1217 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1219 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1220 throw new InvalidArgumentException(
1221 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1225 wfDebug( __METHOD__
.
1226 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1227 if ( $parserOptions->getStubThreshold() ) {
1228 wfIncrStats( 'pcache.miss.stub' );
1231 if ( $useParserCache ) {
1232 $parserOutput = $this->getParserCache()
1233 ->get( $this, $parserOptions );
1234 if ( $parserOutput !== false ) {
1235 return $parserOutput;
1239 if ( $oldid === null ||
$oldid === 0 ) {
1240 $oldid = $this->getLatest();
1243 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1246 return $pool->getParserOutput();
1250 * Do standard deferred updates after page view (existing or missing page)
1251 * @param User $user The relevant user
1252 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1254 public function doViewUpdates( User
$user, $oldid = 0 ) {
1255 if ( wfReadOnly() ) {
1259 // Update newtalk / watchlist notification status;
1260 // Avoid outage if the master is not reachable by using a deferred updated
1261 DeferredUpdates
::addCallableUpdate(
1262 function () use ( $user, $oldid ) {
1263 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1265 $user->clearNotification( $this->mTitle
, $oldid );
1267 DeferredUpdates
::PRESEND
1272 * Perform the actions of a page purging
1274 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1275 * controlled how much purging was done.
1277 public function doPurge() {
1278 // Avoid PHP 7.1 warning of passing $this by reference
1281 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1285 $this->mTitle
->invalidateCache();
1288 HTMLFileCache
::clearFileCache( $this->getTitle() );
1289 // Send purge after above page_touched update was committed
1290 DeferredUpdates
::addUpdate(
1291 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1292 DeferredUpdates
::PRESEND
1295 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1296 $messageCache = MessageCache
::singleton();
1297 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1304 * Insert a new empty page record for this article.
1305 * This *must* be followed up by creating a revision
1306 * and running $this->updateRevisionOn( ... );
1307 * or else the record will be left in a funky state.
1308 * Best if all done inside a transaction.
1310 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1312 * @param IDatabase $dbw
1313 * @param int|null $pageId Custom page ID that will be used for the insert statement
1315 * @return bool|int The newly created page_id key; false if the row was not
1316 * inserted, e.g. because the title already existed or because the specified
1317 * page ID is already in use.
1319 public function insertOn( $dbw, $pageId = null ) {
1320 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1324 'page_namespace' => $this->mTitle
->getNamespace(),
1325 'page_title' => $this->mTitle
->getDBkey(),
1326 'page_restrictions' => '',
1327 'page_is_redirect' => 0, // Will set this shortly...
1329 'page_random' => wfRandom(),
1330 'page_touched' => $dbw->timestamp(),
1331 'page_latest' => 0, // Fill this in shortly...
1332 'page_len' => 0, // Fill this in shortly...
1333 ] +
$pageIdForInsert,
1338 if ( $dbw->affectedRows() > 0 ) {
1339 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1340 $this->mId
= $newid;
1341 $this->mTitle
->resetArticleID( $newid );
1345 return false; // nothing changed
1350 * Update the page record to point to a newly saved revision.
1352 * @todo Factor out into a PageStore service, or move into PageUpdater.
1354 * @param IDatabase $dbw
1355 * @param Revision $revision For ID number, and text used to set
1356 * length and redirect status fields
1357 * @param int|null $lastRevision If given, will not overwrite the page field
1358 * when different from the currently set value.
1359 * Giving 0 indicates the new page flag should be set on.
1360 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1361 * removing rows in redirect table.
1362 * @return bool Success; false if the page row was missing or page_latest changed
1364 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1365 $lastRevIsRedirect = null
1367 global $wgContentHandlerUseDB;
1369 // TODO: move into PageUpdater or PageStore
1370 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1371 // and in the compat stub!
1373 // Assertion to try to catch T92046
1374 if ( (int)$revision->getId() === 0 ) {
1375 throw new InvalidArgumentException(
1376 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1380 $content = $revision->getContent();
1381 $len = $content ?
$content->getSize() : 0;
1382 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1384 $conditions = [ 'page_id' => $this->getId() ];
1386 if ( !is_null( $lastRevision ) ) {
1387 // An extra check against threads stepping on each other
1388 $conditions['page_latest'] = $lastRevision;
1391 $revId = $revision->getId();
1392 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1395 'page_latest' => $revId,
1396 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1397 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1398 'page_is_redirect' => $rt !== null ?
1 : 0,
1402 if ( $wgContentHandlerUseDB ) {
1403 $row['page_content_model'] = $revision->getContentModel();
1406 $dbw->update( 'page',
1411 $result = $dbw->affectedRows() > 0;
1413 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1414 $this->setLastEdit( $revision );
1415 $this->mLatest
= $revision->getId();
1416 $this->mIsRedirect
= (bool)$rt;
1417 // Update the LinkCache.
1418 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1419 $linkCache->addGoodLinkObj(
1425 $revision->getContentModel()
1433 * Add row to the redirect table if this is a redirect, remove otherwise.
1435 * @param IDatabase $dbw
1436 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1437 * or NULL if this is not a redirect
1438 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1439 * removing rows in redirect table.
1440 * @return bool True on success, false on failure
1443 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1444 // Always update redirects (target link might have changed)
1445 // Update/Insert if we don't know if the last revision was a redirect or not
1446 // Delete if changing from redirect to non-redirect
1447 $isRedirect = !is_null( $redirectTitle );
1449 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1453 if ( $isRedirect ) {
1454 $this->insertRedirectEntry( $redirectTitle );
1456 // This is not a redirect, remove row from redirect table
1457 $where = [ 'rd_from' => $this->getId() ];
1458 $dbw->delete( 'redirect', $where, __METHOD__
);
1461 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1462 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1465 return ( $dbw->affectedRows() != 0 );
1469 * If the given revision is newer than the currently set page_latest,
1470 * update the page record. Otherwise, do nothing.
1472 * @deprecated since 1.24, use updateRevisionOn instead
1474 * @param IDatabase $dbw
1475 * @param Revision $revision
1478 public function updateIfNewerOn( $dbw, $revision ) {
1479 $row = $dbw->selectRow(
1480 [ 'revision', 'page' ],
1481 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1483 'page_id' => $this->getId(),
1484 'page_latest=rev_id' ],
1488 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1491 $prev = $row->rev_id
;
1492 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1494 // No or missing previous revision; mark the page as new
1496 $lastRevIsRedirect = null;
1499 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1505 * Helper method for checking whether two revisions have differences that go
1506 * beyond the main slot.
1508 * MCR migration note: this method should go away!
1510 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1512 * @param Revision $a
1513 * @param Revision $b
1516 public static function hasDifferencesOutsideMainSlot( Revision
$a, Revision
$b ) {
1517 $aSlots = $a->getRevisionRecord()->getSlots();
1518 $bSlots = $b->getRevisionRecord()->getSlots();
1519 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1521 return ( $changedRoles !== [ SlotRecord
::MAIN
] && $changedRoles !== [] );
1525 * Get the content that needs to be saved in order to undo all revisions
1526 * between $undo and $undoafter. Revisions must belong to the same page,
1527 * must exist and must not be deleted
1529 * @param Revision $undo
1530 * @param Revision $undoafter Must be an earlier revision than $undo
1531 * @return Content|bool Content on success, false on failure
1533 * Before we had the Content object, this was done in getUndoText
1535 public function getUndoContent( Revision
$undo, Revision
$undoafter ) {
1536 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1538 if ( self
::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1539 // Cannot yet undo edits that involve anything other the main slot.
1543 $handler = $undo->getContentHandler();
1544 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1548 * Returns true if this page's content model supports sections.
1552 * @todo The skin should check this and not offer section functionality if
1553 * sections are not supported.
1554 * @todo The EditPage should check this and not offer section functionality
1555 * if sections are not supported.
1557 public function supportsSections() {
1558 return $this->getContentHandler()->supportsSections();
1562 * @param string|int|null|bool $sectionId Section identifier as a number or string
1563 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1564 * or 'new' for a new section.
1565 * @param Content $sectionContent New content of the section.
1566 * @param string $sectionTitle New section's subject, only if $section is "new".
1567 * @param string $edittime Revision timestamp or null to use the current revision.
1569 * @throws MWException
1570 * @return Content|null New complete article content, or null if error.
1573 * @deprecated since 1.24, use replaceSectionAtRev instead
1575 public function replaceSectionContent(
1576 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1579 if ( $edittime && $sectionId !== 'new' ) {
1580 $lb = $this->getDBLoadBalancer();
1581 $dbr = $lb->getConnection( DB_REPLICA
);
1582 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1583 // Try the master if this thread may have just added it.
1584 // This could be abstracted into a Revision method, but we don't want
1585 // to encourage loading of revisions by timestamp.
1587 && $lb->getServerCount() > 1
1588 && $lb->hasOrMadeRecentMasterChanges()
1590 $dbw = $lb->getConnection( DB_MASTER
);
1591 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1594 $baseRevId = $rev->getId();
1598 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1602 * @param string|int|null|bool $sectionId Section identifier as a number or string
1603 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1604 * or 'new' for a new section.
1605 * @param Content $sectionContent New content of the section.
1606 * @param string $sectionTitle New section's subject, only if $section is "new".
1607 * @param int|null $baseRevId
1609 * @throws MWException
1610 * @return Content|null New complete article content, or null if error.
1614 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1615 $sectionTitle = '', $baseRevId = null
1617 if ( strval( $sectionId ) === '' ) {
1618 // Whole-page edit; let the whole text through
1619 $newContent = $sectionContent;
1621 if ( !$this->supportsSections() ) {
1622 throw new MWException( "sections not supported for content model " .
1623 $this->getContentHandler()->getModelID() );
1626 // T32711: always use current version when adding a new section
1627 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1628 $oldContent = $this->getContent();
1630 $rev = Revision
::newFromId( $baseRevId );
1632 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1633 $this->getId() . "; section: $sectionId)\n" );
1637 $oldContent = $rev->getContent();
1640 if ( !$oldContent ) {
1641 wfDebug( __METHOD__
. ": no page text\n" );
1645 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1652 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1654 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1655 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1658 * @return int Updated $flags
1660 public function checkFlags( $flags ) {
1661 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1662 if ( $this->exists() ) {
1663 $flags |
= EDIT_UPDATE
;
1673 * @return DerivedPageDataUpdater
1675 private function newDerivedDataUpdater() {
1676 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1678 $derivedDataUpdater = new DerivedPageDataUpdater(
1679 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1680 $this->getRevisionStore(),
1681 $this->getRevisionRenderer(),
1682 $this->getSlotRoleRegistry(),
1683 $this->getParserCache(),
1684 JobQueueGroup
::singleton(),
1685 MessageCache
::singleton(),
1686 MediaWikiServices
::getInstance()->getContentLanguage(),
1687 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()
1690 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1691 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1693 return $derivedDataUpdater;
1697 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1698 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1699 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1700 * returned matches that caller's expectations, allowing an existing instance to be re-used
1701 * if the given parameters match that instance's internal state according to
1702 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1703 * match the existign one.
1705 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1706 * created, replacing any DerivedPageDataUpdater currently cached.
1708 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1712 * @param User|null $forUser The user that will be used for, or was used for, PST.
1713 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1714 * to perform updates, if the edit was already saved.
1715 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1716 * if the edit was not yet saved.
1717 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1718 * revision as the edit's parent revision. This ensures that the same
1719 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1721 * @return DerivedPageDataUpdater
1723 private function getDerivedDataUpdater(
1724 User
$forUser = null,
1725 RevisionRecord
$forRevision = null,
1726 RevisionSlotsUpdate
$forUpdate = null,
1729 if ( !$forRevision && !$forUpdate ) {
1730 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1731 // going to use it with.
1732 $this->derivedDataUpdater
= null;
1735 if ( $this->derivedDataUpdater
&& !$this->derivedDataUpdater
->isContentPrepared() ) {
1736 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1737 // to it did not yet initialize it, because we don't know what data it will be
1738 // initialized with.
1739 $this->derivedDataUpdater
= null;
1742 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1743 // However, there is no good way to construct a cache key. We'd need to check against all
1744 // cached instances.
1746 if ( $this->derivedDataUpdater
1747 && !$this->derivedDataUpdater
->isReusableFor(
1751 $forEdit ?
$this->getLatest() : null
1754 $this->derivedDataUpdater
= null;
1757 if ( !$this->derivedDataUpdater
) {
1758 $this->derivedDataUpdater
= $this->newDerivedDataUpdater();
1761 return $this->derivedDataUpdater
;
1765 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1767 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1768 * and to protected such conflict resolution from concurrent edits using a check-and-set
1774 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1775 * that may already have been returned via getDerivedDataUpdater to be re-used.
1777 * @return PageUpdater
1779 public function newPageUpdater( User
$user, RevisionSlotsUpdate
$forUpdate = null ) {
1780 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1782 $pageUpdater = new PageUpdater(
1784 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1785 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1786 $this->getDBLoadBalancer(),
1787 $this->getRevisionStore(),
1788 $this->getSlotRoleRegistry()
1791 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1792 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1793 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1795 return $pageUpdater;
1799 * Change an existing article or create a new article. Updates RC and all necessary caches,
1800 * optionally via the deferred update array.
1802 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1803 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1804 * apply the autopatrol right as appropriate.
1806 * @param Content $content New content
1807 * @param string|CommentStoreComment $summary Edit summary
1808 * @param int $flags Bitfield:
1810 * Article is known or assumed to be non-existent, create a new one
1812 * Article is known or assumed to be pre-existing, update it
1814 * Mark this edit minor, if the user is allowed to do so
1816 * Do not log the change in recentchanges
1818 * Mark the edit a "bot" edit regardless of user rights
1820 * Fill in blank summaries with generated text where possible
1822 * Signal that the page retrieve/save cycle happened entirely in this request.
1824 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1825 * article will be detected. If EDIT_UPDATE is specified and the article
1826 * doesn't exist, the function will return an edit-gone-missing error. If
1827 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1828 * error will be returned. These two conditions are also possible with
1829 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1831 * @param bool|int $originalRevId: The ID of an original revision that the edit
1832 * restores or repeats. The new revision is expected to have the exact same content as
1833 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1834 * which are created to record things like page moves.
1835 * @param User|null $user The user doing the edit
1836 * @param string|null $serialFormat IGNORED.
1837 * @param array|null $tags Change tags to apply to this edit
1838 * Callers are responsible for permission checks
1839 * (with ChangeTags::canAddTagsAccompanyingChange)
1840 * @param Int $undidRevId Id of revision that was undone or 0
1842 * @throws MWException
1843 * @return Status Possible errors:
1844 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1845 * set the fatal flag of $status.
1846 * edit-gone-missing: In update mode, but the article didn't exist.
1847 * edit-conflict: In update mode, the article changed unexpectedly.
1848 * edit-no-change: Warning that the text was the same as before.
1849 * edit-already-exists: In creation mode, but the article already exists.
1851 * Extensions may define additional errors.
1853 * $return->value will contain an associative array with members as follows:
1854 * new: Boolean indicating if the function attempted to create a new article.
1855 * revision: The revision object for the inserted revision, or null.
1858 * @throws MWException
1860 public function doEditContent(
1861 Content
$content, $summary, $flags = 0, $originalRevId = false,
1862 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1864 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1866 if ( !( $summary instanceof CommentStoreComment
) ) {
1867 $summary = CommentStoreComment
::newUnsavedComment( trim( $summary ) );
1874 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1875 // Checking the minoredit right should be done in the same place the 'bot' right is
1876 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1877 if ( ( $flags & EDIT_MINOR
) && !$user->isAllowed( 'minoredit' ) ) {
1878 $flags = ( $flags & ~EDIT_MINOR
);
1881 $slotsUpdate = new RevisionSlotsUpdate();
1882 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
1884 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1885 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1886 // used by this PageUpdater. However, there is no guarantee for this.
1887 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1888 $updater->setContent( SlotRecord
::MAIN
, $content );
1889 $updater->setOriginalRevisionId( $originalRevId );
1890 $updater->setUndidRevisionId( $undidRevId );
1892 $needsPatrol = $wgUseRCPatrol ||
( $wgUseNPPatrol && !$this->exists() );
1894 // TODO: this logic should not be in the storage layer, it's here for compatibility
1895 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1896 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1897 if ( $needsPatrol && $this->getTitle()->userCan( 'autopatrol', $user ) ) {
1898 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
1901 $updater->addTags( $tags );
1903 $revRec = $updater->saveRevision(
1908 // $revRec will be null if the edit failed, or if no new revision was created because
1909 // the content did not change.
1911 // update cached fields
1912 // TODO: this is currently redundant to what is done in updateRevisionOn.
1913 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1914 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1915 $this->mLatest
= $revRec->getId();
1918 return $updater->getStatus();
1922 * Get parser options suitable for rendering the primary article wikitext
1924 * @see ParserOptions::newCanonical
1926 * @param IContextSource|User|string $context One of the following:
1927 * - IContextSource: Use the User and the Language of the provided
1929 * - User: Use the provided User object and $wgLang for the language,
1930 * so use an IContextSource object if possible.
1931 * - 'canonical': Canonical options (anonymous user with default
1932 * preferences and content language).
1933 * @return ParserOptions
1935 public function makeParserOptions( $context ) {
1936 $options = ParserOptions
::newCanonical( $context );
1938 if ( $this->getTitle()->isConversionTable() ) {
1939 // @todo ConversionTable should become a separate content model, so
1940 // we don't need special cases like this one.
1941 $options->disableContentConversion();
1948 * Prepare content which is about to be saved.
1950 * Prior to 1.30, this returned a stdClass.
1952 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1954 * @param Content $content
1955 * @param Revision|RevisionRecord|int|null $revision Revision object.
1956 * For backwards compatibility, a revision ID is also accepted,
1957 * but this is deprecated.
1958 * Used with vary-revision or vary-revision-id.
1959 * @param User|null $user
1960 * @param string|null $serialFormat IGNORED
1961 * @param bool $useCache Check shared prepared edit cache
1963 * @return PreparedEdit
1967 public function prepareContentForEdit(
1971 $serialFormat = null,
1980 if ( !is_object( $revision ) ) {
1982 // This code path is deprecated, and nothing is known to
1983 // use it, so performance here shouldn't be a worry.
1984 if ( $revid !== null ) {
1985 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1986 $store = $this->getRevisionStore();
1987 $revision = $store->getRevisionById( $revid, Revision
::READ_LATEST
);
1991 } elseif ( $revision instanceof Revision
) {
1992 $revision = $revision->getRevisionRecord();
1995 $slots = RevisionSlotsUpdate
::newFromContent( [ SlotRecord
::MAIN
=> $content ] );
1996 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1998 if ( !$updater->isUpdatePrepared() ) {
1999 $updater->prepareContent( $user, $slots, $useCache );
2002 $updater->prepareUpdate(
2005 'causeAction' => 'prepare-edit',
2006 'causeAgent' => $user->getName(),
2012 return $updater->getPreparedEdit();
2016 * Do standard deferred updates after page edit.
2017 * Update links tables, site stats, search index and message cache.
2018 * Purges pages that include this page if the text was changed here.
2019 * Every 100th edit, prune the recent changes table.
2021 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2023 * @param Revision $revision
2024 * @param User $user User object that did the revision
2025 * @param array $options Array of options, following indexes are used:
2026 * - changed: bool, whether the revision changed the content (default true)
2027 * - created: bool, whether the revision created the page (default false)
2028 * - moved: bool, whether the page was moved (default false)
2029 * - restored: bool, whether the page was undeleted (default false)
2030 * - oldrevision: Revision object for the pre-update revision (default null)
2031 * - oldcountable: bool, null, or string 'no-change' (default null):
2032 * - bool: whether the page was counted as an article before that
2033 * revision, only used in changed is true and created is false
2034 * - null: if created is false, don't update the article count; if created
2035 * is true, do update the article count
2036 * - 'no-change': don't update the article count, ever
2037 * - causeAction: an arbitrary string identifying the reason for the update.
2038 * See DataUpdate::getCauseAction(). (default 'edit-page')
2039 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2040 * (string, defaults to the passed user)
2042 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2044 'causeAction' => 'edit-page',
2045 'causeAgent' => $user->getName(),
2048 $revision = $revision->getRevisionRecord();
2050 $updater = $this->getDerivedDataUpdater( $user, $revision );
2052 $updater->prepareUpdate( $revision, $options );
2054 $updater->doUpdates();
2058 * Update the parser cache.
2060 * @note This is a temporary workaround until there is a proper data updater class.
2061 * It will become deprecated soon.
2063 * @param array $options
2064 * - causeAction: an arbitrary string identifying the reason for the update.
2065 * See DataUpdate::getCauseAction(). (default 'edit-page')
2066 * - causeAgent: name of the user who caused the update (string, defaults to the
2067 * user who created the revision)
2070 public function updateParserCache( array $options = [] ) {
2071 $revision = $this->getRevisionRecord();
2072 if ( !$revision ||
!$revision->getId() ) {
2073 LoggerFactory
::getInstance( 'wikipage' )->info(
2074 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2078 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2080 $updater = $this->getDerivedDataUpdater( $user, $revision );
2081 $updater->prepareUpdate( $revision, $options );
2082 $updater->doParserCacheUpdate();
2086 * Do secondary data updates (such as updating link tables).
2087 * Secondary data updates are only a small part of the updates needed after saving
2088 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2089 * secondary data updates). This method is provided for partial purges.
2091 * @note This is a temporary workaround until there is a proper data updater class.
2092 * It will become deprecated soon.
2094 * @param array $options
2095 * - recursive (bool, default true): whether to do a recursive update (update pages that
2096 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2097 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2098 * was something that did not really change the page, such as a null edit.
2099 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2100 * user who created the revision)
2101 * - causeAction: an arbitrary string identifying the reason for the update.
2102 * See DataUpdate::getCauseAction(). (default 'unknown')
2103 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2104 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2105 * Note that even when this is set to false, some updates might still get deferred (as
2106 * some update might directly add child updates to DeferredUpdates).
2107 * - transactionTicket: a transaction ticket from LBFactory::getEmptyTransactionTicket(),
2108 * only when defer is false (default: null)
2111 public function doSecondaryDataUpdates( array $options = [] ) {
2112 $options['recursive'] = $options['recursive'] ??
true;
2113 $revision = $this->getRevisionRecord();
2114 if ( !$revision ||
!$revision->getId() ) {
2115 LoggerFactory
::getInstance( 'wikipage' )->info(
2116 __METHOD__
. 'called with ' . ( $revision ?
'unsaved' : 'no' ) . ' revision'
2120 $user = User
::newFromIdentity( $revision->getUser( RevisionRecord
::RAW
) );
2122 $updater = $this->getDerivedDataUpdater( $user, $revision );
2123 $updater->prepareUpdate( $revision, $options );
2124 $updater->doSecondaryDataUpdates( $options );
2128 * Update the article's restriction field, and leave a log entry.
2129 * This works for protection both existing and non-existing pages.
2131 * @param array $limit Set of restriction keys
2132 * @param array $expiry Per restriction type expiration
2133 * @param int &$cascade Set to false if cascading protection isn't allowed.
2134 * @param string $reason
2135 * @param User $user The user updating the restrictions
2136 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2137 * ($user should be able to add the specified tags before this is called)
2138 * @return Status Status object; if action is taken, $status->value is the log_id of the
2139 * protection log entry.
2141 public function doUpdateRestrictions( array $limit, array $expiry,
2142 &$cascade, $reason, User
$user, $tags = null
2144 global $wgCascadingRestrictionLevels;
2146 if ( wfReadOnly() ) {
2147 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2150 $this->loadPageData( 'fromdbmaster' );
2151 $this->mTitle
->loadRestrictions( null, Title
::READ_LATEST
);
2152 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2153 $id = $this->getId();
2159 // Take this opportunity to purge out expired restrictions
2160 Title
::purgeExpiredRestrictions();
2162 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2163 // we expect a single selection, but the schema allows otherwise.
2164 $isProtected = false;
2168 $dbw = wfGetDB( DB_MASTER
);
2170 foreach ( $restrictionTypes as $action ) {
2171 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2172 $expiry[$action] = 'infinity';
2174 if ( !isset( $limit[$action] ) ) {
2175 $limit[$action] = '';
2176 } elseif ( $limit[$action] != '' ) {
2180 // Get current restrictions on $action
2181 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2182 if ( $current != '' ) {
2183 $isProtected = true;
2186 if ( $limit[$action] != $current ) {
2188 } elseif ( $limit[$action] != '' ) {
2189 // Only check expiry change if the action is actually being
2190 // protected, since expiry does nothing on an not-protected
2192 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2198 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2202 // If nothing has changed, do nothing
2204 return Status
::newGood();
2207 if ( !$protect ) { // No protection at all means unprotection
2208 $revCommentMsg = 'unprotectedarticle-comment';
2209 $logAction = 'unprotect';
2210 } elseif ( $isProtected ) {
2211 $revCommentMsg = 'modifiedarticleprotection-comment';
2212 $logAction = 'modify';
2214 $revCommentMsg = 'protectedarticle-comment';
2215 $logAction = 'protect';
2218 $logRelationsValues = [];
2219 $logRelationsField = null;
2220 $logParamsDetails = [];
2222 // Null revision (used for change tag insertion)
2223 $nullRevision = null;
2225 if ( $id ) { // Protection of existing page
2226 // Avoid PHP 7.1 warning of passing $this by reference
2229 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2230 return Status
::newGood();
2233 // Only certain restrictions can cascade...
2234 $editrestriction = isset( $limit['edit'] )
2235 ?
[ $limit['edit'] ]
2236 : $this->mTitle
->getRestrictions( 'edit' );
2237 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2238 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2240 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2241 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2244 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2245 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2246 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2248 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2249 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2252 // The schema allows multiple restrictions
2253 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2257 // insert null revision to identify the page protection change as edit summary
2258 $latest = $this->getLatest();
2259 $nullRevision = $this->insertProtectNullRevision(
2268 if ( $nullRevision === null ) {
2269 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2272 $logRelationsField = 'pr_id';
2274 // Update restrictions table
2275 foreach ( $limit as $action => $restrictions ) {
2277 'page_restrictions',
2280 'pr_type' => $action
2284 if ( $restrictions != '' ) {
2285 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2287 'page_restrictions',
2290 'pr_type' => $action,
2291 'pr_level' => $restrictions,
2292 'pr_cascade' => $cascadeValue,
2293 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2297 $logRelationsValues[] = $dbw->insertId();
2298 $logParamsDetails[] = [
2300 'level' => $restrictions,
2301 'expiry' => $expiry[$action],
2302 'cascade' => (bool)$cascadeValue,
2307 // Clear out legacy restriction fields
2310 [ 'page_restrictions' => '' ],
2311 [ 'page_id' => $id ],
2315 // Avoid PHP 7.1 warning of passing $this by reference
2318 Hooks
::run( 'NewRevisionFromEditComplete',
2319 [ $this, $nullRevision, $latest, $user ] );
2320 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2321 } else { // Protection of non-existing page (also known as "title protection")
2322 // Cascade protection is meaningless in this case
2325 if ( $limit['create'] != '' ) {
2326 $commentFields = CommentStore
::getStore()->insert( $dbw, 'pt_reason', $reason );
2327 $dbw->replace( 'protected_titles',
2328 [ [ 'pt_namespace', 'pt_title' ] ],
2330 'pt_namespace' => $this->mTitle
->getNamespace(),
2331 'pt_title' => $this->mTitle
->getDBkey(),
2332 'pt_create_perm' => $limit['create'],
2333 'pt_timestamp' => $dbw->timestamp(),
2334 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2335 'pt_user' => $user->getId(),
2336 ] +
$commentFields, __METHOD__
2338 $logParamsDetails[] = [
2340 'level' => $limit['create'],
2341 'expiry' => $expiry['create'],
2344 $dbw->delete( 'protected_titles',
2346 'pt_namespace' => $this->mTitle
->getNamespace(),
2347 'pt_title' => $this->mTitle
->getDBkey()
2353 $this->mTitle
->flushRestrictions();
2354 InfoAction
::invalidateCache( $this->mTitle
);
2356 if ( $logAction == 'unprotect' ) {
2359 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2361 '4::description' => $protectDescriptionLog, // parameter for IRC
2362 '5:bool:cascade' => $cascade,
2363 'details' => $logParamsDetails, // parameter for localize and api
2367 // Update the protection log
2368 $logEntry = new ManualLogEntry( 'protect', $logAction );
2369 $logEntry->setTarget( $this->mTitle
);
2370 $logEntry->setComment( $reason );
2371 $logEntry->setPerformer( $user );
2372 $logEntry->setParameters( $params );
2373 if ( !is_null( $nullRevision ) ) {
2374 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2376 $logEntry->setTags( $tags );
2377 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2378 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2380 $logId = $logEntry->insert();
2381 $logEntry->publish( $logId );
2383 return Status
::newGood( $logId );
2387 * Insert a new null revision for this page.
2389 * @param string $revCommentMsg Comment message key for the revision
2390 * @param array $limit Set of restriction keys
2391 * @param array $expiry Per restriction type expiration
2392 * @param int $cascade Set to false if cascading protection isn't allowed.
2393 * @param string $reason
2394 * @param User|null $user
2395 * @return Revision|null Null on error
2397 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2398 array $expiry, $cascade, $reason, $user = null
2400 $dbw = wfGetDB( DB_MASTER
);
2402 // Prepare a null revision to be added to the history
2403 $editComment = wfMessage(
2405 $this->mTitle
->getPrefixedText(),
2406 $user ?
$user->getName() : ''
2407 )->inContentLanguage()->text();
2409 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2411 $protectDescription = $this->protectDescription( $limit, $expiry );
2412 if ( $protectDescription ) {
2413 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2414 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2415 ->inContentLanguage()->text();
2418 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2419 $editComment .= wfMessage( 'brackets' )->params(
2420 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2421 )->inContentLanguage()->text();
2424 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2426 $nullRev->insertOn( $dbw );
2428 // Update page record and touch page
2429 $oldLatest = $nullRev->getParentId();
2430 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2437 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2440 protected function formatExpiry( $expiry ) {
2441 if ( $expiry != 'infinity' ) {
2442 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2445 $contLang->timeanddate( $expiry, false, false ),
2446 $contLang->date( $expiry, false, false ),
2447 $contLang->time( $expiry, false, false )
2448 )->inContentLanguage()->text();
2450 return wfMessage( 'protect-expiry-indefinite' )
2451 ->inContentLanguage()->text();
2456 * Builds the description to serve as comment for the edit.
2458 * @param array $limit Set of restriction keys
2459 * @param array $expiry Per restriction type expiration
2462 public function protectDescription( array $limit, array $expiry ) {
2463 $protectDescription = '';
2465 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2466 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2467 # All possible message keys are listed here for easier grepping:
2468 # * restriction-create
2469 # * restriction-edit
2470 # * restriction-move
2471 # * restriction-upload
2472 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2473 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2474 # with '' filtered out. All possible message keys are listed below:
2475 # * protect-level-autoconfirmed
2476 # * protect-level-sysop
2477 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2478 ->inContentLanguage()->text();
2480 $expiryText = $this->formatExpiry( $expiry[$action] );
2482 if ( $protectDescription !== '' ) {
2483 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2485 $protectDescription .= wfMessage( 'protect-summary-desc' )
2486 ->params( $actionText, $restrictionsText, $expiryText )
2487 ->inContentLanguage()->text();
2490 return $protectDescription;
2494 * Builds the description to serve as comment for the log entry.
2496 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2497 * protect description text. Keep them in old format to avoid breaking compatibility.
2498 * TODO: Fix protection log to store structured description and format it on-the-fly.
2500 * @param array $limit Set of restriction keys
2501 * @param array $expiry Per restriction type expiration
2504 public function protectDescriptionLog( array $limit, array $expiry ) {
2505 $protectDescriptionLog = '';
2507 $dirMark = MediaWikiServices
::getInstance()->getContentLanguage()->getDirMark();
2508 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2509 $expiryText = $this->formatExpiry( $expiry[$action] );
2510 $protectDescriptionLog .=
2512 "[$action=$restrictions] ($expiryText)";
2515 return trim( $protectDescriptionLog );
2519 * Take an array of page restrictions and flatten it to a string
2520 * suitable for insertion into the page_restrictions field.
2522 * @param string[] $limit
2524 * @throws MWException
2527 protected static function flattenRestrictions( $limit ) {
2528 if ( !is_array( $limit ) ) {
2529 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2535 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2536 $bits[] = "$action=$restrictions";
2539 return implode( ':', $bits );
2543 * Determines if deletion of this page would be batched (executed over time by the job queue)
2544 * or not (completed in the same request as the delete call).
2546 * It is unlikely but possible that an edit from another request could push the page over the
2547 * batching threshold after this function is called, but before the caller acts upon the
2548 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2549 * is provided as an unreliable but situationally useful help for some common cases.
2551 * @param int $safetyMargin Added to the revision count when checking for batching
2552 * @return bool True if deletion would be batched, false otherwise
2554 public function isBatchedDelete( $safetyMargin = 0 ) {
2555 global $wgDeleteRevisionsBatchSize;
2557 $dbr = wfGetDB( DB_REPLICA
);
2558 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2559 $revCount +
= $safetyMargin;
2561 return $revCount >= $wgDeleteRevisionsBatchSize;
2565 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2566 * backwards compatibility, if you care about error reporting you should use
2567 * doDeleteArticleReal() instead.
2569 * Deletes the article with database consistency, writes logs, purges caches
2571 * @param string $reason Delete reason for deletion log
2572 * @param bool $suppress Suppress all revisions and log the deletion in
2573 * the suppression log instead of the deletion log
2574 * @param int|null $u1 Unused
2575 * @param bool|null $u2 Unused
2576 * @param array|string &$error Array of errors to append to
2577 * @param User|null $user The deleting user
2578 * @param bool $immediate false allows deleting over time via the job queue
2579 * @return bool True if successful
2580 * @throws FatalError
2581 * @throws MWException
2583 public function doDeleteArticle(
2584 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2587 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2588 [], 'delete', $immediate );
2590 // Returns true if the page was actually deleted, or is scheduled for deletion
2591 return $status->isOK();
2595 * Back-end article deletion
2596 * Deletes the article with database consistency, writes logs, purges caches
2600 * @param string $reason Delete reason for deletion log
2601 * @param bool $suppress Suppress all revisions and log the deletion in
2602 * the suppression log instead of the deletion log
2603 * @param int|null $u1 Unused
2604 * @param bool|null $u2 Unused
2605 * @param array|string &$error Array of errors to append to
2606 * @param User|null $deleter The deleting user
2607 * @param array $tags Tags to apply to the deletion action
2608 * @param string $logsubtype
2609 * @param bool $immediate false allows deleting over time via the job queue
2610 * @return Status Status object; if successful, $status->value is the log_id of the
2611 * deletion log entry. If the page couldn't be deleted because it wasn't
2612 * found, $status is a non-fatal 'cannotdelete' error
2613 * @throws FatalError
2614 * @throws MWException
2616 public function doDeleteArticleReal(
2617 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$deleter = null,
2618 $tags = [], $logsubtype = 'delete', $immediate = false
2622 wfDebug( __METHOD__
. "\n" );
2624 $status = Status
::newGood();
2626 // Avoid PHP 7.1 warning of passing $this by reference
2629 $deleter = is_null( $deleter ) ?
$wgUser : $deleter;
2630 if ( !Hooks
::run( 'ArticleDelete',
2631 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2633 if ( $status->isOK() ) {
2634 // Hook aborted but didn't set a fatal status
2635 $status->fatal( 'delete-hook-aborted' );
2640 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2641 $logsubtype, $immediate );
2645 * Back-end article deletion
2647 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2648 * Deletions can often be completed inline without involving the job queue.
2650 * Potentially called many times per deletion operation for pages with many revisions.
2652 public function doDeleteArticleBatched(
2653 $reason, $suppress, User
$deleter, $tags,
2654 $logsubtype, $immediate = false, $webRequestId = null
2656 wfDebug( __METHOD__
. "\n" );
2658 $status = Status
::newGood();
2660 $dbw = wfGetDB( DB_MASTER
);
2661 $dbw->startAtomic( __METHOD__
);
2663 $this->loadPageData( self
::READ_LATEST
);
2664 $id = $this->getId();
2665 // T98706: lock the page from various other updates but avoid using
2666 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2667 // the revisions queries (which also JOIN on user). Only lock the page
2668 // row and CAS check on page_latest to see if the trx snapshot matches.
2669 $lockedLatest = $this->lockAndGetLatest();
2670 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2671 $dbw->endAtomic( __METHOD__
);
2672 // Page not there or trx snapshot is stale
2673 $status->error( 'cannotdelete',
2674 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2678 // At this point we are now committed to returning an OK
2679 // status unless some DB query error or other exception comes up.
2680 // This way callers don't have to call rollback() if $status is bad
2681 // unless they actually try to catch exceptions (which is rare).
2683 // we need to remember the old content so we can use it to generate all deletion updates.
2684 $revision = $this->getRevision();
2686 $content = $this->getContent( Revision
::RAW
);
2687 } catch ( Exception
$ex ) {
2688 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2689 . $ex->getMessage() );
2694 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2695 // one batch of revisions and defer archival of any others to the job queue.
2696 $explictTrxLogged = false;
2698 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2699 if ( $done ||
!$immediate ) {
2702 $dbw->endAtomic( __METHOD__
);
2703 if ( $dbw->explicitTrxActive() ) {
2704 // Explict transactions may never happen here in practice. Log to be sure.
2705 if ( !$explictTrxLogged ) {
2706 $explictTrxLogged = true;
2707 LoggerFactory
::getInstance( 'wfDebug' )->debug(
2708 'explicit transaction active in ' . __METHOD__
. ' while deleting {title}', [
2709 'title' => $this->getTitle()->getText(),
2714 if ( $dbw->trxLevel() ) {
2717 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
2718 $lbFactory->waitForReplication();
2719 $dbw->startAtomic( __METHOD__
);
2722 // If done archiving, also delete the article.
2724 $dbw->endAtomic( __METHOD__
);
2727 'wikiPageId' => $id,
2728 'requestId' => $webRequestId ?? WebRequest
::getRequestId(),
2729 'reason' => $reason,
2730 'suppress' => $suppress,
2731 'userId' => $deleter->getId(),
2732 'tags' => json_encode( $tags ),
2733 'logsubtype' => $logsubtype,
2736 $job = new DeletePageJob( $this->getTitle(), $jobParams );
2737 JobQueueGroup
::singleton()->push( $job );
2739 $status->warning( 'delete-scheduled',
2740 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2742 // Get archivedRevisionCount by db query, because there's no better alternative.
2743 // Jobs cannot pass a count of archived revisions to the next job, because additional
2744 // deletion operations can be started while the first is running. Jobs from each
2745 // gracefully interleave, but would not know about each other's count. Deduplication
2746 // in the job queue to avoid simultaneous deletion operations would add overhead.
2747 // Number of archived revisions cannot be known beforehand, because edits can be made
2748 // while deletion operations are being processed, changing the number of archivals.
2749 $archivedRevisionCount = (int)$dbw->selectField(
2750 'archive', 'COUNT(*)',
2752 'ar_namespace' => $this->getTitle()->getNamespace(),
2753 'ar_title' => $this->getTitle()->getDBkey(),
2758 // Clone the title and wikiPage, so we have the information we need when
2759 // we log and run the ArticleDeleteComplete hook.
2760 $logTitle = clone $this->mTitle
;
2761 $wikiPageBeforeDelete = clone $this;
2763 // Now that it's safely backed up, delete it
2764 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2766 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2767 $logtype = $suppress ?
'suppress' : 'delete';
2769 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2770 $logEntry->setPerformer( $deleter );
2771 $logEntry->setTarget( $logTitle );
2772 $logEntry->setComment( $reason );
2773 $logEntry->setTags( $tags );
2774 $logid = $logEntry->insert();
2776 $dbw->onTransactionPreCommitOrIdle(
2777 function () use ( $logEntry, $logid ) {
2778 // T58776: avoid deadlocks (especially from FileDeleteForm)
2779 $logEntry->publish( $logid );
2784 $dbw->endAtomic( __METHOD__
);
2786 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2788 Hooks
::run( 'ArticleDeleteComplete', [
2789 &$wikiPageBeforeDelete,
2795 $archivedRevisionCount
2797 $status->value
= $logid;
2799 // Show log excerpt on 404 pages rather than just a link
2800 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2801 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2802 $cache->set( $key, 1, $cache::TTL_DAY
);
2809 * Archives revisions as part of page deletion.
2811 * @param IDatabase $dbw
2813 * @param bool $suppress Suppress all revisions and log the deletion in
2814 * the suppression log instead of the deletion log
2817 protected function archiveRevisions( $dbw, $id, $suppress ) {
2818 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2819 $wgActorTableSchemaMigrationStage, $wgDeleteRevisionsBatchSize;
2821 // Given the lock above, we can be confident in the title and page ID values
2822 $namespace = $this->getTitle()->getNamespace();
2823 $dbKey = $this->getTitle()->getDBkey();
2825 $commentStore = CommentStore
::getStore();
2826 $actorMigration = ActorMigration
::newMigration();
2828 $revQuery = Revision
::getQueryInfo();
2831 // Bitfields to further suppress the content
2833 $bitfield = Revision
::SUPPRESSED_ALL
;
2834 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2837 // For now, shunt the revision data into the archive table.
2838 // Text is *not* removed from the text table; bulk storage
2839 // is left intact to avoid breaking block-compression or
2840 // immutable storage schemes.
2841 // In the future, we may keep revisions and mark them with
2842 // the rev_deleted field, which is reserved for this purpose.
2844 // Lock rows in `revision` and its temp tables, but not any others.
2845 // Note array_intersect() preserves keys from the first arg, and we're
2846 // assuming $revQuery has `revision` primary and isn't using subtables
2847 // for anything we care about.
2848 $dbw->lockForUpdate(
2850 $revQuery['tables'],
2851 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2853 [ 'rev_page' => $id ],
2859 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2860 // so we can copy it to the archive table.
2861 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2862 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2863 $revQuery['fields'][] = 'rev_text_id';
2865 if ( $wgContentHandlerUseDB ) {
2866 $revQuery['fields'][] = 'rev_content_model';
2867 $revQuery['fields'][] = 'rev_content_format';
2871 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2872 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2873 $res = $dbw->select(
2874 $revQuery['tables'],
2875 $revQuery['fields'],
2876 [ 'rev_page' => $id ],
2878 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize +
1 ],
2882 // Build their equivalent archive rows
2886 /** @var int[] Revision IDs of edits that were made by IPs */
2890 foreach ( $res as $row ) {
2891 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2896 $comment = $commentStore->getComment( 'rev_comment', $row );
2897 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
2899 'ar_namespace' => $namespace,
2900 'ar_title' => $dbKey,
2901 'ar_timestamp' => $row->rev_timestamp
,
2902 'ar_minor_edit' => $row->rev_minor_edit
,
2903 'ar_rev_id' => $row->rev_id
,
2904 'ar_parent_id' => $row->rev_parent_id
,
2906 * ar_text_id should probably not be written to when the multi content schema has
2907 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2908 * default for the field in WMF production currently so we must keep writing
2909 * writing until a default of 0 is set.
2910 * Task: https://phabricator.wikimedia.org/T190148
2911 * Copying the value from the revision table should not lead to any issues for now.
2913 'ar_len' => $row->rev_len
,
2914 'ar_page_id' => $id,
2915 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2916 'ar_sha1' => $row->rev_sha1
,
2917 ] +
$commentStore->insert( $dbw, 'ar_comment', $comment )
2918 +
$actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2920 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2921 $rowInsert['ar_text_id'] = $row->rev_text_id
;
2923 if ( $wgContentHandlerUseDB ) {
2924 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2925 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2929 $rowsInsert[] = $rowInsert;
2930 $revids[] = $row->rev_id
;
2932 // Keep track of IP edits, so that the corresponding rows can
2933 // be deleted in the ip_changes table.
2934 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2935 $ipRevIds[] = $row->rev_id
;
2939 // This conditional is just a sanity check
2940 if ( count( $revids ) > 0 ) {
2941 // Copy them into the archive table
2942 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2944 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__
);
2945 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2946 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2947 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__
);
2950 // Also delete records from ip_changes as applicable.
2951 if ( count( $ipRevIds ) > 0 ) {
2952 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2960 * Lock the page row for this title+id and return page_latest (or 0)
2962 * @return int Returns 0 if no row was found with this title+id
2965 public function lockAndGetLatest() {
2966 return (int)wfGetDB( DB_MASTER
)->selectField(
2970 'page_id' => $this->getId(),
2971 // Typically page_id is enough, but some code might try to do
2972 // updates assuming the title is the same, so verify that
2973 'page_namespace' => $this->getTitle()->getNamespace(),
2974 'page_title' => $this->getTitle()->getDBkey()
2982 * Do some database updates after deletion
2984 * @param int $id The page_id value of the page being deleted
2985 * @param Content|null $content Page content to be used when determining
2986 * the required updates. This may be needed because $this->getContent()
2987 * may already return null when the page proper was deleted.
2988 * @param RevisionRecord|Revision|null $revision The current page revision at the time of
2989 * deletion, used when determining the required updates. This may be needed because
2990 * $this->getRevision() may already return null when the page proper was deleted.
2991 * @param User|null $user The user that caused the deletion
2993 public function doDeleteUpdates(
2994 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2996 if ( $id !== $this->getId() ) {
2997 throw new InvalidArgumentException( 'Mismatching page ID' );
3001 $countable = $this->isCountable();
3002 } catch ( Exception
$ex ) {
3003 // fallback for deleting broken pages for which we cannot load the content for
3004 // some reason. Note that doDeleteArticleReal() already logged this problem.
3008 // Update site status
3009 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory(
3010 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
3013 // Delete pagelinks, update secondary indexes, etc
3014 $updates = $this->getDeletionUpdates(
3015 $revision ?
$revision->getRevisionRecord() : $content
3017 foreach ( $updates as $update ) {
3018 DeferredUpdates
::addUpdate( $update );
3021 $causeAgent = $user ?
$user->getName() : 'unknown';
3022 // Reparse any pages transcluding this page
3023 LinksUpdate
::queueRecursiveJobsForTable(
3024 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3025 // Reparse any pages including this image
3026 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3027 LinksUpdate
::queueRecursiveJobsForTable(
3028 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3032 self
::onArticleDelete( $this->mTitle
);
3033 ResourceLoaderWikiModule
::invalidateModuleCache(
3037 WikiMap
::getCurrentWikiDbDomain()->getId()
3040 // Reset this object and the Title object
3041 $this->loadFromRow( false, self
::READ_LATEST
);
3044 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3048 * Roll back the most recent consecutive set of edits to a page
3049 * from the same user; fails if there are no eligible edits to
3050 * roll back to, e.g. user is the sole contributor. This function
3051 * performs permissions checks on $user, then calls commitRollback()
3052 * to do the dirty work
3054 * @todo Separate the business/permission stuff out from backend code
3055 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3057 * @param string $fromP Name of the user whose edits to rollback.
3058 * @param string $summary Custom summary. Set to default summary if empty.
3059 * @param string $token Rollback token.
3060 * @param bool $bot If true, mark all reverted edits as bot.
3062 * @param array &$resultDetails Array contains result-specific array of additional values
3063 * 'alreadyrolled' : 'current' (rev)
3064 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3066 * @param User $user The user performing the rollback
3067 * @param array|null $tags Change tags to apply to the rollback
3068 * Callers are responsible for permission checks
3069 * (with ChangeTags::canAddTagsAccompanyingChange)
3071 * @return array Array of errors, each error formatted as
3072 * array(messagekey, param1, param2, ...).
3073 * On success, the array is empty. This array can also be passed to
3074 * OutputPage::showPermissionsErrorPage().
3076 public function doRollback(
3077 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3079 $resultDetails = null;
3081 // Check permissions
3082 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3083 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3084 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3086 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3087 $errors[] = [ 'sessionfailure' ];
3090 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3091 $errors[] = [ 'actionthrottledtext' ];
3094 // If there were errors, bail out now
3095 if ( !empty( $errors ) ) {
3099 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3103 * Backend implementation of doRollback(), please refer there for parameter
3104 * and return value documentation
3106 * NOTE: This function does NOT check ANY permissions, it just commits the
3107 * rollback to the DB. Therefore, you should only call this function direct-
3108 * ly if you want to use custom permissions checks. If you don't, use
3109 * doRollback() instead.
3110 * @param string $fromP Name of the user whose edits to rollback.
3111 * @param string $summary Custom summary. Set to default summary if empty.
3112 * @param bool $bot If true, mark all reverted edits as bot.
3114 * @param array &$resultDetails Contains result-specific array of additional values
3115 * @param User $guser The user performing the rollback
3116 * @param array|null $tags Change tags to apply to the rollback
3117 * Callers are responsible for permission checks
3118 * (with ChangeTags::canAddTagsAccompanyingChange)
3120 * @return array An array of error messages, as returned by Status::getErrorsArray()
3122 public function commitRollback( $fromP, $summary, $bot,
3123 &$resultDetails, User
$guser, $tags = null
3125 global $wgUseRCPatrol;
3127 $dbw = wfGetDB( DB_MASTER
);
3129 if ( wfReadOnly() ) {
3130 return [ [ 'readonlytext' ] ];
3133 // Begin revision creation cycle by creating a PageUpdater.
3134 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3135 $updater = $this->newPageUpdater( $guser );
3136 $current = $updater->grabParentRevision();
3138 if ( is_null( $current ) ) {
3139 // Something wrong... no page?
3140 return [ [ 'notanarticle' ] ];
3143 $currentEditorForPublic = $current->getUser( RevisionRecord
::FOR_PUBLIC
);
3144 $legacyCurrent = new Revision( $current );
3145 $from = str_replace( '_', ' ', $fromP );
3147 // User name given should match up with the top revision.
3148 // If the revision's user is not visible, then $from should be empty.
3149 if ( $from !== ( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' ) ) {
3150 $resultDetails = [ 'current' => $legacyCurrent ];
3151 return [ [ 'alreadyrolled',
3152 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3153 htmlspecialchars( $fromP ),
3154 htmlspecialchars( $currentEditorForPublic ?
$currentEditorForPublic->getName() : '' )
3158 // Get the last edit not by this person...
3159 // Note: these may not be public values
3160 $actorWhere = ActorMigration
::newMigration()->getWhere(
3163 $current->getUser( RevisionRecord
::RAW
)
3166 $s = $dbw->selectRow(
3167 [ 'revision' ] +
$actorWhere['tables'],
3168 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3170 'rev_page' => $current->getPageId(),
3171 'NOT(' . $actorWhere['conds'] . ')',
3175 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3176 'ORDER BY' => 'rev_timestamp DESC'
3178 $actorWhere['joins']
3180 if ( $s === false ) {
3181 // No one else ever edited this page
3182 return [ [ 'cantrollback' ] ];
3183 } elseif ( $s->rev_deleted
& RevisionRecord
::DELETED_TEXT
3184 ||
$s->rev_deleted
& RevisionRecord
::DELETED_USER
3186 // Only admins can see this text
3187 return [ [ 'notvisiblerev' ] ];
3190 // Generate the edit summary if necessary
3191 $target = $this->getRevisionStore()->getRevisionById(
3193 RevisionStore
::READ_LATEST
3195 if ( empty( $summary ) ) {
3196 if ( !$currentEditorForPublic ) { // no public user name
3197 $summary = wfMessage( 'revertpage-nouser' );
3199 $summary = wfMessage( 'revertpage' );
3202 $legacyTarget = new Revision( $target );
3203 $targetEditorForPublic = $target->getUser( RevisionRecord
::FOR_PUBLIC
);
3205 // Allow the custom summary to use the same args as the default message
3206 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3208 $targetEditorForPublic ?
$targetEditorForPublic->getName() : null,
3209 $currentEditorForPublic ?
$currentEditorForPublic->getName() : null,
3211 $contLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3213 $contLang->timeanddate( $current->getTimestamp() )
3215 if ( $summary instanceof Message
) {
3216 $summary = $summary->params( $args )->inContentLanguage()->text();
3218 $summary = wfMsgReplaceArgs( $summary, $args );
3221 // Trim spaces on user supplied text
3222 $summary = trim( $summary );
3225 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3227 if ( $guser->isAllowed( 'minoredit' ) ) {
3228 $flags |
= EDIT_MINOR
;
3231 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3232 $flags |
= EDIT_FORCE_BOT
;
3235 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3236 $currentContent = $current->getContent( SlotRecord
::MAIN
);
3237 $targetContent = $target->getContent( SlotRecord
::MAIN
);
3238 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3240 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3241 $tags[] = 'mw-rollback';
3244 // Build rollback revision:
3245 // Restore old content
3246 // TODO: MCR: test this once we can store multiple slots
3247 foreach ( $target->getSlots()->getSlots() as $slot ) {
3248 $updater->inheritSlot( $slot );
3251 // Remove extra slots
3252 // TODO: MCR: test this once we can store multiple slots
3253 foreach ( $current->getSlotRoles() as $role ) {
3254 if ( !$target->hasSlot( $role ) ) {
3255 $updater->removeSlot( $role );
3259 $updater->setOriginalRevisionId( $target->getId() );
3260 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3261 $updater->addTags( $tags );
3263 // TODO: this logic should not be in the storage layer, it's here for compatibility
3264 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3265 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3266 if ( $wgUseRCPatrol && $this->getTitle()->userCan( 'autopatrol', $guser ) ) {
3267 $updater->setRcPatrolStatus( RecentChange
::PRC_AUTOPATROLLED
);
3270 // Actually store the rollback
3271 $rev = $updater->saveRevision(
3272 CommentStoreComment
::newUnsavedComment( $summary ),
3276 // Set patrolling and bot flag on the edits, which gets rollbacked.
3277 // This is done even on edit failure to have patrolling in that case (T64157).
3279 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3280 // Mark all reverted edits as bot
3284 if ( $wgUseRCPatrol ) {
3285 // Mark all reverted edits as patrolled
3286 $set['rc_patrolled'] = RecentChange
::PRC_AUTOPATROLLED
;
3289 if ( count( $set ) ) {
3290 $actorWhere = ActorMigration
::newMigration()->getWhere(
3293 $current->getUser( RevisionRecord
::RAW
),
3296 $dbw->update( 'recentchanges', $set,
3298 'rc_cur_id' => $current->getPageId(),
3299 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3300 $actorWhere['conds'], // No tables/joins are needed for rc_user
3306 if ( !$updater->wasSuccessful() ) {
3307 return $updater->getStatus()->getErrorsArray();
3310 // Report if the edit was not created because it did not change the content.
3311 if ( $updater->isUnchanged() ) {
3312 $resultDetails = [ 'current' => $legacyCurrent ];
3313 return [ [ 'alreadyrolled',
3314 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3315 htmlspecialchars( $fromP ),
3316 htmlspecialchars( $targetEditorForPublic ?
$targetEditorForPublic->getName() : '' )
3320 if ( $changingContentModel ) {
3321 // If the content model changed during the rollback,
3322 // make sure it gets logged to Special:Log/contentmodel
3323 $log = new ManualLogEntry( 'contentmodel', 'change' );
3324 $log->setPerformer( $guser );
3325 $log->setTarget( $this->mTitle
);
3326 $log->setComment( $summary );
3327 $log->setParameters( [
3328 '4::oldmodel' => $currentContent->getModel(),
3329 '5::newmodel' => $targetContent->getModel(),
3332 $logId = $log->insert( $dbw );
3333 $log->publish( $logId );
3336 $revId = $rev->getId();
3338 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3341 'summary' => $summary,
3342 'current' => $legacyCurrent,
3343 'target' => $legacyTarget,
3348 // TODO: make this return a Status object and wrap $resultDetails in that.
3353 * The onArticle*() functions are supposed to be a kind of hooks
3354 * which should be called whenever any of the specified actions
3357 * This is a good place to put code to clear caches, for instance.
3359 * This is called on page move and undelete, as well as edit
3361 * @param Title $title
3363 public static function onArticleCreate( Title
$title ) {
3364 // TODO: move this into a PageEventEmitter service
3366 // Update existence markers on article/talk tabs...
3367 $other = $title->getOtherPage();
3369 $other->purgeSquid();
3371 $title->touchLinks();
3372 $title->purgeSquid();
3373 $title->deleteTitleProtection();
3375 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3377 // Invalidate caches of articles which include this page
3378 DeferredUpdates
::addUpdate(
3379 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3382 if ( $title->getNamespace() == NS_CATEGORY
) {
3383 // Load the Category object, which will schedule a job to create
3384 // the category table row if necessary. Checking a replica DB is ok
3385 // here, in the worst case it'll run an unnecessary recount job on
3386 // a category that probably doesn't have many members.
3387 Category
::newFromTitle( $title )->getID();
3392 * Clears caches when article is deleted
3394 * @param Title $title
3396 public static function onArticleDelete( Title
$title ) {
3397 // TODO: move this into a PageEventEmitter service
3399 // Update existence markers on article/talk tabs...
3400 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3401 BacklinkCache
::get( $title )->clear();
3402 $other = $title->getOtherPage();
3404 $other->purgeSquid();
3406 $title->touchLinks();
3407 $title->purgeSquid();
3409 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3412 HTMLFileCache
::clearFileCache( $title );
3413 InfoAction
::invalidateCache( $title );
3416 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3417 MessageCache
::singleton()->updateMessageOverride( $title, null );
3421 if ( $title->getNamespace() == NS_FILE
) {
3422 DeferredUpdates
::addUpdate(
3423 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3428 if ( $title->getNamespace() == NS_USER_TALK
) {
3429 $user = User
::newFromName( $title->getText(), false );
3431 $user->setNewtalk( false );
3436 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3438 // Purge cross-wiki cache entities referencing this page
3439 self
::purgeInterwikiCheckKey( $title );
3443 * Purge caches on page update etc
3445 * @param Title $title
3446 * @param Revision|null $revision Revision that was just saved, may be null
3447 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3448 * If not given, all slots are assumed to have changed.
3450 public static function onArticleEdit(
3452 Revision
$revision = null,
3453 $slotsChanged = null
3455 // TODO: move this into a PageEventEmitter service
3457 if ( $slotsChanged === null ||
in_array( SlotRecord
::MAIN
, $slotsChanged ) ) {
3458 // Invalidate caches of articles which include this page.
3459 // Only for the main slot, because only the main slot is transcluded.
3460 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3461 DeferredUpdates
::addUpdate(
3462 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3466 // Invalidate the caches of all pages which redirect here
3467 DeferredUpdates
::addUpdate(
3468 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3471 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3473 // Purge CDN for this page only
3474 $title->purgeSquid();
3475 // Clear file cache for this page only
3476 HTMLFileCache
::clearFileCache( $title );
3478 // Purge ?action=info cache
3479 $revid = $revision ?
$revision->getId() : null;
3480 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3481 InfoAction
::invalidateCache( $title, $revid );
3484 // Purge cross-wiki cache entities referencing this page
3485 self
::purgeInterwikiCheckKey( $title );
3491 * Purge the check key for cross-wiki cache entries referencing this page
3493 * @param Title $title
3495 private static function purgeInterwikiCheckKey( Title
$title ) {
3496 global $wgEnableScaryTranscluding;
3498 if ( !$wgEnableScaryTranscluding ) {
3499 return; // @todo: perhaps this wiki is only used as a *source* for content?
3502 DeferredUpdates
::addCallableUpdate( function () use ( $title ) {
3503 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3504 $cache->resetCheckKey(
3505 // Do not include the namespace since there can be multiple aliases to it
3506 // due to different namespace text definitions on different wikis. This only
3507 // means that some cache invalidations happen that are not strictly needed.
3508 $cache->makeGlobalKey(
3510 WikiMap
::getCurrentWikiDbDomain()->getId(),
3518 * Returns a list of categories this page is a member of.
3519 * Results will include hidden categories
3521 * @return TitleArray
3523 public function getCategories() {
3524 $id = $this->getId();
3526 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3529 $dbr = wfGetDB( DB_REPLICA
);
3530 $res = $dbr->select( 'categorylinks',
3531 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3532 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3533 // as not being aliases, and NS_CATEGORY is numeric
3534 [ 'cl_from' => $id ],
3537 return TitleArray
::newFromResult( $res );
3541 * Returns a list of hidden categories this page is a member of.
3542 * Uses the page_props and categorylinks tables.
3544 * @return array Array of Title objects
3546 public function getHiddenCategories() {
3548 $id = $this->getId();
3554 $dbr = wfGetDB( DB_REPLICA
);
3555 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3557 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3558 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3561 if ( $res !== false ) {
3562 foreach ( $res as $row ) {
3563 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3571 * Auto-generates a deletion reason
3573 * @param bool &$hasHistory Whether the page has a history
3574 * @return string|bool String containing deletion reason or empty string, or boolean false
3575 * if no revision occurred
3577 public function getAutoDeleteReason( &$hasHistory ) {
3578 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3582 * Update all the appropriate counts in the category table, given that
3583 * we've added the categories $added and deleted the categories $deleted.
3585 * This should only be called from deferred updates or jobs to avoid contention.
3587 * @param array $added The names of categories that were added
3588 * @param array $deleted The names of categories that were deleted
3589 * @param int $id Page ID (this should be the original deleted page ID)
3591 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3592 $id = $id ?
: $this->getId();
3593 $type = MWNamespace
::getCategoryLinkType( $this->getTitle()->getNamespace() );
3595 $addFields = [ 'cat_pages = cat_pages + 1' ];
3596 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3597 if ( $type !== 'page' ) {
3598 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3599 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3602 $dbw = wfGetDB( DB_MASTER
);
3604 if ( count( $added ) ) {
3605 $existingAdded = $dbw->selectFieldValues(
3608 [ 'cat_title' => $added ],
3612 // For category rows that already exist, do a plain
3613 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3614 // to avoid creating gaps in the cat_id sequence.
3615 if ( count( $existingAdded ) ) {
3619 [ 'cat_title' => $existingAdded ],
3624 $missingAdded = array_diff( $added, $existingAdded );
3625 if ( count( $missingAdded ) ) {
3627 foreach ( $missingAdded as $cat ) {
3629 'cat_title' => $cat,
3631 'cat_subcats' => ( $type === 'subcat' ) ?
1 : 0,
3632 'cat_files' => ( $type === 'file' ) ?
1 : 0,
3645 if ( count( $deleted ) ) {
3649 [ 'cat_title' => $deleted ],
3654 foreach ( $added as $catName ) {
3655 $cat = Category
::newFromName( $catName );
3656 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3659 foreach ( $deleted as $catName ) {
3660 $cat = Category
::newFromName( $catName );
3661 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3662 // Refresh counts on categories that should be empty now (after commit, T166757)
3663 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3664 $cat->refreshCountsIfEmpty();
3670 * Opportunistically enqueue link update jobs given fresh parser output if useful
3672 * @param ParserOutput $parserOutput Current version page output
3675 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3676 if ( wfReadOnly() ) {
3680 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3681 [ $this, $this->mTitle
, $parserOutput ]
3686 $config = RequestContext
::getMain()->getConfig();
3689 'isOpportunistic' => true,
3690 'rootJobTimestamp' => $parserOutput->getCacheTime()
3693 if ( $this->mTitle
->areRestrictionsCascading() ) {
3694 // If the page is cascade protecting, the links should really be up-to-date
3695 JobQueueGroup
::singleton()->lazyPush(
3696 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3698 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3699 // Assume the output contains "dynamic" time/random based magic words.
3700 // Only update pages that expired due to dynamic content and NOT due to edits
3701 // to referenced templates/files. When the cache expires due to dynamic content,
3702 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3703 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3704 // template/file edit already triggered recursive RefreshLinksJob jobs.
3705 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3706 // If a page is uncacheable, do not keep spamming a job for it.
3707 // Although it would be de-duplicated, it would still waste I/O.
3708 $cache = ObjectCache
::getLocalClusterInstance();
3709 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3710 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3711 if ( $cache->add( $key, time(), $ttl ) ) {
3712 JobQueueGroup
::singleton()->lazyPush(
3713 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3721 * Returns a list of updates to be performed when this page is deleted. The
3722 * updates should remove any information about this page from secondary data
3723 * stores such as links tables.
3725 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3726 * object for backwards compatibility.
3727 * @return DeferrableUpdate[]
3729 public function getDeletionUpdates( $rev = null ) {
3731 wfDeprecated( __METHOD__
. ' without a RevisionRecord', '1.32' );
3734 $rev = $this->getRevisionRecord();
3735 } catch ( Exception
$ex ) {
3736 // If we can't load the content, something is wrong. Perhaps that's why
3737 // the user is trying to delete the page, so let's not fail in that case.
3738 // Note that doDeleteArticleReal() will already have logged an issue with
3739 // loading the content.
3740 wfDebug( __METHOD__
. ' failed to load current revision of page ' . $this->getId() );
3746 } elseif ( $rev instanceof Content
) {
3747 wfDeprecated( __METHOD__
. ' with a Content object instead of a RevisionRecord', '1.32' );
3749 $slotContent = [ SlotRecord
::MAIN
=> $rev ];
3751 $slotContent = array_map( function ( SlotRecord
$slot ) {
3752 return $slot->getContent( Revision
::RAW
);
3753 }, $rev->getSlots()->getSlots() );
3756 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3758 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3759 // model here, not the content object!
3760 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3761 /** @var Content $content */
3762 foreach ( $slotContent as $role => $content ) {
3763 $handler = $content->getContentHandler();
3765 $updates = $handler->getDeletionUpdates(
3769 $allUpdates = array_merge( $allUpdates, $updates );
3771 // TODO: remove B/C hack in 1.32!
3772 $legacyUpdates = $content->getDeletionUpdates( $this );
3774 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3775 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3776 return !( $update instanceof LinksDeletionUpdate
);
3779 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3782 Hooks
::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3784 // TODO: hard deprecate old hook in 1.33
3785 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3790 * Whether this content displayed on this page
3791 * comes from the local database
3796 public function isLocal() {
3801 * The display name for the site this content
3802 * come from. If a subclass overrides isLocal(),
3803 * this could return something other than the
3809 public function getWikiDisplayName() {
3815 * Get the source URL for the content on this page,
3816 * typically the canonical URL, but may be a remote
3817 * link if the content comes from another site
3822 public function getSourceURL() {
3823 return $this->getTitle()->getCanonicalURL();
3827 * @param WANObjectCache $cache
3831 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3832 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3834 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );