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 Wikimedia\Assert\Assert
;
27 use Wikimedia\Rdbms\FakeResultWrapper
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use Wikimedia\Rdbms\DBError
;
30 use Wikimedia\Rdbms\DBUnexpectedError
;
33 * Class representing a MediaWiki article and history.
35 * Some fields are public only for backwards-compatibility. Use accessors.
36 * In the past, this class was part of Article.php and everything was public.
38 class WikiPage
implements Page
, IDBAccessObject
{
39 // Constants for $mDataLoadedFrom and related
44 public $mTitle = null;
49 public $mDataLoaded = false; // !< Boolean
50 public $mIsRedirect = false; // !< Boolean
51 public $mLatest = false; // !< Integer (false means "not loaded")
54 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
55 public $mPreparedEdit = false;
60 protected $mId = null;
63 * @var int One of the READ_* constants
65 protected $mDataLoadedFrom = self
::READ_NONE
;
70 protected $mRedirectTarget = null;
75 protected $mLastRevision = null;
78 * @var string Timestamp of the current revision or empty string if not loaded
80 protected $mTimestamp = '';
85 protected $mTouched = '19700101000000';
90 protected $mLinksUpdated = '19700101000000';
93 * Constructor and clear the article
94 * @param Title $title Reference to a Title object.
96 public function __construct( Title
$title ) {
97 $this->mTitle
= $title;
101 * Makes sure that the mTitle object is cloned
102 * to the newly cloned WikiPage.
104 public function __clone() {
105 $this->mTitle
= clone $this->mTitle
;
109 * Create a WikiPage object of the appropriate class for the given title.
111 * @param Title $title
113 * @throws MWException
114 * @return WikiPage|WikiCategoryPage|WikiFilePage
116 public static function factory( Title
$title ) {
117 $ns = $title->getNamespace();
119 if ( $ns == NS_MEDIA
) {
120 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
121 } elseif ( $ns < 0 ) {
122 throw new MWException( "Invalid or virtual namespace $ns given." );
126 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
132 $page = new WikiFilePage( $title );
135 $page = new WikiCategoryPage( $title );
138 $page = new WikiPage( $title );
145 * Constructor from a page id
147 * @param int $id Article ID to load
148 * @param string|int $from One of the following values:
149 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
150 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
152 * @return WikiPage|null
154 public static function newFromID( $id, $from = 'fromdb' ) {
155 // page ids are never 0 or negative, see T63166
160 $from = self
::convertSelectType( $from );
161 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
162 $pageQuery = self
::getQueryInfo();
163 $row = $db->selectRow(
164 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__
,
165 [], $pageQuery['joins']
170 return self
::newFromRow( $row, $from );
174 * Constructor from a database row
177 * @param object $row Database row containing at least fields returned by selectFields().
178 * @param string|int $from Source of $data:
179 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
180 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
181 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
184 public static function newFromRow( $row, $from = 'fromdb' ) {
185 $page = self
::factory( Title
::newFromRow( $row ) );
186 $page->loadFromRow( $row, $from );
191 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
193 * @param object|string|int $type
196 private static function convertSelectType( $type ) {
199 return self
::READ_NORMAL
;
201 return self
::READ_LATEST
;
203 return self
::READ_LOCKING
;
205 // It may already be an integer or whatever else
211 * @todo Move this UI stuff somewhere else
213 * @see ContentHandler::getActionOverrides
216 public function getActionOverrides() {
217 return $this->getContentHandler()->getActionOverrides();
221 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
223 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
225 * @return ContentHandler
229 public function getContentHandler() {
230 return ContentHandler
::getForModelID( $this->getContentModel() );
234 * Get the title object of the article
235 * @return Title Title object of this page
237 public function getTitle() {
238 return $this->mTitle
;
245 public function clear() {
246 $this->mDataLoaded
= false;
247 $this->mDataLoadedFrom
= self
::READ_NONE
;
249 $this->clearCacheFields();
253 * Clear the object cache fields
256 protected function clearCacheFields() {
258 $this->mRedirectTarget
= null; // Title object if set
259 $this->mLastRevision
= null; // Latest revision
260 $this->mTouched
= '19700101000000';
261 $this->mLinksUpdated
= '19700101000000';
262 $this->mTimestamp
= '';
263 $this->mIsRedirect
= false;
264 $this->mLatest
= false;
265 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
266 // the requested rev ID and content against the cached one for equality. For most
267 // content types, the output should not change during the lifetime of this cache.
268 // Clearing it can cause extra parses on edit for no reason.
272 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
276 public function clearPreparedEdit() {
277 $this->mPreparedEdit
= false;
281 * Return the list of revision fields that should be selected to create
284 * @deprecated since 1.31, use self::getQueryInfo() instead.
287 public static function selectFields() {
288 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
290 wfDeprecated( __METHOD__
, '1.31' );
301 'page_links_updated',
306 if ( $wgContentHandlerUseDB ) {
307 $fields[] = 'page_content_model';
310 if ( $wgPageLanguageUseDB ) {
311 $fields[] = 'page_lang';
318 * Return the tables, fields, and join conditions to be selected to create
321 * @return array With three keys:
322 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
323 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
324 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
326 public static function getQueryInfo() {
327 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
330 'tables' => [ 'page' ],
340 'page_links_updated',
347 if ( $wgContentHandlerUseDB ) {
348 $ret['fields'][] = 'page_content_model';
351 if ( $wgPageLanguageUseDB ) {
352 $ret['fields'][] = 'page_lang';
359 * Fetch a page record with the given conditions
360 * @param IDatabase $dbr
361 * @param array $conditions
362 * @param array $options
363 * @return object|bool Database result resource, or false on failure
365 protected function pageData( $dbr, $conditions, $options = [] ) {
366 $pageQuery = self
::getQueryInfo();
368 // Avoid PHP 7.1 warning of passing $this by reference
371 Hooks
::run( 'ArticlePageDataBefore', [
372 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
375 $row = $dbr->selectRow(
376 $pageQuery['tables'],
377 $pageQuery['fields'],
384 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
390 * Fetch a page record matching the Title object's namespace and title
391 * using a sanitized title string
393 * @param IDatabase $dbr
394 * @param Title $title
395 * @param array $options
396 * @return object|bool Database result resource, or false on failure
398 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
399 return $this->pageData( $dbr, [
400 'page_namespace' => $title->getNamespace(),
401 'page_title' => $title->getDBkey() ], $options );
405 * Fetch a page record matching the requested ID
407 * @param IDatabase $dbr
409 * @param array $options
410 * @return object|bool Database result resource, or false on failure
412 public function pageDataFromId( $dbr, $id, $options = [] ) {
413 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
417 * Load the object from a given source by title
419 * @param object|string|int $from One of the following:
420 * - A DB query result object.
421 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
422 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
423 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
424 * using SELECT FOR UPDATE.
428 public function loadPageData( $from = 'fromdb' ) {
429 $from = self
::convertSelectType( $from );
430 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
431 // We already have the data from the correct location, no need to load it twice.
435 if ( is_int( $from ) ) {
436 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
437 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
438 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
441 && $index == DB_REPLICA
442 && $loadBalancer->getServerCount() > 1
443 && $loadBalancer->hasOrMadeRecentMasterChanges()
445 $from = self
::READ_LATEST
;
446 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
447 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
450 // No idea from where the caller got this data, assume replica DB.
452 $from = self
::READ_NORMAL
;
455 $this->loadFromRow( $data, $from );
459 * Load the object from a database row
462 * @param object|bool $data DB row containing fields returned by selectFields() or false
463 * @param string|int $from One of the following:
464 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
465 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
466 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
467 * the master DB using SELECT FOR UPDATE
469 public function loadFromRow( $data, $from ) {
470 $lc = LinkCache
::singleton();
471 $lc->clearLink( $this->mTitle
);
474 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
476 $this->mTitle
->loadFromRow( $data );
478 // Old-fashioned restrictions
479 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
481 $this->mId
= intval( $data->page_id
);
482 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
483 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
484 $this->mIsRedirect
= intval( $data->page_is_redirect
);
485 $this->mLatest
= intval( $data->page_latest
);
486 // T39225: $latest may no longer match the cached latest Revision object.
487 // Double-check the ID of any cached latest Revision object for consistency.
488 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
489 $this->mLastRevision
= null;
490 $this->mTimestamp
= '';
493 $lc->addBadLinkObj( $this->mTitle
);
495 $this->mTitle
->loadFromRow( false );
497 $this->clearCacheFields();
502 $this->mDataLoaded
= true;
503 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
507 * @return int Page ID
509 public function getId() {
510 if ( !$this->mDataLoaded
) {
511 $this->loadPageData();
517 * @return bool Whether or not the page exists in the database
519 public function exists() {
520 if ( !$this->mDataLoaded
) {
521 $this->loadPageData();
523 return $this->mId
> 0;
527 * Check if this page is something we're going to be showing
528 * some sort of sensible content for. If we return false, page
529 * views (plain action=view) will return an HTTP 404 response,
530 * so spiders and robots can know they're following a bad link.
534 public function hasViewableContent() {
535 return $this->mTitle
->isKnown();
539 * Tests if the article content represents a redirect
543 public function isRedirect() {
544 if ( !$this->mDataLoaded
) {
545 $this->loadPageData();
548 return (bool)$this->mIsRedirect
;
552 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
554 * Will use the revisions actual content model if the page exists,
555 * and the page's default if the page doesn't exist yet.
561 public function getContentModel() {
562 if ( $this->exists() ) {
563 $cache = ObjectCache
::getMainWANInstance();
565 return $cache->getWithSetCallback(
566 $cache->makeKey( 'page-content-model', $this->getLatest() ),
569 $rev = $this->getRevision();
571 // Look at the revision's actual content model
572 return $rev->getContentModel();
574 $title = $this->mTitle
->getPrefixedDBkey();
575 wfWarn( "Page $title exists but has no (visible) revisions!" );
576 return $this->mTitle
->getContentModel();
582 // use the default model for this page
583 return $this->mTitle
->getContentModel();
587 * Loads page_touched and returns a value indicating if it should be used
588 * @return bool True if this page exists and is not a redirect
590 public function checkTouched() {
591 if ( !$this->mDataLoaded
) {
592 $this->loadPageData();
594 return ( $this->mId
&& !$this->mIsRedirect
);
598 * Get the page_touched field
599 * @return string Containing GMT timestamp
601 public function getTouched() {
602 if ( !$this->mDataLoaded
) {
603 $this->loadPageData();
605 return $this->mTouched
;
609 * Get the page_links_updated field
610 * @return string|null Containing GMT timestamp
612 public function getLinksTimestamp() {
613 if ( !$this->mDataLoaded
) {
614 $this->loadPageData();
616 return $this->mLinksUpdated
;
620 * Get the page_latest field
621 * @return int The rev_id of current revision
623 public function getLatest() {
624 if ( !$this->mDataLoaded
) {
625 $this->loadPageData();
627 return (int)$this->mLatest
;
631 * Get the Revision object of the oldest revision
632 * @return Revision|null
634 public function getOldestRevision() {
635 // Try using the replica DB first, then try the master
636 $rev = $this->mTitle
->getFirstRevision();
638 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
644 * Loads everything except the text
645 * This isn't necessary for all uses, so it's only done if needed.
647 protected function loadLastEdit() {
648 if ( $this->mLastRevision
!== null ) {
649 return; // already loaded
652 $latest = $this->getLatest();
654 return; // page doesn't exist or is missing page_latest info
657 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
658 // T39225: if session S1 loads the page row FOR UPDATE, the result always
659 // includes the latest changes committed. This is true even within REPEATABLE-READ
660 // transactions, where S1 normally only sees changes committed before the first S1
661 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
662 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
663 // happened after the first S1 SELECT.
664 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
665 $flags = Revision
::READ_LOCKING
;
666 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
667 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
668 // Bug T93976: if page_latest was loaded from the master, fetch the
669 // revision from there as well, as it may not exist yet on a replica DB.
670 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
671 $flags = Revision
::READ_LATEST
;
672 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
674 $dbr = wfGetDB( DB_REPLICA
);
675 $revision = Revision
::newKnownCurrent( $dbr, $this->getTitle(), $latest );
678 if ( $revision ) { // sanity
679 $this->setLastEdit( $revision );
684 * Set the latest revision
685 * @param Revision $revision
687 protected function setLastEdit( Revision
$revision ) {
688 $this->mLastRevision
= $revision;
689 $this->mTimestamp
= $revision->getTimestamp();
693 * Get the latest revision
694 * @return Revision|null
696 public function getRevision() {
697 $this->loadLastEdit();
698 if ( $this->mLastRevision
) {
699 return $this->mLastRevision
;
705 * Get the content of the current revision. No side-effects...
707 * @param int $audience One of:
708 * Revision::FOR_PUBLIC to be displayed to all users
709 * Revision::FOR_THIS_USER to be displayed to $wgUser
710 * Revision::RAW get the text regardless of permissions
711 * @param User $user User object to check for, only if FOR_THIS_USER is passed
712 * to the $audience parameter
713 * @return Content|null The content of the current revision
717 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
718 $this->loadLastEdit();
719 if ( $this->mLastRevision
) {
720 return $this->mLastRevision
->getContent( $audience, $user );
726 * @return string MW timestamp of last article revision
728 public function getTimestamp() {
729 // Check if the field has been filled by WikiPage::setTimestamp()
730 if ( !$this->mTimestamp
) {
731 $this->loadLastEdit();
734 return wfTimestamp( TS_MW
, $this->mTimestamp
);
738 * Set the page timestamp (use only to avoid DB queries)
739 * @param string $ts MW timestamp of last article revision
742 public function setTimestamp( $ts ) {
743 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
747 * @param int $audience One of:
748 * Revision::FOR_PUBLIC to be displayed to all users
749 * Revision::FOR_THIS_USER to be displayed to the given user
750 * Revision::RAW get the text regardless of permissions
751 * @param User $user User object to check for, only if FOR_THIS_USER is passed
752 * to the $audience parameter
753 * @return int User ID for the user that made the last article revision
755 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
756 $this->loadLastEdit();
757 if ( $this->mLastRevision
) {
758 return $this->mLastRevision
->getUser( $audience, $user );
765 * Get the User object of the user who created the page
766 * @param int $audience One of:
767 * Revision::FOR_PUBLIC to be displayed to all users
768 * Revision::FOR_THIS_USER to be displayed to the given user
769 * Revision::RAW get the text regardless of permissions
770 * @param User $user User object to check for, only if FOR_THIS_USER is passed
771 * to the $audience parameter
774 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
775 $revision = $this->getOldestRevision();
777 $userName = $revision->getUserText( $audience, $user );
778 return User
::newFromName( $userName, false );
785 * @param int $audience One of:
786 * Revision::FOR_PUBLIC to be displayed to all users
787 * Revision::FOR_THIS_USER to be displayed to the given user
788 * Revision::RAW get the text regardless of permissions
789 * @param User $user User object to check for, only if FOR_THIS_USER is passed
790 * to the $audience parameter
791 * @return string Username of the user that made the last article revision
793 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
794 $this->loadLastEdit();
795 if ( $this->mLastRevision
) {
796 return $this->mLastRevision
->getUserText( $audience, $user );
803 * @param int $audience One of:
804 * Revision::FOR_PUBLIC to be displayed to all users
805 * Revision::FOR_THIS_USER to be displayed to the given user
806 * Revision::RAW get the text regardless of permissions
807 * @param User $user User object to check for, only if FOR_THIS_USER is passed
808 * to the $audience parameter
809 * @return string Comment stored for the last article revision
811 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
812 $this->loadLastEdit();
813 if ( $this->mLastRevision
) {
814 return $this->mLastRevision
->getComment( $audience, $user );
821 * Returns true if last revision was marked as "minor edit"
823 * @return bool Minor edit indicator for the last article revision.
825 public function getMinorEdit() {
826 $this->loadLastEdit();
827 if ( $this->mLastRevision
) {
828 return $this->mLastRevision
->isMinor();
835 * Determine whether a page would be suitable for being counted as an
836 * article in the site_stats table based on the title & its content
838 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
839 * if false, the current database state will be used
842 public function isCountable( $editInfo = false ) {
843 global $wgArticleCountMethod;
845 if ( !$this->mTitle
->isContentPage() ) {
850 $content = $editInfo->pstContent
;
852 $content = $this->getContent();
855 if ( !$content ||
$content->isRedirect() ) {
861 if ( $wgArticleCountMethod === 'link' ) {
862 // nasty special case to avoid re-parsing to detect links
865 // ParserOutput::getLinks() is a 2D array of page links, so
866 // to be really correct we would need to recurse in the array
867 // but the main array should only have items in it if there are
869 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
871 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
872 [ 'pl_from' => $this->getId() ], __METHOD__
);
876 return $content->isCountable( $hasLinks );
880 * If this page is a redirect, get its target
882 * The target will be fetched from the redirect table if possible.
883 * If this page doesn't have an entry there, call insertRedirect()
884 * @return Title|null Title object, or null if this page is not a redirect
886 public function getRedirectTarget() {
887 if ( !$this->mTitle
->isRedirect() ) {
891 if ( $this->mRedirectTarget
!== null ) {
892 return $this->mRedirectTarget
;
895 // Query the redirect table
896 $dbr = wfGetDB( DB_REPLICA
);
897 $row = $dbr->selectRow( 'redirect',
898 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
899 [ 'rd_from' => $this->getId() ],
903 // rd_fragment and rd_interwiki were added later, populate them if empty
904 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
905 $this->mRedirectTarget
= Title
::makeTitle(
906 $row->rd_namespace
, $row->rd_title
,
907 $row->rd_fragment
, $row->rd_interwiki
909 return $this->mRedirectTarget
;
912 // This page doesn't have an entry in the redirect table
913 $this->mRedirectTarget
= $this->insertRedirect();
914 return $this->mRedirectTarget
;
918 * Insert an entry for this page into the redirect table if the content is a redirect
920 * The database update will be deferred via DeferredUpdates
922 * Don't call this function directly unless you know what you're doing.
923 * @return Title|null Title object or null if not a redirect
925 public function insertRedirect() {
926 $content = $this->getContent();
927 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
932 // Update the DB post-send if the page has not cached since now
933 $latest = $this->getLatest();
934 DeferredUpdates
::addCallableUpdate(
935 function () use ( $retval, $latest ) {
936 $this->insertRedirectEntry( $retval, $latest );
938 DeferredUpdates
::POSTSEND
,
946 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
947 * @param Title $rt Redirect target
948 * @param int|null $oldLatest Prior page_latest for check and set
950 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
951 $dbw = wfGetDB( DB_MASTER
);
952 $dbw->startAtomic( __METHOD__
);
954 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
958 'rd_from' => $this->getId(),
959 'rd_namespace' => $rt->getNamespace(),
960 'rd_title' => $rt->getDBkey(),
961 'rd_fragment' => $rt->getFragment(),
962 'rd_interwiki' => $rt->getInterwiki(),
966 'rd_namespace' => $rt->getNamespace(),
967 'rd_title' => $rt->getDBkey(),
968 'rd_fragment' => $rt->getFragment(),
969 'rd_interwiki' => $rt->getInterwiki(),
975 $dbw->endAtomic( __METHOD__
);
979 * Get the Title object or URL this page redirects to
981 * @return bool|Title|string False, Title of in-wiki target, or string with URL
983 public function followRedirect() {
984 return $this->getRedirectURL( $this->getRedirectTarget() );
988 * Get the Title object or URL to use for a redirect. We use Title
989 * objects for same-wiki, non-special redirects and URLs for everything
991 * @param Title $rt Redirect target
992 * @return bool|Title|string False, Title object of local target, or string with URL
994 public function getRedirectURL( $rt ) {
999 if ( $rt->isExternal() ) {
1000 if ( $rt->isLocal() ) {
1001 // Offsite wikis need an HTTP redirect.
1002 // This can be hard to reverse and may produce loops,
1003 // so they may be disabled in the site configuration.
1004 $source = $this->mTitle
->getFullURL( 'redirect=no' );
1005 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1007 // External pages without "local" bit set are not valid
1013 if ( $rt->isSpecialPage() ) {
1014 // Gotta handle redirects to special pages differently:
1015 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1016 // Some pages are not valid targets.
1017 if ( $rt->isValidRedirectTarget() ) {
1018 return $rt->getFullURL();
1028 * Get a list of users who have edited this article, not including the user who made
1029 * the most recent revision, which you can get from $article->getUser() if you want it
1030 * @return UserArrayFromResult
1032 public function getContributors() {
1033 // @todo FIXME: This is expensive; cache this info somewhere.
1035 $dbr = wfGetDB( DB_REPLICA
);
1037 $tables = [ 'revision', 'user' ];
1040 'user_id' => 'rev_user',
1041 'user_name' => 'rev_user_text',
1042 'user_real_name' => 'MIN(user_real_name)',
1043 'timestamp' => 'MAX(rev_timestamp)',
1046 $conds = [ 'rev_page' => $this->getId() ];
1048 // The user who made the top revision gets credited as "this page was last edited by
1049 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1050 $user = $this->getUser();
1052 $conds[] = "rev_user != $user";
1054 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1058 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1061 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1065 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1066 'ORDER BY' => 'timestamp DESC',
1069 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1070 return new UserArrayFromResult( $res );
1074 * Should the parser cache be used?
1076 * @param ParserOptions $parserOptions ParserOptions to check
1080 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1081 return $parserOptions->getStubThreshold() == 0
1083 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1084 && $this->getContentHandler()->isParserCacheSupported();
1088 * Get a ParserOutput for the given ParserOptions and revision ID.
1090 * The parser cache will be used if possible. Cache misses that result
1091 * in parser runs are debounced with PoolCounter.
1094 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1095 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1096 * get the current revision (default value)
1097 * @param bool $forceParse Force reindexing, regardless of cache settings
1098 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1100 public function getParserOutput(
1101 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1104 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1106 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1107 throw new InvalidArgumentException(
1108 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1112 wfDebug( __METHOD__
.
1113 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1114 if ( $parserOptions->getStubThreshold() ) {
1115 wfIncrStats( 'pcache.miss.stub' );
1118 if ( $useParserCache ) {
1119 $parserOutput = MediaWikiServices
::getInstance()->getParserCache()
1120 ->get( $this, $parserOptions );
1121 if ( $parserOutput !== false ) {
1122 return $parserOutput;
1126 if ( $oldid === null ||
$oldid === 0 ) {
1127 $oldid = $this->getLatest();
1130 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1133 return $pool->getParserOutput();
1137 * Do standard deferred updates after page view (existing or missing page)
1138 * @param User $user The relevant user
1139 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1141 public function doViewUpdates( User
$user, $oldid = 0 ) {
1142 if ( wfReadOnly() ) {
1146 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1147 // Update newtalk / watchlist notification status
1149 $user->clearNotification( $this->mTitle
, $oldid );
1150 } catch ( DBError
$e ) {
1151 // Avoid outage if the master is not reachable
1152 MWExceptionHandler
::logException( $e );
1157 * Perform the actions of a page purging
1159 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1160 * controlled how much purging was done.
1162 public function doPurge() {
1163 // Avoid PHP 7.1 warning of passing $this by reference
1166 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1170 $this->mTitle
->invalidateCache();
1173 HTMLFileCache
::clearFileCache( $this->getTitle() );
1174 // Send purge after above page_touched update was committed
1175 DeferredUpdates
::addUpdate(
1176 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1177 DeferredUpdates
::PRESEND
1180 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1181 $messageCache = MessageCache
::singleton();
1182 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1189 * Insert a new empty page record for this article.
1190 * This *must* be followed up by creating a revision
1191 * and running $this->updateRevisionOn( ... );
1192 * or else the record will be left in a funky state.
1193 * Best if all done inside a transaction.
1195 * @param IDatabase $dbw
1196 * @param int|null $pageId Custom page ID that will be used for the insert statement
1198 * @return bool|int The newly created page_id key; false if the row was not
1199 * inserted, e.g. because the title already existed or because the specified
1200 * page ID is already in use.
1202 public function insertOn( $dbw, $pageId = null ) {
1203 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1207 'page_namespace' => $this->mTitle
->getNamespace(),
1208 'page_title' => $this->mTitle
->getDBkey(),
1209 'page_restrictions' => '',
1210 'page_is_redirect' => 0, // Will set this shortly...
1212 'page_random' => wfRandom(),
1213 'page_touched' => $dbw->timestamp(),
1214 'page_latest' => 0, // Fill this in shortly...
1215 'page_len' => 0, // Fill this in shortly...
1216 ] +
$pageIdForInsert,
1221 if ( $dbw->affectedRows() > 0 ) {
1222 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1223 $this->mId
= $newid;
1224 $this->mTitle
->resetArticleID( $newid );
1228 return false; // nothing changed
1233 * Update the page record to point to a newly saved revision.
1235 * @param IDatabase $dbw
1236 * @param Revision $revision For ID number, and text used to set
1237 * length and redirect status fields
1238 * @param int $lastRevision If given, will not overwrite the page field
1239 * when different from the currently set value.
1240 * Giving 0 indicates the new page flag should be set on.
1241 * @param bool $lastRevIsRedirect If given, will optimize adding and
1242 * removing rows in redirect table.
1243 * @return bool Success; false if the page row was missing or page_latest changed
1245 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1246 $lastRevIsRedirect = null
1248 global $wgContentHandlerUseDB;
1250 // Assertion to try to catch T92046
1251 if ( (int)$revision->getId() === 0 ) {
1252 throw new InvalidArgumentException(
1253 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1257 $content = $revision->getContent();
1258 $len = $content ?
$content->getSize() : 0;
1259 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1261 $conditions = [ 'page_id' => $this->getId() ];
1263 if ( !is_null( $lastRevision ) ) {
1264 // An extra check against threads stepping on each other
1265 $conditions['page_latest'] = $lastRevision;
1268 $revId = $revision->getId();
1269 Assert
::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1272 'page_latest' => $revId,
1273 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1274 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1275 'page_is_redirect' => $rt !== null ?
1 : 0,
1279 if ( $wgContentHandlerUseDB ) {
1280 $row['page_content_model'] = $revision->getContentModel();
1283 $dbw->update( 'page',
1288 $result = $dbw->affectedRows() > 0;
1290 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1291 $this->setLastEdit( $revision );
1292 $this->mLatest
= $revision->getId();
1293 $this->mIsRedirect
= (bool)$rt;
1294 // Update the LinkCache.
1295 LinkCache
::singleton()->addGoodLinkObj(
1301 $revision->getContentModel()
1309 * Add row to the redirect table if this is a redirect, remove otherwise.
1311 * @param IDatabase $dbw
1312 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1313 * or NULL if this is not a redirect
1314 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1315 * removing rows in redirect table.
1316 * @return bool True on success, false on failure
1319 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1320 // Always update redirects (target link might have changed)
1321 // Update/Insert if we don't know if the last revision was a redirect or not
1322 // Delete if changing from redirect to non-redirect
1323 $isRedirect = !is_null( $redirectTitle );
1325 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1329 if ( $isRedirect ) {
1330 $this->insertRedirectEntry( $redirectTitle );
1332 // This is not a redirect, remove row from redirect table
1333 $where = [ 'rd_from' => $this->getId() ];
1334 $dbw->delete( 'redirect', $where, __METHOD__
);
1337 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1338 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1341 return ( $dbw->affectedRows() != 0 );
1345 * If the given revision is newer than the currently set page_latest,
1346 * update the page record. Otherwise, do nothing.
1348 * @deprecated since 1.24, use updateRevisionOn instead
1350 * @param IDatabase $dbw
1351 * @param Revision $revision
1354 public function updateIfNewerOn( $dbw, $revision ) {
1355 $row = $dbw->selectRow(
1356 [ 'revision', 'page' ],
1357 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1359 'page_id' => $this->getId(),
1360 'page_latest=rev_id' ],
1364 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1367 $prev = $row->rev_id
;
1368 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1370 // No or missing previous revision; mark the page as new
1372 $lastRevIsRedirect = null;
1375 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1381 * Get the content that needs to be saved in order to undo all revisions
1382 * between $undo and $undoafter. Revisions must belong to the same page,
1383 * must exist and must not be deleted
1384 * @param Revision $undo
1385 * @param Revision $undoafter Must be an earlier revision than $undo
1386 * @return Content|bool Content on success, false on failure
1388 * Before we had the Content object, this was done in getUndoText
1390 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1391 $handler = $undo->getContentHandler();
1392 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1396 * Returns true if this page's content model supports sections.
1400 * @todo The skin should check this and not offer section functionality if
1401 * sections are not supported.
1402 * @todo The EditPage should check this and not offer section functionality
1403 * if sections are not supported.
1405 public function supportsSections() {
1406 return $this->getContentHandler()->supportsSections();
1410 * @param string|int|null|bool $sectionId Section identifier as a number or string
1411 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1412 * or 'new' for a new section.
1413 * @param Content $sectionContent New content of the section.
1414 * @param string $sectionTitle New section's subject, only if $section is "new".
1415 * @param string $edittime Revision timestamp or null to use the current revision.
1417 * @throws MWException
1418 * @return Content|null New complete article content, or null if error.
1421 * @deprecated since 1.24, use replaceSectionAtRev instead
1423 public function replaceSectionContent(
1424 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1427 if ( $edittime && $sectionId !== 'new' ) {
1428 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1429 $dbr = wfGetDB( DB_REPLICA
);
1430 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1431 // Try the master if this thread may have just added it.
1432 // This could be abstracted into a Revision method, but we don't want
1433 // to encourage loading of revisions by timestamp.
1435 && $lb->getServerCount() > 1
1436 && $lb->hasOrMadeRecentMasterChanges()
1438 $dbw = wfGetDB( DB_MASTER
);
1439 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1442 $baseRevId = $rev->getId();
1446 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1450 * @param string|int|null|bool $sectionId Section identifier as a number or string
1451 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1452 * or 'new' for a new section.
1453 * @param Content $sectionContent New content of the section.
1454 * @param string $sectionTitle New section's subject, only if $section is "new".
1455 * @param int|null $baseRevId
1457 * @throws MWException
1458 * @return Content|null New complete article content, or null if error.
1462 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1463 $sectionTitle = '', $baseRevId = null
1465 if ( strval( $sectionId ) === '' ) {
1466 // Whole-page edit; let the whole text through
1467 $newContent = $sectionContent;
1469 if ( !$this->supportsSections() ) {
1470 throw new MWException( "sections not supported for content model " .
1471 $this->getContentHandler()->getModelID() );
1474 // T32711: always use current version when adding a new section
1475 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1476 $oldContent = $this->getContent();
1478 $rev = Revision
::newFromId( $baseRevId );
1480 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1481 $this->getId() . "; section: $sectionId)\n" );
1485 $oldContent = $rev->getContent();
1488 if ( !$oldContent ) {
1489 wfDebug( __METHOD__
. ": no page text\n" );
1493 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1500 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1502 * @return int Updated $flags
1504 public function checkFlags( $flags ) {
1505 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1506 if ( $this->exists() ) {
1507 $flags |
= EDIT_UPDATE
;
1517 * Change an existing article or create a new article. Updates RC and all necessary caches,
1518 * optionally via the deferred update array.
1520 * @param Content $content New content
1521 * @param string $summary Edit summary
1522 * @param int $flags Bitfield:
1524 * Article is known or assumed to be non-existent, create a new one
1526 * Article is known or assumed to be pre-existing, update it
1528 * Mark this edit minor, if the user is allowed to do so
1530 * Do not log the change in recentchanges
1532 * Mark the edit a "bot" edit regardless of user rights
1534 * Fill in blank summaries with generated text where possible
1536 * Signal that the page retrieve/save cycle happened entirely in this request.
1538 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1539 * article will be detected. If EDIT_UPDATE is specified and the article
1540 * doesn't exist, the function will return an edit-gone-missing error. If
1541 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1542 * error will be returned. These two conditions are also possible with
1543 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1545 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1546 * This is not the parent revision ID, rather the revision ID for older
1547 * content used as the source for a rollback, for example.
1548 * @param User $user The user doing the edit
1549 * @param string $serialFormat Format for storing the content in the
1551 * @param array|null $tags Change tags to apply to this edit
1552 * Callers are responsible for permission checks
1553 * (with ChangeTags::canAddTagsAccompanyingChange)
1554 * @param Int $undidRevId Id of revision that was undone or 0
1556 * @throws MWException
1557 * @return Status Possible errors:
1558 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1559 * set the fatal flag of $status.
1560 * edit-gone-missing: In update mode, but the article didn't exist.
1561 * edit-conflict: In update mode, the article changed unexpectedly.
1562 * edit-no-change: Warning that the text was the same as before.
1563 * edit-already-exists: In creation mode, but the article already exists.
1565 * Extensions may define additional errors.
1567 * $return->value will contain an associative array with members as follows:
1568 * new: Boolean indicating if the function attempted to create a new article.
1569 * revision: The revision object for the inserted revision, or null.
1572 * @throws MWException
1574 public function doEditContent(
1575 Content
$content, $summary, $flags = 0, $baseRevId = false,
1576 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1578 global $wgUser, $wgUseAutomaticEditSummaries;
1580 // Old default parameter for $tags was null
1581 if ( $tags === null ) {
1585 // Low-level sanity check
1586 if ( $this->mTitle
->getText() === '' ) {
1587 throw new MWException( 'Something is trying to edit an article with an empty title' );
1589 // Make sure the given content type is allowed for this page
1590 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1591 return Status
::newFatal( 'content-not-allowed-here',
1592 ContentHandler
::getLocalizedName( $content->getModel() ),
1593 $this->mTitle
->getPrefixedText()
1597 // Load the data from the master database if needed.
1598 // The caller may already loaded it from the master or even loaded it using
1599 // SELECT FOR UPDATE, so do not override that using clear().
1600 $this->loadPageData( 'fromdbmaster' );
1602 $user = $user ?
: $wgUser;
1603 $flags = $this->checkFlags( $flags );
1605 // Avoid PHP 7.1 warning of passing $this by reference
1608 // Trigger pre-save hook (using provided edit summary)
1609 $hookStatus = Status
::newGood( [] );
1610 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1611 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1612 // Check if the hook rejected the attempted save
1613 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1614 if ( $hookStatus->isOK() ) {
1615 // Hook returned false but didn't call fatal(); use generic message
1616 $hookStatus->fatal( 'edit-hook-aborted' );
1622 $old_revision = $this->getRevision(); // current revision
1623 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1625 $handler = $content->getContentHandler();
1626 $tag = $handler->getChangeTag( $old_content, $content, $flags );
1627 // If there is no applicable tag, null is returned, so we need to check
1632 // Check for undo tag
1633 if ( $undidRevId !== 0 && in_array( 'mw-undo', ChangeTags
::getSoftwareTags() ) ) {
1634 $tags[] = 'mw-undo';
1637 // Provide autosummaries if summary is not provided and autosummaries are enabled
1638 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1639 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1642 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1643 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1649 // Get the pre-save transform content and final parser output
1650 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1651 $pstContent = $editInfo->pstContent
; // Content object
1653 'bot' => ( $flags & EDIT_FORCE_BOT
),
1654 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1655 'serialized' => $pstContent->serialize( $serialFormat ),
1656 'serialFormat' => $serialFormat,
1657 'baseRevId' => $baseRevId,
1658 'oldRevision' => $old_revision,
1659 'oldContent' => $old_content,
1660 'oldId' => $this->getLatest(),
1661 'oldIsRedirect' => $this->isRedirect(),
1662 'oldCountable' => $this->isCountable(),
1663 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1664 'undidRevId' => $undidRevId
1667 // Actually create the revision and create/update the page
1668 if ( $flags & EDIT_UPDATE
) {
1669 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1671 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1674 // Promote user to any groups they meet the criteria for
1675 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1676 $user->addAutopromoteOnceGroups( 'onEdit' );
1677 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1684 * @param Content $content Pre-save transform content
1687 * @param string $summary
1688 * @param array $meta
1690 * @throws DBUnexpectedError
1692 * @throws FatalError
1693 * @throws MWException
1695 private function doModify(
1696 Content
$content, $flags, User
$user, $summary, array $meta
1698 global $wgUseRCPatrol;
1700 // Update article, but only if changed.
1701 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1703 // Convenience variables
1704 $now = wfTimestampNow();
1705 $oldid = $meta['oldId'];
1706 /** @var Content|null $oldContent */
1707 $oldContent = $meta['oldContent'];
1708 $newsize = $content->getSize();
1711 // Article gone missing
1712 $status->fatal( 'edit-gone-missing' );
1715 } elseif ( !$oldContent ) {
1716 // Sanity check for T39225
1717 throw new MWException( "Could not find text for current revision {$oldid}." );
1720 $changed = !$content->equals( $oldContent );
1722 $dbw = wfGetDB( DB_MASTER
);
1725 // @TODO: pass content object?!
1726 $revision = new Revision( [
1727 'page' => $this->getId(),
1728 'title' => $this->mTitle
, // for determining the default content model
1729 'comment' => $summary,
1730 'minor_edit' => $meta['minor'],
1731 'text' => $meta['serialized'],
1733 'parent_id' => $oldid,
1734 'user' => $user->getId(),
1735 'user_text' => $user->getName(),
1736 'timestamp' => $now,
1737 'content_model' => $content->getModel(),
1738 'content_format' => $meta['serialFormat'],
1741 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1742 $status->merge( $prepStatus );
1743 if ( !$status->isOK() ) {
1747 $dbw->startAtomic( __METHOD__
);
1748 // Get the latest page_latest value while locking it.
1749 // Do a CAS style check to see if it's the same as when this method
1750 // started. If it changed then bail out before touching the DB.
1751 $latestNow = $this->lockAndGetLatest();
1752 if ( $latestNow != $oldid ) {
1753 $dbw->endAtomic( __METHOD__
);
1754 // Page updated or deleted in the mean time
1755 $status->fatal( 'edit-conflict' );
1760 // At this point we are now comitted to returning an OK
1761 // status unless some DB query error or other exception comes up.
1762 // This way callers don't have to call rollback() if $status is bad
1763 // unless they actually try to catch exceptions (which is rare).
1765 // Save the revision text
1766 $revisionId = $revision->insertOn( $dbw );
1767 // Update page_latest and friends to reflect the new revision
1768 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1769 throw new MWException( "Failed to update page row to use new revision." );
1772 Hooks
::run( 'NewRevisionFromEditComplete',
1773 [ $this, $revision, $meta['baseRevId'], $user ] );
1775 // Update recentchanges
1776 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1777 // Mark as patrolled if the user can do so
1778 $patrolled = $wgUseRCPatrol && !count(
1779 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1780 // Add RC row to the DB
1781 RecentChange
::notifyEdit(
1784 $revision->isMinor(),
1788 $this->getTimestamp(),
1791 $oldContent ?
$oldContent->getSize() : 0,
1799 $user->incEditCount();
1801 $dbw->endAtomic( __METHOD__
);
1802 $this->mTimestamp
= $now;
1804 // T34948: revision ID must be set to page {{REVISIONID}} and
1805 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1806 // Since we don't insert a new revision into the database, the least
1807 // error-prone way is to reuse given old revision.
1808 $revision = $meta['oldRevision'];
1812 // Return the new revision to the caller
1813 $status->value
['revision'] = $revision;
1815 $status->warning( 'edit-no-change' );
1816 // Update page_touched as updateRevisionOn() was not called.
1817 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1818 $this->mTitle
->invalidateCache( $now );
1821 // Do secondary updates once the main changes have been committed...
1822 DeferredUpdates
::addUpdate(
1823 new AtomicSectionUpdate(
1827 $revision, &$user, $content, $summary, &$flags,
1828 $changed, $meta, &$status
1830 // Update links tables, site stats, etc.
1831 $this->doEditUpdates(
1835 'changed' => $changed,
1836 'oldcountable' => $meta['oldCountable'],
1837 'oldrevision' => $meta['oldRevision']
1840 // Avoid PHP 7.1 warning of passing $this by reference
1842 // Trigger post-save hook
1843 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1844 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1845 $meta['undidRevId'] ];
1846 Hooks
::run( 'PageContentSaveComplete', $params );
1849 DeferredUpdates
::PRESEND
1856 * @param Content $content Pre-save transform content
1859 * @param string $summary
1860 * @param array $meta
1862 * @throws DBUnexpectedError
1864 * @throws FatalError
1865 * @throws MWException
1867 private function doCreate(
1868 Content
$content, $flags, User
$user, $summary, array $meta
1870 global $wgUseRCPatrol, $wgUseNPPatrol;
1872 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1874 $now = wfTimestampNow();
1875 $newsize = $content->getSize();
1876 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1877 $status->merge( $prepStatus );
1878 if ( !$status->isOK() ) {
1882 $dbw = wfGetDB( DB_MASTER
);
1883 $dbw->startAtomic( __METHOD__
);
1885 // Add the page record unless one already exists for the title
1886 $newid = $this->insertOn( $dbw );
1887 if ( $newid === false ) {
1888 $dbw->endAtomic( __METHOD__
); // nothing inserted
1889 $status->fatal( 'edit-already-exists' );
1891 return $status; // nothing done
1894 // At this point we are now comitted to returning an OK
1895 // status unless some DB query error or other exception comes up.
1896 // This way callers don't have to call rollback() if $status is bad
1897 // unless they actually try to catch exceptions (which is rare).
1899 // @TODO: pass content object?!
1900 $revision = new Revision( [
1902 'title' => $this->mTitle
, // for determining the default content model
1903 'comment' => $summary,
1904 'minor_edit' => $meta['minor'],
1905 'text' => $meta['serialized'],
1907 'user' => $user->getId(),
1908 'user_text' => $user->getName(),
1909 'timestamp' => $now,
1910 'content_model' => $content->getModel(),
1911 'content_format' => $meta['serialFormat'],
1914 // Save the revision text...
1915 $revisionId = $revision->insertOn( $dbw );
1916 // Update the page record with revision data
1917 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1918 throw new MWException( "Failed to update page row to use new revision." );
1921 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1923 // Update recentchanges
1924 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1925 // Mark as patrolled if the user can do so
1926 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1927 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1928 // Add RC row to the DB
1929 RecentChange
::notifyNew(
1932 $revision->isMinor(),
1944 $user->incEditCount();
1946 $dbw->endAtomic( __METHOD__
);
1947 $this->mTimestamp
= $now;
1949 // Return the new revision to the caller
1950 $status->value
['revision'] = $revision;
1952 // Do secondary updates once the main changes have been committed...
1953 DeferredUpdates
::addUpdate(
1954 new AtomicSectionUpdate(
1958 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1960 // Update links, etc.
1961 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1962 // Avoid PHP 7.1 warning of passing $this by reference
1964 // Trigger post-create hook
1965 $params = [ &$wikiPage, &$user, $content, $summary,
1966 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1967 Hooks
::run( 'PageContentInsertComplete', $params );
1968 // Trigger post-save hook
1969 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1970 Hooks
::run( 'PageContentSaveComplete', $params );
1973 DeferredUpdates
::PRESEND
1980 * Get parser options suitable for rendering the primary article wikitext
1982 * @see ContentHandler::makeParserOptions
1984 * @param IContextSource|User|string $context One of the following:
1985 * - IContextSource: Use the User and the Language of the provided
1987 * - User: Use the provided User object and $wgLang for the language,
1988 * so use an IContextSource object if possible.
1989 * - 'canonical': Canonical options (anonymous user with default
1990 * preferences and content language).
1991 * @return ParserOptions
1993 public function makeParserOptions( $context ) {
1994 $options = $this->getContentHandler()->makeParserOptions( $context );
1996 if ( $this->getTitle()->isConversionTable() ) {
1997 // @todo ConversionTable should become a separate content model, so
1998 // we don't need special cases like this one.
1999 $options->disableContentConversion();
2006 * Prepare content which is about to be saved.
2008 * Prior to 1.30, this returned a stdClass object with the same class
2011 * @param Content $content
2012 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2013 * revision ID is also accepted, but this is deprecated.
2014 * @param User|null $user
2015 * @param string|null $serialFormat
2016 * @param bool $useCache Check shared prepared edit cache
2018 * @return PreparedEdit
2022 public function prepareContentForEdit(
2023 Content
$content, $revision = null, User
$user = null,
2024 $serialFormat = null, $useCache = true
2026 global $wgContLang, $wgUser, $wgAjaxEditStash;
2028 if ( is_object( $revision ) ) {
2029 $revid = $revision->getId();
2032 // This code path is deprecated, and nothing is known to
2033 // use it, so performance here shouldn't be a worry.
2034 if ( $revid !== null ) {
2035 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
2036 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2042 $user = is_null( $user ) ?
$wgUser : $user;
2043 // XXX: check $user->getId() here???
2045 // Use a sane default for $serialFormat, see T59026
2046 if ( $serialFormat === null ) {
2047 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2050 if ( $this->mPreparedEdit
2051 && isset( $this->mPreparedEdit
->newContent
)
2052 && $this->mPreparedEdit
->newContent
->equals( $content )
2053 && $this->mPreparedEdit
->revid
== $revid
2054 && $this->mPreparedEdit
->format
== $serialFormat
2055 // XXX: also check $user here?
2058 return $this->mPreparedEdit
;
2061 // The edit may have already been prepared via api.php?action=stashedit
2062 $cachedEdit = $useCache && $wgAjaxEditStash
2063 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2066 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2067 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2069 $edit = new PreparedEdit();
2070 if ( $cachedEdit ) {
2071 $edit->timestamp
= $cachedEdit->timestamp
;
2073 $edit->timestamp
= wfTimestampNow();
2075 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2076 $edit->revid
= $revid;
2078 if ( $cachedEdit ) {
2079 $edit->pstContent
= $cachedEdit->pstContent
;
2081 $edit->pstContent
= $content
2082 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2086 $edit->format
= $serialFormat;
2087 $edit->popts
= $this->makeParserOptions( 'canonical' );
2088 if ( $cachedEdit ) {
2089 $edit->output
= $cachedEdit->output
;
2092 // We get here if vary-revision is set. This means that this page references
2093 // itself (such as via self-transclusion). In this case, we need to make sure
2094 // that any such self-references refer to the newly-saved revision, and not
2095 // to the previous one, which could otherwise happen due to replica DB lag.
2096 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2097 $edit->popts
->setCurrentRevisionCallback(
2098 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2099 if ( $title->equals( $revision->getTitle() ) ) {
2102 return call_user_func( $oldCallback, $title, $parser );
2107 // Try to avoid a second parse if {{REVISIONID}} is used
2108 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2109 ? DB_MASTER
// use the best possible guess
2110 : DB_REPLICA
; // T154554
2112 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2113 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2121 $edit->output
= $edit->pstContent
2122 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2126 $edit->newContent
= $content;
2127 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2129 // NOTE: B/C for hooks! don't use these fields!
2130 $edit->newText
= $edit->newContent
2131 ? ContentHandler
::getContentText( $edit->newContent
)
2133 $edit->oldText
= $edit->oldContent
2134 ? ContentHandler
::getContentText( $edit->oldContent
)
2136 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2138 if ( $edit->output
) {
2139 $edit->output
->setCacheTime( wfTimestampNow() );
2142 // Process cache the result
2143 $this->mPreparedEdit
= $edit;
2149 * Do standard deferred updates after page edit.
2150 * Update links tables, site stats, search index and message cache.
2151 * Purges pages that include this page if the text was changed here.
2152 * Every 100th edit, prune the recent changes table.
2154 * @param Revision $revision
2155 * @param User $user User object that did the revision
2156 * @param array $options Array of options, following indexes are used:
2157 * - changed: bool, whether the revision changed the content (default true)
2158 * - created: bool, whether the revision created the page (default false)
2159 * - moved: bool, whether the page was moved (default false)
2160 * - restored: bool, whether the page was undeleted (default false)
2161 * - oldrevision: Revision object for the pre-update revision (default null)
2162 * - oldcountable: bool, null, or string 'no-change' (default null):
2163 * - bool: whether the page was counted as an article before that
2164 * revision, only used in changed is true and created is false
2165 * - null: if created is false, don't update the article count; if created
2166 * is true, do update the article count
2167 * - 'no-change': don't update the article count, ever
2169 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2170 global $wgRCWatchCategoryMembership;
2176 'restored' => false,
2177 'oldrevision' => null,
2178 'oldcountable' => null
2180 $content = $revision->getContent();
2182 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2184 // See if the parser output before $revision was inserted is still valid
2186 if ( !$this->mPreparedEdit
) {
2187 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2188 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2189 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2190 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2191 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2193 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2194 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2195 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2197 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2198 $editInfo = $this->mPreparedEdit
;
2202 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2203 // $text is usually already pre-save transformed once. Avoid using the edit stash
2204 // as any prepared content from there or in doEditContent() was already rejected.
2205 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2208 // Save it to the parser cache.
2209 // Make sure the cache time matches page_touched to avoid double parsing.
2210 MediaWikiServices
::getInstance()->getParserCache()->save(
2211 $editInfo->output
, $this, $editInfo->popts
,
2212 $revision->getTimestamp(), $editInfo->revid
2215 // Update the links tables and other secondary data
2217 $recursive = $options['changed']; // T52785
2218 $updates = $content->getSecondaryDataUpdates(
2219 $this->getTitle(), null, $recursive, $editInfo->output
2221 foreach ( $updates as $update ) {
2222 $update->setCause( 'edit-page', $user->getName() );
2223 if ( $update instanceof LinksUpdate
) {
2224 $update->setRevision( $revision );
2225 $update->setTriggeringUser( $user );
2227 DeferredUpdates
::addUpdate( $update );
2229 if ( $wgRCWatchCategoryMembership
2230 && $this->getContentHandler()->supportsCategories() === true
2231 && ( $options['changed'] ||
$options['created'] )
2232 && !$options['restored']
2234 // Note: jobs are pushed after deferred updates, so the job should be able to see
2235 // the recent change entry (also done via deferred updates) and carry over any
2236 // bot/deletion/IP flags, ect.
2237 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2240 'pageId' => $this->getId(),
2241 'revTimestamp' => $revision->getTimestamp()
2247 // Avoid PHP 7.1 warning of passing $this by reference
2250 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2252 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2253 // Flush old entries from the `recentchanges` table
2254 if ( mt_rand( 0, 9 ) == 0 ) {
2255 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2259 if ( !$this->exists() ) {
2263 $id = $this->getId();
2264 $title = $this->mTitle
->getPrefixedDBkey();
2265 $shortTitle = $this->mTitle
->getDBkey();
2267 if ( $options['oldcountable'] === 'no-change' ||
2268 ( !$options['changed'] && !$options['moved'] )
2271 } elseif ( $options['created'] ) {
2272 $good = (int)$this->isCountable( $editInfo );
2273 } elseif ( $options['oldcountable'] !== null ) {
2274 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2278 $edits = $options['changed'] ?
1 : 0;
2279 $total = $options['created'] ?
1 : 0;
2281 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2282 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2284 // If this is another user's talk page, update newtalk.
2285 // Don't do this if $options['changed'] = false (null-edits) nor if
2286 // it's a minor edit and the user doesn't want notifications for those.
2287 if ( $options['changed']
2288 && $this->mTitle
->getNamespace() == NS_USER_TALK
2289 && $shortTitle != $user->getTitleKey()
2290 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2292 $recipient = User
::newFromName( $shortTitle, false );
2293 if ( !$recipient ) {
2294 wfDebug( __METHOD__
. ": invalid username\n" );
2296 // Avoid PHP 7.1 warning of passing $this by reference
2299 // Allow extensions to prevent user notification
2300 // when a new message is added to their talk page
2301 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2302 if ( User
::isIP( $shortTitle ) ) {
2303 // An anonymous user
2304 $recipient->setNewtalk( true, $revision );
2305 } elseif ( $recipient->isLoggedIn() ) {
2306 $recipient->setNewtalk( true, $revision );
2308 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2314 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2315 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2318 if ( $options['created'] ) {
2319 self
::onArticleCreate( $this->mTitle
);
2320 } elseif ( $options['changed'] ) { // T52785
2321 self
::onArticleEdit( $this->mTitle
, $revision );
2324 ResourceLoaderWikiModule
::invalidateModuleCache(
2325 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2330 * Update the article's restriction field, and leave a log entry.
2331 * This works for protection both existing and non-existing pages.
2333 * @param array $limit Set of restriction keys
2334 * @param array $expiry Per restriction type expiration
2335 * @param int &$cascade Set to false if cascading protection isn't allowed.
2336 * @param string $reason
2337 * @param User $user The user updating the restrictions
2338 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2339 * ($user should be able to add the specified tags before this is called)
2340 * @return Status Status object; if action is taken, $status->value is the log_id of the
2341 * protection log entry.
2343 public function doUpdateRestrictions( array $limit, array $expiry,
2344 &$cascade, $reason, User
$user, $tags = null
2346 global $wgCascadingRestrictionLevels;
2348 if ( wfReadOnly() ) {
2349 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2352 $this->loadPageData( 'fromdbmaster' );
2353 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2354 $id = $this->getId();
2360 // Take this opportunity to purge out expired restrictions
2361 Title
::purgeExpiredRestrictions();
2363 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2364 // we expect a single selection, but the schema allows otherwise.
2365 $isProtected = false;
2369 $dbw = wfGetDB( DB_MASTER
);
2371 foreach ( $restrictionTypes as $action ) {
2372 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2373 $expiry[$action] = 'infinity';
2375 if ( !isset( $limit[$action] ) ) {
2376 $limit[$action] = '';
2377 } elseif ( $limit[$action] != '' ) {
2381 // Get current restrictions on $action
2382 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2383 if ( $current != '' ) {
2384 $isProtected = true;
2387 if ( $limit[$action] != $current ) {
2389 } elseif ( $limit[$action] != '' ) {
2390 // Only check expiry change if the action is actually being
2391 // protected, since expiry does nothing on an not-protected
2393 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2399 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2403 // If nothing has changed, do nothing
2405 return Status
::newGood();
2408 if ( !$protect ) { // No protection at all means unprotection
2409 $revCommentMsg = 'unprotectedarticle-comment';
2410 $logAction = 'unprotect';
2411 } elseif ( $isProtected ) {
2412 $revCommentMsg = 'modifiedarticleprotection-comment';
2413 $logAction = 'modify';
2415 $revCommentMsg = 'protectedarticle-comment';
2416 $logAction = 'protect';
2419 $logRelationsValues = [];
2420 $logRelationsField = null;
2421 $logParamsDetails = [];
2423 // Null revision (used for change tag insertion)
2424 $nullRevision = null;
2426 if ( $id ) { // Protection of existing page
2427 // Avoid PHP 7.1 warning of passing $this by reference
2430 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2431 return Status
::newGood();
2434 // Only certain restrictions can cascade...
2435 $editrestriction = isset( $limit['edit'] )
2436 ?
[ $limit['edit'] ]
2437 : $this->mTitle
->getRestrictions( 'edit' );
2438 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2439 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2441 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2442 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2445 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2446 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2447 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2449 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2450 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2453 // The schema allows multiple restrictions
2454 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2458 // insert null revision to identify the page protection change as edit summary
2459 $latest = $this->getLatest();
2460 $nullRevision = $this->insertProtectNullRevision(
2469 if ( $nullRevision === null ) {
2470 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2473 $logRelationsField = 'pr_id';
2475 // Update restrictions table
2476 foreach ( $limit as $action => $restrictions ) {
2478 'page_restrictions',
2481 'pr_type' => $action
2485 if ( $restrictions != '' ) {
2486 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2488 'page_restrictions',
2491 'pr_type' => $action,
2492 'pr_level' => $restrictions,
2493 'pr_cascade' => $cascadeValue,
2494 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2498 $logRelationsValues[] = $dbw->insertId();
2499 $logParamsDetails[] = [
2501 'level' => $restrictions,
2502 'expiry' => $expiry[$action],
2503 'cascade' => (bool)$cascadeValue,
2508 // Clear out legacy restriction fields
2511 [ 'page_restrictions' => '' ],
2512 [ 'page_id' => $id ],
2516 // Avoid PHP 7.1 warning of passing $this by reference
2519 Hooks
::run( 'NewRevisionFromEditComplete',
2520 [ $this, $nullRevision, $latest, $user ] );
2521 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2522 } else { // Protection of non-existing page (also known as "title protection")
2523 // Cascade protection is meaningless in this case
2526 if ( $limit['create'] != '' ) {
2527 $commentFields = CommentStore
::newKey( 'pt_reason' )->insert( $dbw, $reason );
2528 $dbw->replace( 'protected_titles',
2529 [ [ 'pt_namespace', 'pt_title' ] ],
2531 'pt_namespace' => $this->mTitle
->getNamespace(),
2532 'pt_title' => $this->mTitle
->getDBkey(),
2533 'pt_create_perm' => $limit['create'],
2534 'pt_timestamp' => $dbw->timestamp(),
2535 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2536 'pt_user' => $user->getId(),
2537 ] +
$commentFields, __METHOD__
2539 $logParamsDetails[] = [
2541 'level' => $limit['create'],
2542 'expiry' => $expiry['create'],
2545 $dbw->delete( 'protected_titles',
2547 'pt_namespace' => $this->mTitle
->getNamespace(),
2548 'pt_title' => $this->mTitle
->getDBkey()
2554 $this->mTitle
->flushRestrictions();
2555 InfoAction
::invalidateCache( $this->mTitle
);
2557 if ( $logAction == 'unprotect' ) {
2560 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2562 '4::description' => $protectDescriptionLog, // parameter for IRC
2563 '5:bool:cascade' => $cascade,
2564 'details' => $logParamsDetails, // parameter for localize and api
2568 // Update the protection log
2569 $logEntry = new ManualLogEntry( 'protect', $logAction );
2570 $logEntry->setTarget( $this->mTitle
);
2571 $logEntry->setComment( $reason );
2572 $logEntry->setPerformer( $user );
2573 $logEntry->setParameters( $params );
2574 if ( !is_null( $nullRevision ) ) {
2575 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2577 $logEntry->setTags( $tags );
2578 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2579 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2581 $logId = $logEntry->insert();
2582 $logEntry->publish( $logId );
2584 return Status
::newGood( $logId );
2588 * Insert a new null revision for this page.
2590 * @param string $revCommentMsg Comment message key for the revision
2591 * @param array $limit Set of restriction keys
2592 * @param array $expiry Per restriction type expiration
2593 * @param int $cascade Set to false if cascading protection isn't allowed.
2594 * @param string $reason
2595 * @param User|null $user
2596 * @return Revision|null Null on error
2598 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2599 array $expiry, $cascade, $reason, $user = null
2601 $dbw = wfGetDB( DB_MASTER
);
2603 // Prepare a null revision to be added to the history
2604 $editComment = wfMessage(
2606 $this->mTitle
->getPrefixedText(),
2607 $user ?
$user->getName() : ''
2608 )->inContentLanguage()->text();
2610 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2612 $protectDescription = $this->protectDescription( $limit, $expiry );
2613 if ( $protectDescription ) {
2614 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2615 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2616 ->inContentLanguage()->text();
2619 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2620 $editComment .= wfMessage( 'brackets' )->params(
2621 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2622 )->inContentLanguage()->text();
2625 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2627 $nullRev->insertOn( $dbw );
2629 // Update page record and touch page
2630 $oldLatest = $nullRev->getParentId();
2631 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2638 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2641 protected function formatExpiry( $expiry ) {
2644 if ( $expiry != 'infinity' ) {
2647 $wgContLang->timeanddate( $expiry, false, false ),
2648 $wgContLang->date( $expiry, false, false ),
2649 $wgContLang->time( $expiry, false, false )
2650 )->inContentLanguage()->text();
2652 return wfMessage( 'protect-expiry-indefinite' )
2653 ->inContentLanguage()->text();
2658 * Builds the description to serve as comment for the edit.
2660 * @param array $limit Set of restriction keys
2661 * @param array $expiry Per restriction type expiration
2664 public function protectDescription( array $limit, array $expiry ) {
2665 $protectDescription = '';
2667 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2668 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2669 # All possible message keys are listed here for easier grepping:
2670 # * restriction-create
2671 # * restriction-edit
2672 # * restriction-move
2673 # * restriction-upload
2674 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2675 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2676 # with '' filtered out. All possible message keys are listed below:
2677 # * protect-level-autoconfirmed
2678 # * protect-level-sysop
2679 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2680 ->inContentLanguage()->text();
2682 $expiryText = $this->formatExpiry( $expiry[$action] );
2684 if ( $protectDescription !== '' ) {
2685 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2687 $protectDescription .= wfMessage( 'protect-summary-desc' )
2688 ->params( $actionText, $restrictionsText, $expiryText )
2689 ->inContentLanguage()->text();
2692 return $protectDescription;
2696 * Builds the description to serve as comment for the log entry.
2698 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2699 * protect description text. Keep them in old format to avoid breaking compatibility.
2700 * TODO: Fix protection log to store structured description and format it on-the-fly.
2702 * @param array $limit Set of restriction keys
2703 * @param array $expiry Per restriction type expiration
2706 public function protectDescriptionLog( array $limit, array $expiry ) {
2709 $protectDescriptionLog = '';
2711 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2712 $expiryText = $this->formatExpiry( $expiry[$action] );
2713 $protectDescriptionLog .= $wgContLang->getDirMark() .
2714 "[$action=$restrictions] ($expiryText)";
2717 return trim( $protectDescriptionLog );
2721 * Take an array of page restrictions and flatten it to a string
2722 * suitable for insertion into the page_restrictions field.
2724 * @param string[] $limit
2726 * @throws MWException
2729 protected static function flattenRestrictions( $limit ) {
2730 if ( !is_array( $limit ) ) {
2731 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2737 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2738 $bits[] = "$action=$restrictions";
2741 return implode( ':', $bits );
2745 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2746 * backwards compatibility, if you care about error reporting you should use
2747 * doDeleteArticleReal() instead.
2749 * Deletes the article with database consistency, writes logs, purges caches
2751 * @param string $reason Delete reason for deletion log
2752 * @param bool $suppress Suppress all revisions and log the deletion in
2753 * the suppression log instead of the deletion log
2754 * @param int $u1 Unused
2755 * @param bool $u2 Unused
2756 * @param array|string &$error Array of errors to append to
2757 * @param User $user The deleting user
2758 * @return bool True if successful
2760 public function doDeleteArticle(
2761 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2763 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2764 return $status->isGood();
2768 * Back-end article deletion
2769 * Deletes the article with database consistency, writes logs, purges caches
2773 * @param string $reason Delete reason for deletion log
2774 * @param bool $suppress Suppress all revisions and log the deletion in
2775 * the suppression log instead of the deletion log
2776 * @param int $u1 Unused
2777 * @param bool $u2 Unused
2778 * @param array|string &$error Array of errors to append to
2779 * @param User $user The deleting user
2780 * @param array $tags Tags to apply to the deletion action
2781 * @param string $logsubtype
2782 * @return Status Status object; if successful, $status->value is the log_id of the
2783 * deletion log entry. If the page couldn't be deleted because it wasn't
2784 * found, $status is a non-fatal 'cannotdelete' error
2786 public function doDeleteArticleReal(
2787 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2788 $tags = [], $logsubtype = 'delete'
2790 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2792 wfDebug( __METHOD__
. "\n" );
2794 $status = Status
::newGood();
2796 if ( $this->mTitle
->getDBkey() === '' ) {
2797 $status->error( 'cannotdelete',
2798 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2802 // Avoid PHP 7.1 warning of passing $this by reference
2805 $user = is_null( $user ) ?
$wgUser : $user;
2806 if ( !Hooks
::run( 'ArticleDelete',
2807 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2809 if ( $status->isOK() ) {
2810 // Hook aborted but didn't set a fatal status
2811 $status->fatal( 'delete-hook-aborted' );
2816 $dbw = wfGetDB( DB_MASTER
);
2817 $dbw->startAtomic( __METHOD__
);
2819 $this->loadPageData( self
::READ_LATEST
);
2820 $id = $this->getId();
2821 // T98706: lock the page from various other updates but avoid using
2822 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2823 // the revisions queries (which also JOIN on user). Only lock the page
2824 // row and CAS check on page_latest to see if the trx snapshot matches.
2825 $lockedLatest = $this->lockAndGetLatest();
2826 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2827 $dbw->endAtomic( __METHOD__
);
2828 // Page not there or trx snapshot is stale
2829 $status->error( 'cannotdelete',
2830 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2834 // Given the lock above, we can be confident in the title and page ID values
2835 $namespace = $this->getTitle()->getNamespace();
2836 $dbKey = $this->getTitle()->getDBkey();
2838 // At this point we are now comitted to returning an OK
2839 // status unless some DB query error or other exception comes up.
2840 // This way callers don't have to call rollback() if $status is bad
2841 // unless they actually try to catch exceptions (which is rare).
2843 // we need to remember the old content so we can use it to generate all deletion updates.
2844 $revision = $this->getRevision();
2846 $content = $this->getContent( Revision
::RAW
);
2847 } catch ( Exception
$ex ) {
2848 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2849 . $ex->getMessage() );
2854 $revCommentStore = new CommentStore( 'rev_comment' );
2855 $arCommentStore = new CommentStore( 'ar_comment' );
2857 $revQuery = Revision
::getQueryInfo();
2860 // Bitfields to further suppress the content
2862 $bitfield = Revision
::SUPPRESSED_ALL
;
2863 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2866 // For now, shunt the revision data into the archive table.
2867 // Text is *not* removed from the text table; bulk storage
2868 // is left intact to avoid breaking block-compression or
2869 // immutable storage schemes.
2870 // In the future, we may keep revisions and mark them with
2871 // the rev_deleted field, which is reserved for this purpose.
2873 // Get all of the page revisions
2874 $res = $dbw->select(
2875 $revQuery['tables'],
2876 $revQuery['fields'],
2877 [ 'rev_page' => $id ],
2883 // Build their equivalent archive rows
2887 /** @var int[] Revision IDs of edits that were made by IPs */
2890 foreach ( $res as $row ) {
2891 $comment = $revCommentStore->getComment( $row );
2893 'ar_namespace' => $namespace,
2894 'ar_title' => $dbKey,
2895 'ar_user' => $row->rev_user
,
2896 'ar_user_text' => $row->rev_user_text
,
2897 'ar_timestamp' => $row->rev_timestamp
,
2898 'ar_minor_edit' => $row->rev_minor_edit
,
2899 'ar_rev_id' => $row->rev_id
,
2900 'ar_parent_id' => $row->rev_parent_id
,
2901 'ar_text_id' => $row->rev_text_id
,
2904 'ar_len' => $row->rev_len
,
2905 'ar_page_id' => $id,
2906 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2907 'ar_sha1' => $row->rev_sha1
,
2908 ] +
$arCommentStore->insert( $dbw, $comment );
2909 if ( $wgContentHandlerUseDB ) {
2910 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2911 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2913 $rowsInsert[] = $rowInsert;
2914 $revids[] = $row->rev_id
;
2916 // Keep track of IP edits, so that the corresponding rows can
2917 // be deleted in the ip_changes table.
2918 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2919 $ipRevIds[] = $row->rev_id
;
2922 // Copy them into the archive table
2923 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2924 // Save this so we can pass it to the ArticleDeleteComplete hook.
2925 $archivedRevisionCount = $dbw->affectedRows();
2927 // Clone the title and wikiPage, so we have the information we need when
2928 // we log and run the ArticleDeleteComplete hook.
2929 $logTitle = clone $this->mTitle
;
2930 $wikiPageBeforeDelete = clone $this;
2932 // Now that it's safely backed up, delete it
2933 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2934 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2935 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2936 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2939 // Also delete records from ip_changes as applicable.
2940 if ( count( $ipRevIds ) > 0 ) {
2941 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2944 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2945 $logtype = $suppress ?
'suppress' : 'delete';
2947 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2948 $logEntry->setPerformer( $user );
2949 $logEntry->setTarget( $logTitle );
2950 $logEntry->setComment( $reason );
2951 $logEntry->setTags( $tags );
2952 $logid = $logEntry->insert();
2954 $dbw->onTransactionPreCommitOrIdle(
2955 function () use ( $dbw, $logEntry, $logid ) {
2956 // T58776: avoid deadlocks (especially from FileDeleteForm)
2957 $logEntry->publish( $logid );
2962 $dbw->endAtomic( __METHOD__
);
2964 $this->doDeleteUpdates( $id, $content, $revision, $user );
2966 Hooks
::run( 'ArticleDeleteComplete', [
2967 &$wikiPageBeforeDelete,
2973 $archivedRevisionCount
2975 $status->value
= $logid;
2977 // Show log excerpt on 404 pages rather than just a link
2978 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2979 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2980 $cache->set( $key, 1, $cache::TTL_DAY
);
2986 * Lock the page row for this title+id and return page_latest (or 0)
2988 * @return int Returns 0 if no row was found with this title+id
2991 public function lockAndGetLatest() {
2992 return (int)wfGetDB( DB_MASTER
)->selectField(
2996 'page_id' => $this->getId(),
2997 // Typically page_id is enough, but some code might try to do
2998 // updates assuming the title is the same, so verify that
2999 'page_namespace' => $this->getTitle()->getNamespace(),
3000 'page_title' => $this->getTitle()->getDBkey()
3008 * Do some database updates after deletion
3010 * @param int $id The page_id value of the page being deleted
3011 * @param Content|null $content Optional page content to be used when determining
3012 * the required updates. This may be needed because $this->getContent()
3013 * may already return null when the page proper was deleted.
3014 * @param Revision|null $revision The latest page revision
3015 * @param User|null $user The user that caused the deletion
3017 public function doDeleteUpdates(
3018 $id, Content
$content = null, Revision
$revision = null, User
$user = null
3021 $countable = $this->isCountable();
3022 } catch ( Exception
$ex ) {
3023 // fallback for deleting broken pages for which we cannot load the content for
3024 // some reason. Note that doDeleteArticleReal() already logged this problem.
3028 // Update site status
3029 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3031 // Delete pagelinks, update secondary indexes, etc
3032 $updates = $this->getDeletionUpdates( $content );
3033 foreach ( $updates as $update ) {
3034 DeferredUpdates
::addUpdate( $update );
3037 $causeAgent = $user ?
$user->getName() : 'unknown';
3038 // Reparse any pages transcluding this page
3039 LinksUpdate
::queueRecursiveJobsForTable(
3040 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
3041 // Reparse any pages including this image
3042 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3043 LinksUpdate
::queueRecursiveJobsForTable(
3044 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
3048 self
::onArticleDelete( $this->mTitle
);
3049 ResourceLoaderWikiModule
::invalidateModuleCache(
3050 $this->mTitle
, $revision, null, wfWikiID()
3053 // Reset this object and the Title object
3054 $this->loadFromRow( false, self
::READ_LATEST
);
3057 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3061 * Roll back the most recent consecutive set of edits to a page
3062 * from the same user; fails if there are no eligible edits to
3063 * roll back to, e.g. user is the sole contributor. This function
3064 * performs permissions checks on $user, then calls commitRollback()
3065 * to do the dirty work
3067 * @todo Separate the business/permission stuff out from backend code
3068 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3070 * @param string $fromP Name of the user whose edits to rollback.
3071 * @param string $summary Custom summary. Set to default summary if empty.
3072 * @param string $token Rollback token.
3073 * @param bool $bot If true, mark all reverted edits as bot.
3075 * @param array &$resultDetails Array contains result-specific array of additional values
3076 * 'alreadyrolled' : 'current' (rev)
3077 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3079 * @param User $user The user performing the rollback
3080 * @param array|null $tags Change tags to apply to the rollback
3081 * Callers are responsible for permission checks
3082 * (with ChangeTags::canAddTagsAccompanyingChange)
3084 * @return array Array of errors, each error formatted as
3085 * array(messagekey, param1, param2, ...).
3086 * On success, the array is empty. This array can also be passed to
3087 * OutputPage::showPermissionsErrorPage().
3089 public function doRollback(
3090 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3092 $resultDetails = null;
3094 // Check permissions
3095 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3096 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3097 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3099 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3100 $errors[] = [ 'sessionfailure' ];
3103 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3104 $errors[] = [ 'actionthrottledtext' ];
3107 // If there were errors, bail out now
3108 if ( !empty( $errors ) ) {
3112 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3116 * Backend implementation of doRollback(), please refer there for parameter
3117 * and return value documentation
3119 * NOTE: This function does NOT check ANY permissions, it just commits the
3120 * rollback to the DB. Therefore, you should only call this function direct-
3121 * ly if you want to use custom permissions checks. If you don't, use
3122 * doRollback() instead.
3123 * @param string $fromP Name of the user whose edits to rollback.
3124 * @param string $summary Custom summary. Set to default summary if empty.
3125 * @param bool $bot If true, mark all reverted edits as bot.
3127 * @param array &$resultDetails Contains result-specific array of additional values
3128 * @param User $guser The user performing the rollback
3129 * @param array|null $tags Change tags to apply to the rollback
3130 * Callers are responsible for permission checks
3131 * (with ChangeTags::canAddTagsAccompanyingChange)
3135 public function commitRollback( $fromP, $summary, $bot,
3136 &$resultDetails, User
$guser, $tags = null
3138 global $wgUseRCPatrol, $wgContLang;
3140 $dbw = wfGetDB( DB_MASTER
);
3142 if ( wfReadOnly() ) {
3143 return [ [ 'readonlytext' ] ];
3146 // Get the last editor
3147 $current = $this->getRevision();
3148 if ( is_null( $current ) ) {
3149 // Something wrong... no page?
3150 return [ [ 'notanarticle' ] ];
3153 $from = str_replace( '_', ' ', $fromP );
3154 // User name given should match up with the top revision.
3155 // If the user was deleted then $from should be empty.
3156 if ( $from != $current->getUserText() ) {
3157 $resultDetails = [ 'current' => $current ];
3158 return [ [ 'alreadyrolled',
3159 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3160 htmlspecialchars( $fromP ),
3161 htmlspecialchars( $current->getUserText() )
3165 // Get the last edit not by this person...
3166 // Note: these may not be public values
3167 $user = intval( $current->getUser( Revision
::RAW
) );
3168 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3169 $s = $dbw->selectRow( 'revision',
3170 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3171 [ 'rev_page' => $current->getPage(),
3172 "rev_user != {$user} OR rev_user_text != {$user_text}"
3174 [ 'USE INDEX' => 'page_timestamp',
3175 'ORDER BY' => 'rev_timestamp DESC' ]
3177 if ( $s === false ) {
3178 // No one else ever edited this page
3179 return [ [ 'cantrollback' ] ];
3180 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3181 ||
$s->rev_deleted
& Revision
::DELETED_USER
3183 // Only admins can see this text
3184 return [ [ 'notvisiblerev' ] ];
3187 // Generate the edit summary if necessary
3188 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3189 if ( empty( $summary ) ) {
3190 if ( $from == '' ) { // no public user name
3191 $summary = wfMessage( 'revertpage-nouser' );
3193 $summary = wfMessage( 'revertpage' );
3197 // Allow the custom summary to use the same args as the default message
3199 $target->getUserText(), $from, $s->rev_id
,
3200 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3201 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3203 if ( $summary instanceof Message
) {
3204 $summary = $summary->params( $args )->inContentLanguage()->text();
3206 $summary = wfMsgReplaceArgs( $summary, $args );
3209 // Trim spaces on user supplied text
3210 $summary = trim( $summary );
3213 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3215 if ( $guser->isAllowed( 'minoredit' ) ) {
3216 $flags |
= EDIT_MINOR
;
3219 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3220 $flags |
= EDIT_FORCE_BOT
;
3223 $targetContent = $target->getContent();
3224 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3226 if ( in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
3227 $tags[] = 'mw-rollback';
3230 // Actually store the edit
3231 $status = $this->doEditContent(
3241 // Set patrolling and bot flag on the edits, which gets rollbacked.
3242 // This is done even on edit failure to have patrolling in that case (T64157).
3244 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3245 // Mark all reverted edits as bot
3249 if ( $wgUseRCPatrol ) {
3250 // Mark all reverted edits as patrolled
3251 $set['rc_patrolled'] = 1;
3254 if ( count( $set ) ) {
3255 $dbw->update( 'recentchanges', $set,
3257 'rc_cur_id' => $current->getPage(),
3258 'rc_user_text' => $current->getUserText(),
3259 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3265 if ( !$status->isOK() ) {
3266 return $status->getErrorsArray();
3269 // raise error, when the edit is an edit without a new version
3270 $statusRev = isset( $status->value
['revision'] )
3271 ?
$status->value
['revision']
3273 if ( !( $statusRev instanceof Revision
) ) {
3274 $resultDetails = [ 'current' => $current ];
3275 return [ [ 'alreadyrolled',
3276 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3277 htmlspecialchars( $fromP ),
3278 htmlspecialchars( $current->getUserText() )
3282 if ( $changingContentModel ) {
3283 // If the content model changed during the rollback,
3284 // make sure it gets logged to Special:Log/contentmodel
3285 $log = new ManualLogEntry( 'contentmodel', 'change' );
3286 $log->setPerformer( $guser );
3287 $log->setTarget( $this->mTitle
);
3288 $log->setComment( $summary );
3289 $log->setParameters( [
3290 '4::oldmodel' => $current->getContentModel(),
3291 '5::newmodel' => $targetContent->getModel(),
3294 $logId = $log->insert( $dbw );
3295 $log->publish( $logId );
3298 $revId = $statusRev->getId();
3300 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3303 'summary' => $summary,
3304 'current' => $current,
3305 'target' => $target,
3314 * The onArticle*() functions are supposed to be a kind of hooks
3315 * which should be called whenever any of the specified actions
3318 * This is a good place to put code to clear caches, for instance.
3320 * This is called on page move and undelete, as well as edit
3322 * @param Title $title
3324 public static function onArticleCreate( Title
$title ) {
3325 // Update existence markers on article/talk tabs...
3326 $other = $title->getOtherPage();
3328 $other->purgeSquid();
3330 $title->touchLinks();
3331 $title->purgeSquid();
3332 $title->deleteTitleProtection();
3334 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3336 // Invalidate caches of articles which include this page
3337 DeferredUpdates
::addUpdate(
3338 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3341 if ( $title->getNamespace() == NS_CATEGORY
) {
3342 // Load the Category object, which will schedule a job to create
3343 // the category table row if necessary. Checking a replica DB is ok
3344 // here, in the worst case it'll run an unnecessary recount job on
3345 // a category that probably doesn't have many members.
3346 Category
::newFromTitle( $title )->getID();
3351 * Clears caches when article is deleted
3353 * @param Title $title
3355 public static function onArticleDelete( Title
$title ) {
3356 // Update existence markers on article/talk tabs...
3357 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3358 BacklinkCache
::get( $title )->clear();
3359 $other = $title->getOtherPage();
3361 $other->purgeSquid();
3363 $title->touchLinks();
3364 $title->purgeSquid();
3366 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3369 HTMLFileCache
::clearFileCache( $title );
3370 InfoAction
::invalidateCache( $title );
3373 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3374 MessageCache
::singleton()->updateMessageOverride( $title, null );
3378 if ( $title->getNamespace() == NS_FILE
) {
3379 DeferredUpdates
::addUpdate(
3380 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3385 if ( $title->getNamespace() == NS_USER_TALK
) {
3386 $user = User
::newFromName( $title->getText(), false );
3388 $user->setNewtalk( false );
3393 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3397 * Purge caches on page update etc
3399 * @param Title $title
3400 * @param Revision|null $revision Revision that was just saved, may be null
3402 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3403 // Invalidate caches of articles which include this page
3404 DeferredUpdates
::addUpdate(
3405 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3408 // Invalidate the caches of all pages which redirect here
3409 DeferredUpdates
::addUpdate(
3410 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3413 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3415 // Purge CDN for this page only
3416 $title->purgeSquid();
3417 // Clear file cache for this page only
3418 HTMLFileCache
::clearFileCache( $title );
3420 $revid = $revision ?
$revision->getId() : null;
3421 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3422 InfoAction
::invalidateCache( $title, $revid );
3429 * Returns a list of categories this page is a member of.
3430 * Results will include hidden categories
3432 * @return TitleArray
3434 public function getCategories() {
3435 $id = $this->getId();
3437 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3440 $dbr = wfGetDB( DB_REPLICA
);
3441 $res = $dbr->select( 'categorylinks',
3442 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3443 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3444 // as not being aliases, and NS_CATEGORY is numeric
3445 [ 'cl_from' => $id ],
3448 return TitleArray
::newFromResult( $res );
3452 * Returns a list of hidden categories this page is a member of.
3453 * Uses the page_props and categorylinks tables.
3455 * @return array Array of Title objects
3457 public function getHiddenCategories() {
3459 $id = $this->getId();
3465 $dbr = wfGetDB( DB_REPLICA
);
3466 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3468 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3469 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3472 if ( $res !== false ) {
3473 foreach ( $res as $row ) {
3474 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3482 * Auto-generates a deletion reason
3484 * @param bool &$hasHistory Whether the page has a history
3485 * @return string|bool String containing deletion reason or empty string, or boolean false
3486 * if no revision occurred
3488 public function getAutoDeleteReason( &$hasHistory ) {
3489 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3493 * Update all the appropriate counts in the category table, given that
3494 * we've added the categories $added and deleted the categories $deleted.
3496 * This should only be called from deferred updates or jobs to avoid contention.
3498 * @param array $added The names of categories that were added
3499 * @param array $deleted The names of categories that were deleted
3500 * @param int $id Page ID (this should be the original deleted page ID)
3502 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3503 $id = $id ?
: $this->getId();
3504 $ns = $this->getTitle()->getNamespace();
3506 $addFields = [ 'cat_pages = cat_pages + 1' ];
3507 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3508 if ( $ns == NS_CATEGORY
) {
3509 $addFields[] = 'cat_subcats = cat_subcats + 1';
3510 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3511 } elseif ( $ns == NS_FILE
) {
3512 $addFields[] = 'cat_files = cat_files + 1';
3513 $removeFields[] = 'cat_files = cat_files - 1';
3516 $dbw = wfGetDB( DB_MASTER
);
3518 if ( count( $added ) ) {
3519 $existingAdded = $dbw->selectFieldValues(
3522 [ 'cat_title' => $added ],
3526 // For category rows that already exist, do a plain
3527 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3528 // to avoid creating gaps in the cat_id sequence.
3529 if ( count( $existingAdded ) ) {
3533 [ 'cat_title' => $existingAdded ],
3538 $missingAdded = array_diff( $added, $existingAdded );
3539 if ( count( $missingAdded ) ) {
3541 foreach ( $missingAdded as $cat ) {
3543 'cat_title' => $cat,
3545 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3546 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3559 if ( count( $deleted ) ) {
3563 [ 'cat_title' => $deleted ],
3568 foreach ( $added as $catName ) {
3569 $cat = Category
::newFromName( $catName );
3570 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3573 foreach ( $deleted as $catName ) {
3574 $cat = Category
::newFromName( $catName );
3575 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3578 // Refresh counts on categories that should be empty now, to
3579 // trigger possible deletion. Check master for the most
3580 // up-to-date cat_pages.
3581 if ( count( $deleted ) ) {
3582 $rows = $dbw->select(
3584 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3585 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3588 foreach ( $rows as $row ) {
3589 $cat = Category
::newFromRow( $row );
3590 // T166757: do the update after this DB commit
3591 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3592 $cat->refreshCounts();
3599 * Opportunistically enqueue link update jobs given fresh parser output if useful
3601 * @param ParserOutput $parserOutput Current version page output
3604 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3605 if ( wfReadOnly() ) {
3609 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3610 [ $this, $this->mTitle
, $parserOutput ]
3615 $config = RequestContext
::getMain()->getConfig();
3618 'isOpportunistic' => true,
3619 'rootJobTimestamp' => $parserOutput->getCacheTime()
3622 if ( $this->mTitle
->areRestrictionsCascading() ) {
3623 // If the page is cascade protecting, the links should really be up-to-date
3624 JobQueueGroup
::singleton()->lazyPush(
3625 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3627 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3628 // Assume the output contains "dynamic" time/random based magic words.
3629 // Only update pages that expired due to dynamic content and NOT due to edits
3630 // to referenced templates/files. When the cache expires due to dynamic content,
3631 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3632 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3633 // template/file edit already triggered recursive RefreshLinksJob jobs.
3634 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3635 // If a page is uncacheable, do not keep spamming a job for it.
3636 // Although it would be de-duplicated, it would still waste I/O.
3637 $cache = ObjectCache
::getLocalClusterInstance();
3638 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3639 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3640 if ( $cache->add( $key, time(), $ttl ) ) {
3641 JobQueueGroup
::singleton()->lazyPush(
3642 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3650 * Returns a list of updates to be performed when this page is deleted. The
3651 * updates should remove any information about this page from secondary data
3652 * stores such as links tables.
3654 * @param Content|null $content Optional Content object for determining the
3655 * necessary updates.
3656 * @return DeferrableUpdate[]
3658 public function getDeletionUpdates( Content
$content = null ) {
3660 // load content object, which may be used to determine the necessary updates.
3661 // XXX: the content may not be needed to determine the updates.
3663 $content = $this->getContent( Revision
::RAW
);
3664 } catch ( Exception
$ex ) {
3665 // If we can't load the content, something is wrong. Perhaps that's why
3666 // the user is trying to delete the page, so let's not fail in that case.
3667 // Note that doDeleteArticleReal() will already have logged an issue with
3668 // loading the content.
3675 $updates = $content->getDeletionUpdates( $this );
3678 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3683 * Whether this content displayed on this page
3684 * comes from the local database
3689 public function isLocal() {
3694 * The display name for the site this content
3695 * come from. If a subclass overrides isLocal(),
3696 * this could return something other than the
3702 public function getWikiDisplayName() {
3708 * Get the source URL for the content on this page,
3709 * typically the canonical URL, but may be a remote
3710 * link if the content comes from another site
3715 public function getSourceURL() {
3716 return $this->getTitle()->getCanonicalURL();
3720 * @param WANObjectCache $cache
3724 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3725 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3727 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );