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\Logger\LoggerFactory
;
24 use \MediaWiki\MediaWikiServices
;
27 * Class representing a MediaWiki article and history.
29 * Some fields are public only for backwards-compatibility. Use accessors.
30 * In the past, this class was part of Article.php and everything was public.
32 class WikiPage
implements Page
, IDBAccessObject
{
33 // Constants for $mDataLoadedFrom and related
38 public $mTitle = null;
43 public $mDataLoaded = false; // !< Boolean
44 public $mIsRedirect = false; // !< Boolean
45 public $mLatest = false; // !< Integer (false means "not loaded")
48 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
49 public $mPreparedEdit = false;
54 protected $mId = null;
57 * @var int One of the READ_* constants
59 protected $mDataLoadedFrom = self
::READ_NONE
;
64 protected $mRedirectTarget = null;
69 protected $mLastRevision = null;
72 * @var string Timestamp of the current revision or empty string if not loaded
74 protected $mTimestamp = '';
79 protected $mTouched = '19700101000000';
84 protected $mLinksUpdated = '19700101000000';
86 const PURGE_CDN_CACHE
= 1; // purge CDN cache for page variant URLs
87 const PURGE_CLUSTER_PCACHE
= 2; // purge parser cache in the local datacenter
88 const PURGE_GLOBAL_PCACHE
= 4; // set page_touched to clear parser cache in all datacenters
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title
$title ) {
96 $this->mTitle
= $title;
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
103 public function __clone() {
104 $this->mTitle
= clone $this->mTitle
;
108 * Create a WikiPage object of the appropriate class for the given title.
110 * @param Title $title
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
115 public static function factory( Title
$title ) {
116 $ns = $title->getNamespace();
118 if ( $ns == NS_MEDIA
) {
119 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
120 } elseif ( $ns < 0 ) {
121 throw new MWException( "Invalid or virtual namespace $ns given." );
126 $page = new WikiFilePage( $title );
129 $page = new WikiCategoryPage( $title );
132 $page = new WikiPage( $title );
139 * Constructor from a page id
141 * @param int $id Article ID to load
142 * @param string|int $from One of the following values:
143 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
144 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
146 * @return WikiPage|null
148 public static function newFromID( $id, $from = 'fromdb' ) {
149 // page id's are never 0 or negative, see bug 61166
154 $from = self
::convertSelectType( $from );
155 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
156 $row = $db->selectRow(
157 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
161 return self
::newFromRow( $row, $from );
165 * Constructor from a database row
168 * @param object $row Database row containing at least fields returned by selectFields().
169 * @param string|int $from Source of $data:
170 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
171 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
172 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
175 public static function newFromRow( $row, $from = 'fromdb' ) {
176 $page = self
::factory( Title
::newFromRow( $row ) );
177 $page->loadFromRow( $row, $from );
182 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
184 * @param object|string|int $type
187 private static function convertSelectType( $type ) {
190 return self
::READ_NORMAL
;
192 return self
::READ_LATEST
;
194 return self
::READ_LOCKING
;
196 // It may already be an integer or whatever else
202 * @todo Move this UI stuff somewhere else
204 * @see ContentHandler::getActionOverrides
206 public function getActionOverrides() {
207 return $this->getContentHandler()->getActionOverrides();
211 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
213 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
215 * @return ContentHandler
219 public function getContentHandler() {
220 return ContentHandler
::getForModelID( $this->getContentModel() );
224 * Get the title object of the article
225 * @return Title Title object of this page
227 public function getTitle() {
228 return $this->mTitle
;
235 public function clear() {
236 $this->mDataLoaded
= false;
237 $this->mDataLoadedFrom
= self
::READ_NONE
;
239 $this->clearCacheFields();
243 * Clear the object cache fields
246 protected function clearCacheFields() {
248 $this->mRedirectTarget
= null; // Title object if set
249 $this->mLastRevision
= null; // Latest revision
250 $this->mTouched
= '19700101000000';
251 $this->mLinksUpdated
= '19700101000000';
252 $this->mTimestamp
= '';
253 $this->mIsRedirect
= false;
254 $this->mLatest
= false;
255 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
256 // the requested rev ID and content against the cached one for equality. For most
257 // content types, the output should not change during the lifetime of this cache.
258 // Clearing it can cause extra parses on edit for no reason.
262 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
266 public function clearPreparedEdit() {
267 $this->mPreparedEdit
= false;
271 * Return the list of revision fields that should be selected to create
276 public static function selectFields() {
277 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
288 'page_links_updated',
293 if ( $wgContentHandlerUseDB ) {
294 $fields[] = 'page_content_model';
297 if ( $wgPageLanguageUseDB ) {
298 $fields[] = 'page_lang';
305 * Fetch a page record with the given conditions
306 * @param IDatabase $dbr
307 * @param array $conditions
308 * @param array $options
309 * @return object|bool Database result resource, or false on failure
311 protected function pageData( $dbr, $conditions, $options = [] ) {
312 $fields = self
::selectFields();
314 Hooks
::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
318 Hooks
::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
327 * @param IDatabase $dbr
328 * @param Title $title
329 * @param array $options
330 * @return object|bool Database result resource, or false on failure
332 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
333 return $this->pageData( $dbr, [
334 'page_namespace' => $title->getNamespace(),
335 'page_title' => $title->getDBkey() ], $options );
339 * Fetch a page record matching the requested ID
341 * @param IDatabase $dbr
343 * @param array $options
344 * @return object|bool Database result resource, or false on failure
346 public function pageDataFromId( $dbr, $id, $options = [] ) {
347 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
351 * Load the object from a given source by title
353 * @param object|string|int $from One of the following:
354 * - A DB query result object.
355 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
356 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
357 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
358 * using SELECT FOR UPDATE.
362 public function loadPageData( $from = 'fromdb' ) {
363 $from = self
::convertSelectType( $from );
364 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
365 // We already have the data from the correct location, no need to load it twice.
369 if ( is_int( $from ) ) {
370 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
371 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
374 && $index == DB_REPLICA
375 && wfGetLB()->getServerCount() > 1
376 && wfGetLB()->hasOrMadeRecentMasterChanges()
378 $from = self
::READ_LATEST
;
379 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
380 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
383 // No idea from where the caller got this data, assume replica DB.
385 $from = self
::READ_NORMAL
;
388 $this->loadFromRow( $data, $from );
392 * Load the object from a database row
395 * @param object|bool $data DB row containing fields returned by selectFields() or false
396 * @param string|int $from One of the following:
397 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
398 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
399 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
400 * the master DB using SELECT FOR UPDATE
402 public function loadFromRow( $data, $from ) {
403 $lc = LinkCache
::singleton();
404 $lc->clearLink( $this->mTitle
);
407 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
409 $this->mTitle
->loadFromRow( $data );
411 // Old-fashioned restrictions
412 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
414 $this->mId
= intval( $data->page_id
);
415 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
416 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
417 $this->mIsRedirect
= intval( $data->page_is_redirect
);
418 $this->mLatest
= intval( $data->page_latest
);
419 // Bug 37225: $latest may no longer match the cached latest Revision object.
420 // Double-check the ID of any cached latest Revision object for consistency.
421 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
422 $this->mLastRevision
= null;
423 $this->mTimestamp
= '';
426 $lc->addBadLinkObj( $this->mTitle
);
428 $this->mTitle
->loadFromRow( false );
430 $this->clearCacheFields();
435 $this->mDataLoaded
= true;
436 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
440 * @return int Page ID
442 public function getId() {
443 if ( !$this->mDataLoaded
) {
444 $this->loadPageData();
450 * @return bool Whether or not the page exists in the database
452 public function exists() {
453 if ( !$this->mDataLoaded
) {
454 $this->loadPageData();
456 return $this->mId
> 0;
460 * Check if this page is something we're going to be showing
461 * some sort of sensible content for. If we return false, page
462 * views (plain action=view) will return an HTTP 404 response,
463 * so spiders and robots can know they're following a bad link.
467 public function hasViewableContent() {
468 return $this->mTitle
->isKnown();
472 * Tests if the article content represents a redirect
476 public function isRedirect() {
477 if ( !$this->mDataLoaded
) {
478 $this->loadPageData();
481 return (bool)$this->mIsRedirect
;
485 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
487 * Will use the revisions actual content model if the page exists,
488 * and the page's default if the page doesn't exist yet.
494 public function getContentModel() {
495 if ( $this->exists() ) {
496 $cache = ObjectCache
::getMainWANInstance();
498 return $cache->getWithSetCallback(
499 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
502 $rev = $this->getRevision();
504 // Look at the revision's actual content model
505 return $rev->getContentModel();
507 $title = $this->mTitle
->getPrefixedDBkey();
508 wfWarn( "Page $title exists but has no (visible) revisions!" );
509 return $this->mTitle
->getContentModel();
515 // use the default model for this page
516 return $this->mTitle
->getContentModel();
520 * Loads page_touched and returns a value indicating if it should be used
521 * @return bool True if this page exists and is not a redirect
523 public function checkTouched() {
524 if ( !$this->mDataLoaded
) {
525 $this->loadPageData();
527 return ( $this->mId
&& !$this->mIsRedirect
);
531 * Get the page_touched field
532 * @return string Containing GMT timestamp
534 public function getTouched() {
535 if ( !$this->mDataLoaded
) {
536 $this->loadPageData();
538 return $this->mTouched
;
542 * Get the page_links_updated field
543 * @return string|null Containing GMT timestamp
545 public function getLinksTimestamp() {
546 if ( !$this->mDataLoaded
) {
547 $this->loadPageData();
549 return $this->mLinksUpdated
;
553 * Get the page_latest field
554 * @return int The rev_id of current revision
556 public function getLatest() {
557 if ( !$this->mDataLoaded
) {
558 $this->loadPageData();
560 return (int)$this->mLatest
;
564 * Get the Revision object of the oldest revision
565 * @return Revision|null
567 public function getOldestRevision() {
569 // Try using the replica DB first, then try the master
571 $db = wfGetDB( DB_REPLICA
);
572 $revSelectFields = Revision
::selectFields();
575 while ( $continue ) {
576 $row = $db->selectRow(
577 [ 'page', 'revision' ],
580 'page_namespace' => $this->mTitle
->getNamespace(),
581 'page_title' => $this->mTitle
->getDBkey(),
586 'ORDER BY' => 'rev_timestamp ASC'
593 $db = wfGetDB( DB_MASTER
);
598 return $row ? Revision
::newFromRow( $row ) : null;
602 * Loads everything except the text
603 * This isn't necessary for all uses, so it's only done if needed.
605 protected function loadLastEdit() {
606 if ( $this->mLastRevision
!== null ) {
607 return; // already loaded
610 $latest = $this->getLatest();
612 return; // page doesn't exist or is missing page_latest info
615 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
616 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
617 // includes the latest changes committed. This is true even within REPEATABLE-READ
618 // transactions, where S1 normally only sees changes committed before the first S1
619 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
620 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
621 // happened after the first S1 SELECT.
622 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
623 $flags = Revision
::READ_LOCKING
;
624 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
625 // Bug T93976: if page_latest was loaded from the master, fetch the
626 // revision from there as well, as it may not exist yet on a replica DB.
627 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
628 $flags = Revision
::READ_LATEST
;
632 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
633 if ( $revision ) { // sanity
634 $this->setLastEdit( $revision );
639 * Set the latest revision
640 * @param Revision $revision
642 protected function setLastEdit( Revision
$revision ) {
643 $this->mLastRevision
= $revision;
644 $this->mTimestamp
= $revision->getTimestamp();
648 * Get the latest revision
649 * @return Revision|null
651 public function getRevision() {
652 $this->loadLastEdit();
653 if ( $this->mLastRevision
) {
654 return $this->mLastRevision
;
660 * Get the content of the current revision. No side-effects...
662 * @param int $audience One of:
663 * Revision::FOR_PUBLIC to be displayed to all users
664 * Revision::FOR_THIS_USER to be displayed to $wgUser
665 * Revision::RAW get the text regardless of permissions
666 * @param User $user User object to check for, only if FOR_THIS_USER is passed
667 * to the $audience parameter
668 * @return Content|null The content of the current revision
672 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
673 $this->loadLastEdit();
674 if ( $this->mLastRevision
) {
675 return $this->mLastRevision
->getContent( $audience, $user );
681 * Get the text of the current revision. No side-effects...
683 * @param int $audience One of:
684 * Revision::FOR_PUBLIC to be displayed to all users
685 * Revision::FOR_THIS_USER to be displayed to the given user
686 * Revision::RAW get the text regardless of permissions
687 * @param User $user User object to check for, only if FOR_THIS_USER is passed
688 * to the $audience parameter
689 * @return string|bool The text of the current revision
690 * @deprecated since 1.21, getContent() should be used instead.
692 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
693 ContentHandler
::deprecated( __METHOD__
, '1.21' );
695 $this->loadLastEdit();
696 if ( $this->mLastRevision
) {
697 return $this->mLastRevision
->getText( $audience, $user );
703 * @return string MW timestamp of last article revision
705 public function getTimestamp() {
706 // Check if the field has been filled by WikiPage::setTimestamp()
707 if ( !$this->mTimestamp
) {
708 $this->loadLastEdit();
711 return wfTimestamp( TS_MW
, $this->mTimestamp
);
715 * Set the page timestamp (use only to avoid DB queries)
716 * @param string $ts MW timestamp of last article revision
719 public function setTimestamp( $ts ) {
720 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
724 * @param int $audience One of:
725 * Revision::FOR_PUBLIC to be displayed to all users
726 * Revision::FOR_THIS_USER to be displayed to the given user
727 * Revision::RAW get the text regardless of permissions
728 * @param User $user User object to check for, only if FOR_THIS_USER is passed
729 * to the $audience parameter
730 * @return int User ID for the user that made the last article revision
732 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
733 $this->loadLastEdit();
734 if ( $this->mLastRevision
) {
735 return $this->mLastRevision
->getUser( $audience, $user );
742 * Get the User object of the user who created the page
743 * @param int $audience One of:
744 * Revision::FOR_PUBLIC to be displayed to all users
745 * Revision::FOR_THIS_USER to be displayed to the given user
746 * Revision::RAW get the text regardless of permissions
747 * @param User $user User object to check for, only if FOR_THIS_USER is passed
748 * to the $audience parameter
751 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
752 $revision = $this->getOldestRevision();
754 $userName = $revision->getUserText( $audience, $user );
755 return User
::newFromName( $userName, false );
762 * @param int $audience One of:
763 * Revision::FOR_PUBLIC to be displayed to all users
764 * Revision::FOR_THIS_USER to be displayed to the given user
765 * Revision::RAW get the text regardless of permissions
766 * @param User $user User object to check for, only if FOR_THIS_USER is passed
767 * to the $audience parameter
768 * @return string Username of the user that made the last article revision
770 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
771 $this->loadLastEdit();
772 if ( $this->mLastRevision
) {
773 return $this->mLastRevision
->getUserText( $audience, $user );
780 * @param int $audience One of:
781 * Revision::FOR_PUBLIC to be displayed to all users
782 * Revision::FOR_THIS_USER to be displayed to the given user
783 * Revision::RAW get the text regardless of permissions
784 * @param User $user User object to check for, only if FOR_THIS_USER is passed
785 * to the $audience parameter
786 * @return string Comment stored for the last article revision
788 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
789 $this->loadLastEdit();
790 if ( $this->mLastRevision
) {
791 return $this->mLastRevision
->getComment( $audience, $user );
798 * Returns true if last revision was marked as "minor edit"
800 * @return bool Minor edit indicator for the last article revision.
802 public function getMinorEdit() {
803 $this->loadLastEdit();
804 if ( $this->mLastRevision
) {
805 return $this->mLastRevision
->isMinor();
812 * Determine whether a page would be suitable for being counted as an
813 * article in the site_stats table based on the title & its content
815 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
816 * if false, the current database state will be used
819 public function isCountable( $editInfo = false ) {
820 global $wgArticleCountMethod;
822 if ( !$this->mTitle
->isContentPage() ) {
827 $content = $editInfo->pstContent
;
829 $content = $this->getContent();
832 if ( !$content ||
$content->isRedirect() ) {
838 if ( $wgArticleCountMethod === 'link' ) {
839 // nasty special case to avoid re-parsing to detect links
842 // ParserOutput::getLinks() is a 2D array of page links, so
843 // to be really correct we would need to recurse in the array
844 // but the main array should only have items in it if there are
846 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
848 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
849 [ 'pl_from' => $this->getId() ], __METHOD__
);
853 return $content->isCountable( $hasLinks );
857 * If this page is a redirect, get its target
859 * The target will be fetched from the redirect table if possible.
860 * If this page doesn't have an entry there, call insertRedirect()
861 * @return Title|null Title object, or null if this page is not a redirect
863 public function getRedirectTarget() {
864 if ( !$this->mTitle
->isRedirect() ) {
868 if ( $this->mRedirectTarget
!== null ) {
869 return $this->mRedirectTarget
;
872 // Query the redirect table
873 $dbr = wfGetDB( DB_REPLICA
);
874 $row = $dbr->selectRow( 'redirect',
875 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
876 [ 'rd_from' => $this->getId() ],
880 // rd_fragment and rd_interwiki were added later, populate them if empty
881 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
882 $this->mRedirectTarget
= Title
::makeTitle(
883 $row->rd_namespace
, $row->rd_title
,
884 $row->rd_fragment
, $row->rd_interwiki
886 return $this->mRedirectTarget
;
889 // This page doesn't have an entry in the redirect table
890 $this->mRedirectTarget
= $this->insertRedirect();
891 return $this->mRedirectTarget
;
895 * Insert an entry for this page into the redirect table if the content is a redirect
897 * The database update will be deferred via DeferredUpdates
899 * Don't call this function directly unless you know what you're doing.
900 * @return Title|null Title object or null if not a redirect
902 public function insertRedirect() {
903 $content = $this->getContent();
904 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
909 // Update the DB post-send if the page has not cached since now
911 $latest = $this->getLatest();
912 DeferredUpdates
::addCallableUpdate(
913 function () use ( $that, $retval, $latest ) {
914 $that->insertRedirectEntry( $retval, $latest );
916 DeferredUpdates
::POSTSEND
,
924 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
925 * @param Title $rt Redirect target
926 * @param int|null $oldLatest Prior page_latest for check and set
928 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
929 $dbw = wfGetDB( DB_MASTER
);
930 $dbw->startAtomic( __METHOD__
);
932 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
933 $dbw->replace( 'redirect',
936 'rd_from' => $this->getId(),
937 'rd_namespace' => $rt->getNamespace(),
938 'rd_title' => $rt->getDBkey(),
939 'rd_fragment' => $rt->getFragment(),
940 'rd_interwiki' => $rt->getInterwiki(),
946 $dbw->endAtomic( __METHOD__
);
950 * Get the Title object or URL this page redirects to
952 * @return bool|Title|string False, Title of in-wiki target, or string with URL
954 public function followRedirect() {
955 return $this->getRedirectURL( $this->getRedirectTarget() );
959 * Get the Title object or URL to use for a redirect. We use Title
960 * objects for same-wiki, non-special redirects and URLs for everything
962 * @param Title $rt Redirect target
963 * @return bool|Title|string False, Title object of local target, or string with URL
965 public function getRedirectURL( $rt ) {
970 if ( $rt->isExternal() ) {
971 if ( $rt->isLocal() ) {
972 // Offsite wikis need an HTTP redirect.
973 // This can be hard to reverse and may produce loops,
974 // so they may be disabled in the site configuration.
975 $source = $this->mTitle
->getFullURL( 'redirect=no' );
976 return $rt->getFullURL( [ 'rdfrom' => $source ] );
978 // External pages without "local" bit set are not valid
984 if ( $rt->isSpecialPage() ) {
985 // Gotta handle redirects to special pages differently:
986 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
987 // Some pages are not valid targets.
988 if ( $rt->isValidRedirectTarget() ) {
989 return $rt->getFullURL();
999 * Get a list of users who have edited this article, not including the user who made
1000 * the most recent revision, which you can get from $article->getUser() if you want it
1001 * @return UserArrayFromResult
1003 public function getContributors() {
1004 // @todo FIXME: This is expensive; cache this info somewhere.
1006 $dbr = wfGetDB( DB_REPLICA
);
1008 if ( $dbr->implicitGroupby() ) {
1009 $realNameField = 'user_real_name';
1011 $realNameField = 'MIN(user_real_name) AS user_real_name';
1014 $tables = [ 'revision', 'user' ];
1017 'user_id' => 'rev_user',
1018 'user_name' => 'rev_user_text',
1020 'timestamp' => 'MAX(rev_timestamp)',
1023 $conds = [ 'rev_page' => $this->getId() ];
1025 // The user who made the top revision gets credited as "this page was last edited by
1026 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1027 $user = $this->getUser();
1029 $conds[] = "rev_user != $user";
1031 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1035 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1038 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1042 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1043 'ORDER BY' => 'timestamp DESC',
1046 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1047 return new UserArrayFromResult( $res );
1051 * Should the parser cache be used?
1053 * @param ParserOptions $parserOptions ParserOptions to check
1057 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1058 return $parserOptions->getStubThreshold() == 0
1060 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1061 && $this->getContentHandler()->isParserCacheSupported();
1065 * Get a ParserOutput for the given ParserOptions and revision ID.
1067 * The parser cache will be used if possible. Cache misses that result
1068 * in parser runs are debounced with PoolCounter.
1071 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1072 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1073 * get the current revision (default value)
1074 * @param bool $forceParse Force reindexing, regardless of cache settings
1075 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1077 public function getParserOutput(
1078 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1081 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1082 wfDebug( __METHOD__
.
1083 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1084 if ( $parserOptions->getStubThreshold() ) {
1085 wfIncrStats( 'pcache.miss.stub' );
1088 if ( $useParserCache ) {
1089 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1090 if ( $parserOutput !== false ) {
1091 return $parserOutput;
1095 if ( $oldid === null ||
$oldid === 0 ) {
1096 $oldid = $this->getLatest();
1099 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1102 return $pool->getParserOutput();
1106 * Do standard deferred updates after page view (existing or missing page)
1107 * @param User $user The relevant user
1108 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1110 public function doViewUpdates( User
$user, $oldid = 0 ) {
1111 if ( wfReadOnly() ) {
1115 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1116 // Update newtalk / watchlist notification status
1118 $user->clearNotification( $this->mTitle
, $oldid );
1119 } catch ( DBError
$e ) {
1120 // Avoid outage if the master is not reachable
1121 MWExceptionHandler
::logException( $e );
1126 * Perform the actions of a page purging
1127 * @param integer $flags Bitfield of WikiPage::PURGE_* constants
1130 public function doPurge( $flags = self
::PURGE_ALL
) {
1131 if ( !Hooks
::run( 'ArticlePurge', [ &$this ] ) ) {
1135 if ( ( $flags & self
::PURGE_GLOBAL_PCACHE
) == self
::PURGE_GLOBAL_PCACHE
) {
1136 // Set page_touched in the database to invalidate all DC caches
1137 $this->mTitle
->invalidateCache();
1138 } elseif ( ( $flags & self
::PURGE_CLUSTER_PCACHE
) == self
::PURGE_CLUSTER_PCACHE
) {
1139 // Delete the parser options key in the local cluster to invalidate the DC cache
1140 ParserCache
::singleton()->deleteOptionsKey( $this );
1141 // Avoid sending HTTP 304s in ViewAction to the client who just issued the purge
1142 $cache = ObjectCache
::getLocalClusterInstance();
1144 $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ),
1145 wfTimestamp( TS_MW
),
1150 if ( ( $flags & self
::PURGE_CDN_CACHE
) == self
::PURGE_CDN_CACHE
) {
1151 // Clear any HTML file cache
1152 HTMLFileCache
::clearFileCache( $this->getTitle() );
1153 // Send purge after any page_touched above update was committed
1154 DeferredUpdates
::addUpdate(
1155 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1156 DeferredUpdates
::PRESEND
1160 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1161 // @todo move this logic to MessageCache
1162 if ( $this->exists() ) {
1163 // NOTE: use transclusion text for messages.
1164 // This is consistent with MessageCache::getMsgFromNamespace()
1166 $content = $this->getContent();
1167 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1169 if ( $text === null ) {
1176 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1183 * Get the last time a user explicitly purged the page via action=purge
1185 * @return string|bool TS_MW timestamp or false
1188 public function getLastPurgeTimestamp() {
1189 $cache = ObjectCache
::getLocalClusterInstance();
1191 return $cache->get( $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ) );
1195 * Insert a new empty page record for this article.
1196 * This *must* be followed up by creating a revision
1197 * and running $this->updateRevisionOn( ... );
1198 * or else the record will be left in a funky state.
1199 * Best if all done inside a transaction.
1201 * @param IDatabase $dbw
1202 * @param int|null $pageId Custom page ID that will be used for the insert statement
1204 * @return bool|int The newly created page_id key; false if the row was not
1205 * inserted, e.g. because the title already existed or because the specified
1206 * page ID is already in use.
1208 public function insertOn( $dbw, $pageId = null ) {
1209 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1213 'page_id' => $pageIdForInsert,
1214 'page_namespace' => $this->mTitle
->getNamespace(),
1215 'page_title' => $this->mTitle
->getDBkey(),
1216 'page_restrictions' => '',
1217 'page_is_redirect' => 0, // Will set this shortly...
1219 'page_random' => wfRandom(),
1220 'page_touched' => $dbw->timestamp(),
1221 'page_latest' => 0, // Fill this in shortly...
1222 'page_len' => 0, // Fill this in shortly...
1228 if ( $dbw->affectedRows() > 0 ) {
1229 $newid = $pageId ?
: $dbw->insertId();
1230 $this->mId
= $newid;
1231 $this->mTitle
->resetArticleID( $newid );
1235 return false; // nothing changed
1240 * Update the page record to point to a newly saved revision.
1242 * @param IDatabase $dbw
1243 * @param Revision $revision For ID number, and text used to set
1244 * length and redirect status fields
1245 * @param int $lastRevision If given, will not overwrite the page field
1246 * when different from the currently set value.
1247 * Giving 0 indicates the new page flag should be set on.
1248 * @param bool $lastRevIsRedirect If given, will optimize adding and
1249 * removing rows in redirect table.
1250 * @return bool Success; false if the page row was missing or page_latest changed
1252 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1253 $lastRevIsRedirect = null
1255 global $wgContentHandlerUseDB;
1257 // Assertion to try to catch T92046
1258 if ( (int)$revision->getId() === 0 ) {
1259 throw new InvalidArgumentException(
1260 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1264 $content = $revision->getContent();
1265 $len = $content ?
$content->getSize() : 0;
1266 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1268 $conditions = [ 'page_id' => $this->getId() ];
1270 if ( !is_null( $lastRevision ) ) {
1271 // An extra check against threads stepping on each other
1272 $conditions['page_latest'] = $lastRevision;
1276 'page_latest' => $revision->getId(),
1277 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1278 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1279 'page_is_redirect' => $rt !== null ?
1 : 0,
1283 if ( $wgContentHandlerUseDB ) {
1284 $row['page_content_model'] = $revision->getContentModel();
1287 $dbw->update( 'page',
1292 $result = $dbw->affectedRows() > 0;
1294 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1295 $this->setLastEdit( $revision );
1296 $this->mLatest
= $revision->getId();
1297 $this->mIsRedirect
= (bool)$rt;
1298 // Update the LinkCache.
1299 LinkCache
::singleton()->addGoodLinkObj(
1305 $revision->getContentModel()
1313 * Add row to the redirect table if this is a redirect, remove otherwise.
1315 * @param IDatabase $dbw
1316 * @param Title $redirectTitle Title object pointing to the redirect target,
1317 * or NULL if this is not a redirect
1318 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1319 * removing rows in redirect table.
1320 * @return bool True on success, false on failure
1323 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1324 // Always update redirects (target link might have changed)
1325 // Update/Insert if we don't know if the last revision was a redirect or not
1326 // Delete if changing from redirect to non-redirect
1327 $isRedirect = !is_null( $redirectTitle );
1329 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1333 if ( $isRedirect ) {
1334 $this->insertRedirectEntry( $redirectTitle );
1336 // This is not a redirect, remove row from redirect table
1337 $where = [ 'rd_from' => $this->getId() ];
1338 $dbw->delete( 'redirect', $where, __METHOD__
);
1341 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1342 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1345 return ( $dbw->affectedRows() != 0 );
1349 * If the given revision is newer than the currently set page_latest,
1350 * update the page record. Otherwise, do nothing.
1352 * @deprecated since 1.24, use updateRevisionOn instead
1354 * @param IDatabase $dbw
1355 * @param Revision $revision
1358 public function updateIfNewerOn( $dbw, $revision ) {
1360 $row = $dbw->selectRow(
1361 [ 'revision', 'page' ],
1362 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1364 'page_id' => $this->getId(),
1365 'page_latest=rev_id' ],
1369 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1372 $prev = $row->rev_id
;
1373 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1375 // No or missing previous revision; mark the page as new
1377 $lastRevIsRedirect = null;
1380 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1386 * Get the content that needs to be saved in order to undo all revisions
1387 * between $undo and $undoafter. Revisions must belong to the same page,
1388 * must exist and must not be deleted
1389 * @param Revision $undo
1390 * @param Revision $undoafter Must be an earlier revision than $undo
1391 * @return Content|bool Content on success, false on failure
1393 * Before we had the Content object, this was done in getUndoText
1395 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1396 $handler = $undo->getContentHandler();
1397 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1401 * Returns true if this page's content model supports sections.
1405 * @todo The skin should check this and not offer section functionality if
1406 * sections are not supported.
1407 * @todo The EditPage should check this and not offer section functionality
1408 * if sections are not supported.
1410 public function supportsSections() {
1411 return $this->getContentHandler()->supportsSections();
1415 * @param string|number|null|bool $sectionId Section identifier as a number or string
1416 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1417 * or 'new' for a new section.
1418 * @param Content $sectionContent New content of the section.
1419 * @param string $sectionTitle New section's subject, only if $section is "new".
1420 * @param string $edittime Revision timestamp or null to use the current revision.
1422 * @throws MWException
1423 * @return Content|null New complete article content, or null if error.
1426 * @deprecated since 1.24, use replaceSectionAtRev instead
1428 public function replaceSectionContent(
1429 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1433 if ( $edittime && $sectionId !== 'new' ) {
1434 $dbr = wfGetDB( DB_REPLICA
);
1435 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1436 // Try the master if this thread may have just added it.
1437 // This could be abstracted into a Revision method, but we don't want
1438 // to encourage loading of revisions by timestamp.
1440 && wfGetLB()->getServerCount() > 1
1441 && wfGetLB()->hasOrMadeRecentMasterChanges()
1443 $dbw = wfGetDB( DB_MASTER
);
1444 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1447 $baseRevId = $rev->getId();
1451 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1455 * @param string|number|null|bool $sectionId Section identifier as a number or string
1456 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1457 * or 'new' for a new section.
1458 * @param Content $sectionContent New content of the section.
1459 * @param string $sectionTitle New section's subject, only if $section is "new".
1460 * @param int|null $baseRevId
1462 * @throws MWException
1463 * @return Content|null New complete article content, or null if error.
1467 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1468 $sectionTitle = '', $baseRevId = null
1471 if ( strval( $sectionId ) === '' ) {
1472 // Whole-page edit; let the whole text through
1473 $newContent = $sectionContent;
1475 if ( !$this->supportsSections() ) {
1476 throw new MWException( "sections not supported for content model " .
1477 $this->getContentHandler()->getModelID() );
1480 // Bug 30711: always use current version when adding a new section
1481 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1482 $oldContent = $this->getContent();
1484 $rev = Revision
::newFromId( $baseRevId );
1486 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1487 $this->getId() . "; section: $sectionId)\n" );
1491 $oldContent = $rev->getContent();
1494 if ( !$oldContent ) {
1495 wfDebug( __METHOD__
. ": no page text\n" );
1499 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1506 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1508 * @return int Updated $flags
1510 public function checkFlags( $flags ) {
1511 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1512 if ( $this->exists() ) {
1513 $flags |
= EDIT_UPDATE
;
1523 * Change an existing article or create a new article. Updates RC and all necessary caches,
1524 * optionally via the deferred update array.
1526 * @param string $text New text
1527 * @param string $summary Edit summary
1528 * @param int $flags Bitfield:
1530 * Article is known or assumed to be non-existent, create a new one
1532 * Article is known or assumed to be pre-existing, update it
1534 * Mark this edit minor, if the user is allowed to do so
1536 * Do not log the change in recentchanges
1538 * Mark the edit a "bot" edit regardless of user rights
1540 * Fill in blank summaries with generated text where possible
1542 * Signal that the page retrieve/save cycle happened entirely in this request.
1544 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1545 * article will be detected. If EDIT_UPDATE is specified and the article
1546 * doesn't exist, the function will return an edit-gone-missing error. If
1547 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1548 * error will be returned. These two conditions are also possible with
1549 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1551 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1552 * This is not the parent revision ID, rather the revision ID for older
1553 * content used as the source for a rollback, for example.
1554 * @param User $user The user doing the edit
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.
1571 * Compatibility note: this function previously returned a boolean value
1572 * indicating success/failure
1574 * @deprecated since 1.21: use doEditContent() instead.
1576 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1577 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1579 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1581 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1585 * Change an existing article or create a new article. Updates RC and all necessary caches,
1586 * optionally via the deferred update array.
1588 * @param Content $content New content
1589 * @param string $summary Edit summary
1590 * @param int $flags Bitfield:
1592 * Article is known or assumed to be non-existent, create a new one
1594 * Article is known or assumed to be pre-existing, update it
1596 * Mark this edit minor, if the user is allowed to do so
1598 * Do not log the change in recentchanges
1600 * Mark the edit a "bot" edit regardless of user rights
1602 * Fill in blank summaries with generated text where possible
1604 * Signal that the page retrieve/save cycle happened entirely in this request.
1606 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1607 * article will be detected. If EDIT_UPDATE is specified and the article
1608 * doesn't exist, the function will return an edit-gone-missing error. If
1609 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1610 * error will be returned. These two conditions are also possible with
1611 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1613 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1614 * This is not the parent revision ID, rather the revision ID for older
1615 * content used as the source for a rollback, for example.
1616 * @param User $user The user doing the edit
1617 * @param string $serialFormat Format for storing the content in the
1619 * @param array|null $tags Change tags to apply to this edit
1620 * Callers are responsible for permission checks
1621 * (with ChangeTags::canAddTagsAccompanyingChange)
1623 * @throws MWException
1624 * @return Status Possible errors:
1625 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1626 * set the fatal flag of $status.
1627 * edit-gone-missing: In update mode, but the article didn't exist.
1628 * edit-conflict: In update mode, the article changed unexpectedly.
1629 * edit-no-change: Warning that the text was the same as before.
1630 * edit-already-exists: In creation mode, but the article already exists.
1632 * Extensions may define additional errors.
1634 * $return->value will contain an associative array with members as follows:
1635 * new: Boolean indicating if the function attempted to create a new article.
1636 * revision: The revision object for the inserted revision, or null.
1639 * @throws MWException
1641 public function doEditContent(
1642 Content
$content, $summary, $flags = 0, $baseRevId = false,
1643 User
$user = null, $serialFormat = null, $tags = []
1645 global $wgUser, $wgUseAutomaticEditSummaries;
1647 // Old default parameter for $tags was null
1648 if ( $tags === null ) {
1652 // Low-level sanity check
1653 if ( $this->mTitle
->getText() === '' ) {
1654 throw new MWException( 'Something is trying to edit an article with an empty title' );
1656 // Make sure the given content type is allowed for this page
1657 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1658 return Status
::newFatal( 'content-not-allowed-here',
1659 ContentHandler
::getLocalizedName( $content->getModel() ),
1660 $this->mTitle
->getPrefixedText()
1664 // Load the data from the master database if needed.
1665 // The caller may already loaded it from the master or even loaded it using
1666 // SELECT FOR UPDATE, so do not override that using clear().
1667 $this->loadPageData( 'fromdbmaster' );
1669 $user = $user ?
: $wgUser;
1670 $flags = $this->checkFlags( $flags );
1672 // Trigger pre-save hook (using provided edit summary)
1673 $hookStatus = Status
::newGood( [] );
1674 $hook_args = [ &$this, &$user, &$content, &$summary,
1675 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1676 // Check if the hook rejected the attempted save
1677 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1678 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args )
1680 if ( $hookStatus->isOK() ) {
1681 // Hook returned false but didn't call fatal(); use generic message
1682 $hookStatus->fatal( 'edit-hook-aborted' );
1688 $old_revision = $this->getRevision(); // current revision
1689 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1691 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1692 $tags[] = 'mw-contentmodelchange';
1695 // Provide autosummaries if one is not provided and autosummaries are enabled
1696 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1697 $handler = $content->getContentHandler();
1698 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1701 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1702 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1708 // Get the pre-save transform content and final parser output
1709 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1710 $pstContent = $editInfo->pstContent
; // Content object
1712 'bot' => ( $flags & EDIT_FORCE_BOT
),
1713 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1714 'serialized' => $editInfo->pst
,
1715 'serialFormat' => $serialFormat,
1716 'baseRevId' => $baseRevId,
1717 'oldRevision' => $old_revision,
1718 'oldContent' => $old_content,
1719 'oldId' => $this->getLatest(),
1720 'oldIsRedirect' => $this->isRedirect(),
1721 'oldCountable' => $this->isCountable(),
1722 'tags' => ( $tags !== null ) ?
(array)$tags : []
1725 // Actually create the revision and create/update the page
1726 if ( $flags & EDIT_UPDATE
) {
1727 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1729 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1732 // Promote user to any groups they meet the criteria for
1733 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1734 $user->addAutopromoteOnceGroups( 'onEdit' );
1735 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1742 * @param Content $content Pre-save transform content
1743 * @param integer $flags
1745 * @param string $summary
1746 * @param array $meta
1748 * @throws DBUnexpectedError
1750 * @throws FatalError
1751 * @throws MWException
1753 private function doModify(
1754 Content
$content, $flags, User
$user, $summary, array $meta
1756 global $wgUseRCPatrol;
1758 // Update article, but only if changed.
1759 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1761 // Convenience variables
1762 $now = wfTimestampNow();
1763 $oldid = $meta['oldId'];
1764 /** @var $oldContent Content|null */
1765 $oldContent = $meta['oldContent'];
1766 $newsize = $content->getSize();
1769 // Article gone missing
1770 $status->fatal( 'edit-gone-missing' );
1773 } elseif ( !$oldContent ) {
1774 // Sanity check for bug 37225
1775 throw new MWException( "Could not find text for current revision {$oldid}." );
1778 // @TODO: pass content object?!
1779 $revision = new Revision( [
1780 'page' => $this->getId(),
1781 'title' => $this->mTitle
, // for determining the default content model
1782 'comment' => $summary,
1783 'minor_edit' => $meta['minor'],
1784 'text' => $meta['serialized'],
1786 'parent_id' => $oldid,
1787 'user' => $user->getId(),
1788 'user_text' => $user->getName(),
1789 'timestamp' => $now,
1790 'content_model' => $content->getModel(),
1791 'content_format' => $meta['serialFormat'],
1794 $changed = !$content->equals( $oldContent );
1796 $dbw = wfGetDB( DB_MASTER
);
1799 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1800 $status->merge( $prepStatus );
1801 if ( !$status->isOK() ) {
1805 $dbw->startAtomic( __METHOD__
);
1806 // Get the latest page_latest value while locking it.
1807 // Do a CAS style check to see if it's the same as when this method
1808 // started. If it changed then bail out before touching the DB.
1809 $latestNow = $this->lockAndGetLatest();
1810 if ( $latestNow != $oldid ) {
1811 $dbw->endAtomic( __METHOD__
);
1812 // Page updated or deleted in the mean time
1813 $status->fatal( 'edit-conflict' );
1818 // At this point we are now comitted to returning an OK
1819 // status unless some DB query error or other exception comes up.
1820 // This way callers don't have to call rollback() if $status is bad
1821 // unless they actually try to catch exceptions (which is rare).
1823 // Save the revision text
1824 $revisionId = $revision->insertOn( $dbw );
1825 // Update page_latest and friends to reflect the new revision
1826 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1827 throw new MWException( "Failed to update page row to use new revision." );
1830 Hooks
::run( 'NewRevisionFromEditComplete',
1831 [ $this, $revision, $meta['baseRevId'], $user ] );
1833 // Update recentchanges
1834 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1835 // Mark as patrolled if the user can do so
1836 $patrolled = $wgUseRCPatrol && !count(
1837 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1838 // Add RC row to the DB
1839 RecentChange
::notifyEdit(
1842 $revision->isMinor(),
1846 $this->getTimestamp(),
1849 $oldContent ?
$oldContent->getSize() : 0,
1857 $user->incEditCount();
1859 $dbw->endAtomic( __METHOD__
);
1860 $this->mTimestamp
= $now;
1862 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1863 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1864 $revision->setId( $this->getLatest() );
1865 $revision->setUserIdAndName(
1866 $this->getUser( Revision
::RAW
),
1867 $this->getUserText( Revision
::RAW
)
1872 // Return the new revision to the caller
1873 $status->value
['revision'] = $revision;
1875 $status->warning( 'edit-no-change' );
1876 // Update page_touched as updateRevisionOn() was not called.
1877 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1878 $this->mTitle
->invalidateCache( $now );
1881 // Do secondary updates once the main changes have been committed...
1882 DeferredUpdates
::addUpdate(
1883 new AtomicSectionUpdate(
1887 $revision, &$user, $content, $summary, &$flags,
1888 $changed, $meta, &$status
1890 // Update links tables, site stats, etc.
1891 $this->doEditUpdates(
1895 'changed' => $changed,
1896 'oldcountable' => $meta['oldCountable'],
1897 'oldrevision' => $meta['oldRevision']
1900 // Trigger post-save hook
1901 $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR
,
1902 null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1903 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
1904 Hooks
::run( 'PageContentSaveComplete', $params );
1907 DeferredUpdates
::PRESEND
1914 * @param Content $content Pre-save transform content
1915 * @param integer $flags
1917 * @param string $summary
1918 * @param array $meta
1920 * @throws DBUnexpectedError
1922 * @throws FatalError
1923 * @throws MWException
1925 private function doCreate(
1926 Content
$content, $flags, User
$user, $summary, array $meta
1928 global $wgUseRCPatrol, $wgUseNPPatrol;
1930 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1932 $now = wfTimestampNow();
1933 $newsize = $content->getSize();
1934 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1935 $status->merge( $prepStatus );
1936 if ( !$status->isOK() ) {
1940 $dbw = wfGetDB( DB_MASTER
);
1941 $dbw->startAtomic( __METHOD__
);
1943 // Add the page record unless one already exists for the title
1944 $newid = $this->insertOn( $dbw );
1945 if ( $newid === false ) {
1946 $dbw->endAtomic( __METHOD__
); // nothing inserted
1947 $status->fatal( 'edit-already-exists' );
1949 return $status; // nothing done
1952 // At this point we are now comitted to returning an OK
1953 // status unless some DB query error or other exception comes up.
1954 // This way callers don't have to call rollback() if $status is bad
1955 // unless they actually try to catch exceptions (which is rare).
1957 // @TODO: pass content object?!
1958 $revision = new Revision( [
1960 'title' => $this->mTitle
, // for determining the default content model
1961 'comment' => $summary,
1962 'minor_edit' => $meta['minor'],
1963 'text' => $meta['serialized'],
1965 'user' => $user->getId(),
1966 'user_text' => $user->getName(),
1967 'timestamp' => $now,
1968 'content_model' => $content->getModel(),
1969 'content_format' => $meta['serialFormat'],
1972 // Save the revision text...
1973 $revisionId = $revision->insertOn( $dbw );
1974 // Update the page record with revision data
1975 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1976 throw new MWException( "Failed to update page row to use new revision." );
1979 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1981 // Update recentchanges
1982 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1983 // Mark as patrolled if the user can do so
1984 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1985 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1986 // Add RC row to the DB
1987 RecentChange
::notifyNew(
1990 $revision->isMinor(),
2002 $user->incEditCount();
2004 $dbw->endAtomic( __METHOD__
);
2005 $this->mTimestamp
= $now;
2007 // Return the new revision to the caller
2008 $status->value
['revision'] = $revision;
2010 // Do secondary updates once the main changes have been committed...
2011 DeferredUpdates
::addUpdate(
2012 new AtomicSectionUpdate(
2016 $revision, &$user, $content, $summary, &$flags, $meta, &$status
2018 // Update links, etc.
2019 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
2020 // Trigger post-create hook
2021 $params = [ &$this, &$user, $content, $summary,
2022 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
2023 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $params );
2024 Hooks
::run( 'PageContentInsertComplete', $params );
2025 // Trigger post-save hook
2026 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
2027 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
2028 Hooks
::run( 'PageContentSaveComplete', $params );
2032 DeferredUpdates
::PRESEND
2039 * Get parser options suitable for rendering the primary article wikitext
2041 * @see ContentHandler::makeParserOptions
2043 * @param IContextSource|User|string $context One of the following:
2044 * - IContextSource: Use the User and the Language of the provided
2046 * - User: Use the provided User object and $wgLang for the language,
2047 * so use an IContextSource object if possible.
2048 * - 'canonical': Canonical options (anonymous user with default
2049 * preferences and content language).
2050 * @return ParserOptions
2052 public function makeParserOptions( $context ) {
2053 $options = $this->getContentHandler()->makeParserOptions( $context );
2055 if ( $this->getTitle()->isConversionTable() ) {
2056 // @todo ConversionTable should become a separate content model, so
2057 // we don't need special cases like this one.
2058 $options->disableContentConversion();
2065 * Prepare text which is about to be saved.
2066 * Returns a stdClass with source, pst and output members
2068 * @param string $text
2069 * @param int|null $revid
2070 * @param User|null $user
2071 * @deprecated since 1.21: use prepareContentForEdit instead.
2074 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2075 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2076 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2077 return $this->prepareContentForEdit( $content, $revid, $user );
2081 * Prepare content which is about to be saved.
2082 * Returns a stdClass with source, pst and output members
2084 * @param Content $content
2085 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2086 * revision ID is also accepted, but this is deprecated.
2087 * @param User|null $user
2088 * @param string|null $serialFormat
2089 * @param bool $useCache Check shared prepared edit cache
2095 public function prepareContentForEdit(
2096 Content
$content, $revision = null, User
$user = null,
2097 $serialFormat = null, $useCache = true
2099 global $wgContLang, $wgUser, $wgAjaxEditStash;
2101 if ( is_object( $revision ) ) {
2102 $revid = $revision->getId();
2105 // This code path is deprecated, and nothing is known to
2106 // use it, so performance here shouldn't be a worry.
2107 if ( $revid !== null ) {
2108 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2114 $user = is_null( $user ) ?
$wgUser : $user;
2115 // XXX: check $user->getId() here???
2117 // Use a sane default for $serialFormat, see bug 57026
2118 if ( $serialFormat === null ) {
2119 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2122 if ( $this->mPreparedEdit
2123 && isset( $this->mPreparedEdit
->newContent
)
2124 && $this->mPreparedEdit
->newContent
->equals( $content )
2125 && $this->mPreparedEdit
->revid
== $revid
2126 && $this->mPreparedEdit
->format
== $serialFormat
2127 // XXX: also check $user here?
2130 return $this->mPreparedEdit
;
2133 // The edit may have already been prepared via api.php?action=stashedit
2134 $cachedEdit = $useCache && $wgAjaxEditStash
2135 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2138 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2139 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2142 if ( $cachedEdit ) {
2143 $edit->timestamp
= $cachedEdit->timestamp
;
2145 $edit->timestamp
= wfTimestampNow();
2147 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2148 $edit->revid
= $revid;
2150 if ( $cachedEdit ) {
2151 $edit->pstContent
= $cachedEdit->pstContent
;
2153 $edit->pstContent
= $content
2154 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2158 $edit->format
= $serialFormat;
2159 $edit->popts
= $this->makeParserOptions( 'canonical' );
2160 if ( $cachedEdit ) {
2161 $edit->output
= $cachedEdit->output
;
2164 // We get here if vary-revision is set. This means that this page references
2165 // itself (such as via self-transclusion). In this case, we need to make sure
2166 // that any such self-references refer to the newly-saved revision, and not
2167 // to the previous one, which could otherwise happen due to replica DB lag.
2168 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2169 $edit->popts
->setCurrentRevisionCallback(
2170 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2171 if ( $title->equals( $revision->getTitle() ) ) {
2174 return call_user_func( $oldCallback, $title, $parser );
2179 // Try to avoid a second parse if {{REVISIONID}} is used
2180 $edit->popts
->setSpeculativeRevIdCallback( function () {
2181 return 1 +
(int)wfGetDB( DB_MASTER
)->selectField(
2189 $edit->output
= $edit->pstContent
2190 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2194 $edit->newContent
= $content;
2195 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2197 // NOTE: B/C for hooks! don't use these fields!
2198 $edit->newText
= $edit->newContent
2199 ? ContentHandler
::getContentText( $edit->newContent
)
2201 $edit->oldText
= $edit->oldContent
2202 ? ContentHandler
::getContentText( $edit->oldContent
)
2204 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2206 if ( $edit->output
) {
2207 $edit->output
->setCacheTime( wfTimestampNow() );
2210 // Process cache the result
2211 $this->mPreparedEdit
= $edit;
2217 * Do standard deferred updates after page edit.
2218 * Update links tables, site stats, search index and message cache.
2219 * Purges pages that include this page if the text was changed here.
2220 * Every 100th edit, prune the recent changes table.
2222 * @param Revision $revision
2223 * @param User $user User object that did the revision
2224 * @param array $options Array of options, following indexes are used:
2225 * - changed: boolean, whether the revision changed the content (default true)
2226 * - created: boolean, whether the revision created the page (default false)
2227 * - moved: boolean, whether the page was moved (default false)
2228 * - restored: boolean, whether the page was undeleted (default false)
2229 * - oldrevision: Revision object for the pre-update revision (default null)
2230 * - oldcountable: boolean, null, or string 'no-change' (default null):
2231 * - boolean: whether the page was counted as an article before that
2232 * revision, only used in changed is true and created is false
2233 * - null: if created is false, don't update the article count; if created
2234 * is true, do update the article count
2235 * - 'no-change': don't update the article count, ever
2237 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2238 global $wgRCWatchCategoryMembership, $wgContLang;
2244 'restored' => false,
2245 'oldrevision' => null,
2246 'oldcountable' => null
2248 $content = $revision->getContent();
2250 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2252 // See if the parser output before $revision was inserted is still valid
2254 if ( !$this->mPreparedEdit
) {
2255 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2256 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2257 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2258 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2259 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2261 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2262 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2263 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2265 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2266 $editInfo = $this->mPreparedEdit
;
2270 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2271 // $text is usually already pre-save transformed once. Avoid using the edit stash
2272 // as any prepared content from there or in doEditContent() was already rejected.
2273 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2276 // Save it to the parser cache.
2277 // Make sure the cache time matches page_touched to avoid double parsing.
2278 ParserCache
::singleton()->save(
2279 $editInfo->output
, $this, $editInfo->popts
,
2280 $revision->getTimestamp(), $editInfo->revid
2283 // Update the links tables and other secondary data
2285 $recursive = $options['changed']; // bug 50785
2286 $updates = $content->getSecondaryDataUpdates(
2287 $this->getTitle(), null, $recursive, $editInfo->output
2289 foreach ( $updates as $update ) {
2290 if ( $update instanceof LinksUpdate
) {
2291 $update->setRevision( $revision );
2292 $update->setTriggeringUser( $user );
2294 DeferredUpdates
::addUpdate( $update );
2296 if ( $wgRCWatchCategoryMembership
2297 && $this->getContentHandler()->supportsCategories() === true
2298 && ( $options['changed'] ||
$options['created'] )
2299 && !$options['restored']
2301 // Note: jobs are pushed after deferred updates, so the job should be able to see
2302 // the recent change entry (also done via deferred updates) and carry over any
2303 // bot/deletion/IP flags, ect.
2304 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2307 'pageId' => $this->getId(),
2308 'revTimestamp' => $revision->getTimestamp()
2314 Hooks
::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2316 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2317 // Flush old entries from the `recentchanges` table
2318 if ( mt_rand( 0, 9 ) == 0 ) {
2319 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2323 if ( !$this->exists() ) {
2327 $id = $this->getId();
2328 $title = $this->mTitle
->getPrefixedDBkey();
2329 $shortTitle = $this->mTitle
->getDBkey();
2331 if ( $options['oldcountable'] === 'no-change' ||
2332 ( !$options['changed'] && !$options['moved'] )
2335 } elseif ( $options['created'] ) {
2336 $good = (int)$this->isCountable( $editInfo );
2337 } elseif ( $options['oldcountable'] !== null ) {
2338 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2342 $edits = $options['changed'] ?
1 : 0;
2343 $total = $options['created'] ?
1 : 0;
2345 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2346 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2348 // If this is another user's talk page, update newtalk.
2349 // Don't do this if $options['changed'] = false (null-edits) nor if
2350 // it's a minor edit and the user doesn't want notifications for those.
2351 if ( $options['changed']
2352 && $this->mTitle
->getNamespace() == NS_USER_TALK
2353 && $shortTitle != $user->getTitleKey()
2354 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2356 $recipient = User
::newFromName( $shortTitle, false );
2357 if ( !$recipient ) {
2358 wfDebug( __METHOD__
. ": invalid username\n" );
2360 // Allow extensions to prevent user notification
2361 // when a new message is added to their talk page
2362 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2363 if ( User
::isIP( $shortTitle ) ) {
2364 // An anonymous user
2365 $recipient->setNewtalk( true, $revision );
2366 } elseif ( $recipient->isLoggedIn() ) {
2367 $recipient->setNewtalk( true, $revision );
2369 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2375 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2376 // XXX: could skip pseudo-messages like js/css here, based on content model.
2377 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2378 if ( $msgtext === false ||
$msgtext === null ) {
2382 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2384 if ( $wgContLang->hasVariants() ) {
2385 $wgContLang->updateConversionTable( $this->mTitle
);
2389 if ( $options['created'] ) {
2390 self
::onArticleCreate( $this->mTitle
);
2391 } elseif ( $options['changed'] ) { // bug 50785
2392 self
::onArticleEdit( $this->mTitle
, $revision );
2397 * Edit an article without doing all that other stuff
2398 * The article must already exist; link tables etc
2399 * are not updated, caches are not flushed.
2401 * @param Content $content Content submitted
2402 * @param User $user The relevant user
2403 * @param string $comment Comment submitted
2404 * @param bool $minor Whereas it's a minor modification
2405 * @param string $serialFormat Format for storing the content in the database
2407 public function doQuickEditContent(
2408 Content
$content, User
$user, $comment = '', $minor = false, $serialFormat = null
2411 $serialized = $content->serialize( $serialFormat );
2413 $dbw = wfGetDB( DB_MASTER
);
2414 $revision = new Revision( [
2415 'title' => $this->getTitle(), // for determining the default content model
2416 'page' => $this->getId(),
2417 'user_text' => $user->getName(),
2418 'user' => $user->getId(),
2419 'text' => $serialized,
2420 'length' => $content->getSize(),
2421 'comment' => $comment,
2422 'minor_edit' => $minor ?
1 : 0,
2423 ] ); // XXX: set the content object?
2424 $revision->insertOn( $dbw );
2425 $this->updateRevisionOn( $dbw, $revision );
2427 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2432 * Update the article's restriction field, and leave a log entry.
2433 * This works for protection both existing and non-existing pages.
2435 * @param array $limit Set of restriction keys
2436 * @param array $expiry Per restriction type expiration
2437 * @param int &$cascade Set to false if cascading protection isn't allowed.
2438 * @param string $reason
2439 * @param User $user The user updating the restrictions
2440 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2441 * ($user should be able to add the specified tags before this is called)
2442 * @return Status Status object; if action is taken, $status->value is the log_id of the
2443 * protection log entry.
2445 public function doUpdateRestrictions( array $limit, array $expiry,
2446 &$cascade, $reason, User
$user, $tags = null
2448 global $wgCascadingRestrictionLevels, $wgContLang;
2450 if ( wfReadOnly() ) {
2451 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2454 $this->loadPageData( 'fromdbmaster' );
2455 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2456 $id = $this->getId();
2462 // Take this opportunity to purge out expired restrictions
2463 Title
::purgeExpiredRestrictions();
2465 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2466 // we expect a single selection, but the schema allows otherwise.
2467 $isProtected = false;
2471 $dbw = wfGetDB( DB_MASTER
);
2473 foreach ( $restrictionTypes as $action ) {
2474 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2475 $expiry[$action] = 'infinity';
2477 if ( !isset( $limit[$action] ) ) {
2478 $limit[$action] = '';
2479 } elseif ( $limit[$action] != '' ) {
2483 // Get current restrictions on $action
2484 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2485 if ( $current != '' ) {
2486 $isProtected = true;
2489 if ( $limit[$action] != $current ) {
2491 } elseif ( $limit[$action] != '' ) {
2492 // Only check expiry change if the action is actually being
2493 // protected, since expiry does nothing on an not-protected
2495 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2501 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2505 // If nothing has changed, do nothing
2507 return Status
::newGood();
2510 if ( !$protect ) { // No protection at all means unprotection
2511 $revCommentMsg = 'unprotectedarticle';
2512 $logAction = 'unprotect';
2513 } elseif ( $isProtected ) {
2514 $revCommentMsg = 'modifiedarticleprotection';
2515 $logAction = 'modify';
2517 $revCommentMsg = 'protectedarticle';
2518 $logAction = 'protect';
2521 // Truncate for whole multibyte characters
2522 $reason = $wgContLang->truncate( $reason, 255 );
2524 $logRelationsValues = [];
2525 $logRelationsField = null;
2526 $logParamsDetails = [];
2528 // Null revision (used for change tag insertion)
2529 $nullRevision = null;
2531 if ( $id ) { // Protection of existing page
2532 if ( !Hooks
::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2533 return Status
::newGood();
2536 // Only certain restrictions can cascade...
2537 $editrestriction = isset( $limit['edit'] )
2538 ?
[ $limit['edit'] ]
2539 : $this->mTitle
->getRestrictions( 'edit' );
2540 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2541 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2543 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2544 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2547 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2548 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2549 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2551 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2552 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2555 // The schema allows multiple restrictions
2556 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2560 // insert null revision to identify the page protection change as edit summary
2561 $latest = $this->getLatest();
2562 $nullRevision = $this->insertProtectNullRevision(
2571 if ( $nullRevision === null ) {
2572 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2575 $logRelationsField = 'pr_id';
2577 // Update restrictions table
2578 foreach ( $limit as $action => $restrictions ) {
2580 'page_restrictions',
2583 'pr_type' => $action
2587 if ( $restrictions != '' ) {
2588 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2590 'page_restrictions',
2592 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2594 'pr_type' => $action,
2595 'pr_level' => $restrictions,
2596 'pr_cascade' => $cascadeValue,
2597 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2601 $logRelationsValues[] = $dbw->insertId();
2602 $logParamsDetails[] = [
2604 'level' => $restrictions,
2605 'expiry' => $expiry[$action],
2606 'cascade' => (bool)$cascadeValue,
2611 // Clear out legacy restriction fields
2614 [ 'page_restrictions' => '' ],
2615 [ 'page_id' => $id ],
2619 Hooks
::run( 'NewRevisionFromEditComplete',
2620 [ $this, $nullRevision, $latest, $user ] );
2621 Hooks
::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2622 } else { // Protection of non-existing page (also known as "title protection")
2623 // Cascade protection is meaningless in this case
2626 if ( $limit['create'] != '' ) {
2627 $dbw->replace( 'protected_titles',
2628 [ [ 'pt_namespace', 'pt_title' ] ],
2630 'pt_namespace' => $this->mTitle
->getNamespace(),
2631 'pt_title' => $this->mTitle
->getDBkey(),
2632 'pt_create_perm' => $limit['create'],
2633 'pt_timestamp' => $dbw->timestamp(),
2634 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2635 'pt_user' => $user->getId(),
2636 'pt_reason' => $reason,
2639 $logParamsDetails[] = [
2641 'level' => $limit['create'],
2642 'expiry' => $expiry['create'],
2645 $dbw->delete( 'protected_titles',
2647 'pt_namespace' => $this->mTitle
->getNamespace(),
2648 'pt_title' => $this->mTitle
->getDBkey()
2654 $this->mTitle
->flushRestrictions();
2655 InfoAction
::invalidateCache( $this->mTitle
);
2657 if ( $logAction == 'unprotect' ) {
2660 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2662 '4::description' => $protectDescriptionLog, // parameter for IRC
2663 '5:bool:cascade' => $cascade,
2664 'details' => $logParamsDetails, // parameter for localize and api
2668 // Update the protection log
2669 $logEntry = new ManualLogEntry( 'protect', $logAction );
2670 $logEntry->setTarget( $this->mTitle
);
2671 $logEntry->setComment( $reason );
2672 $logEntry->setPerformer( $user );
2673 $logEntry->setParameters( $params );
2674 if ( !is_null( $nullRevision ) ) {
2675 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2677 $logEntry->setTags( $tags );
2678 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2679 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2681 $logId = $logEntry->insert();
2682 $logEntry->publish( $logId );
2684 return Status
::newGood( $logId );
2688 * Insert a new null revision for this page.
2690 * @param string $revCommentMsg Comment message key for the revision
2691 * @param array $limit Set of restriction keys
2692 * @param array $expiry Per restriction type expiration
2693 * @param int $cascade Set to false if cascading protection isn't allowed.
2694 * @param string $reason
2695 * @param User|null $user
2696 * @return Revision|null Null on error
2698 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2699 array $expiry, $cascade, $reason, $user = null
2702 $dbw = wfGetDB( DB_MASTER
);
2704 // Prepare a null revision to be added to the history
2705 $editComment = $wgContLang->ucfirst(
2708 $this->mTitle
->getPrefixedText()
2709 )->inContentLanguage()->text()
2712 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2714 $protectDescription = $this->protectDescription( $limit, $expiry );
2715 if ( $protectDescription ) {
2716 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2717 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2718 ->inContentLanguage()->text();
2721 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2722 $editComment .= wfMessage( 'brackets' )->params(
2723 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2724 )->inContentLanguage()->text();
2727 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2729 $nullRev->insertOn( $dbw );
2731 // Update page record and touch page
2732 $oldLatest = $nullRev->getParentId();
2733 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2740 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2743 protected function formatExpiry( $expiry ) {
2746 if ( $expiry != 'infinity' ) {
2749 $wgContLang->timeanddate( $expiry, false, false ),
2750 $wgContLang->date( $expiry, false, false ),
2751 $wgContLang->time( $expiry, false, false )
2752 )->inContentLanguage()->text();
2754 return wfMessage( 'protect-expiry-indefinite' )
2755 ->inContentLanguage()->text();
2760 * Builds the description to serve as comment for the edit.
2762 * @param array $limit Set of restriction keys
2763 * @param array $expiry Per restriction type expiration
2766 public function protectDescription( array $limit, array $expiry ) {
2767 $protectDescription = '';
2769 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2770 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2771 # All possible message keys are listed here for easier grepping:
2772 # * restriction-create
2773 # * restriction-edit
2774 # * restriction-move
2775 # * restriction-upload
2776 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2777 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2778 # with '' filtered out. All possible message keys are listed below:
2779 # * protect-level-autoconfirmed
2780 # * protect-level-sysop
2781 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2782 ->inContentLanguage()->text();
2784 $expiryText = $this->formatExpiry( $expiry[$action] );
2786 if ( $protectDescription !== '' ) {
2787 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2789 $protectDescription .= wfMessage( 'protect-summary-desc' )
2790 ->params( $actionText, $restrictionsText, $expiryText )
2791 ->inContentLanguage()->text();
2794 return $protectDescription;
2798 * Builds the description to serve as comment for the log entry.
2800 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2801 * protect description text. Keep them in old format to avoid breaking compatibility.
2802 * TODO: Fix protection log to store structured description and format it on-the-fly.
2804 * @param array $limit Set of restriction keys
2805 * @param array $expiry Per restriction type expiration
2808 public function protectDescriptionLog( array $limit, array $expiry ) {
2811 $protectDescriptionLog = '';
2813 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2814 $expiryText = $this->formatExpiry( $expiry[$action] );
2815 $protectDescriptionLog .= $wgContLang->getDirMark() .
2816 "[$action=$restrictions] ($expiryText)";
2819 return trim( $protectDescriptionLog );
2823 * Take an array of page restrictions and flatten it to a string
2824 * suitable for insertion into the page_restrictions field.
2826 * @param string[] $limit
2828 * @throws MWException
2831 protected static function flattenRestrictions( $limit ) {
2832 if ( !is_array( $limit ) ) {
2833 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2839 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2840 $bits[] = "$action=$restrictions";
2843 return implode( ':', $bits );
2847 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2848 * backwards compatibility, if you care about error reporting you should use
2849 * doDeleteArticleReal() instead.
2851 * Deletes the article with database consistency, writes logs, purges caches
2853 * @param string $reason Delete reason for deletion log
2854 * @param bool $suppress Suppress all revisions and log the deletion in
2855 * the suppression log instead of the deletion log
2856 * @param int $u1 Unused
2857 * @param bool $u2 Unused
2858 * @param array|string &$error Array of errors to append to
2859 * @param User $user The deleting user
2860 * @return bool True if successful
2862 public function doDeleteArticle(
2863 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2865 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2866 return $status->isGood();
2870 * Back-end article deletion
2871 * Deletes the article with database consistency, writes logs, purges caches
2875 * @param string $reason Delete reason for deletion log
2876 * @param bool $suppress Suppress all revisions and log the deletion in
2877 * the suppression log instead of the deletion log
2878 * @param int $u1 Unused
2879 * @param bool $u2 Unused
2880 * @param array|string &$error Array of errors to append to
2881 * @param User $user The deleting user
2882 * @return Status Status object; if successful, $status->value is the log_id of the
2883 * deletion log entry. If the page couldn't be deleted because it wasn't
2884 * found, $status is a non-fatal 'cannotdelete' error
2886 public function doDeleteArticleReal(
2887 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2889 global $wgUser, $wgContentHandlerUseDB;
2891 wfDebug( __METHOD__
. "\n" );
2893 $status = Status
::newGood();
2895 if ( $this->mTitle
->getDBkey() === '' ) {
2896 $status->error( 'cannotdelete',
2897 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2901 $user = is_null( $user ) ?
$wgUser : $user;
2902 if ( !Hooks
::run( 'ArticleDelete',
2903 [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2905 if ( $status->isOK() ) {
2906 // Hook aborted but didn't set a fatal status
2907 $status->fatal( 'delete-hook-aborted' );
2912 $dbw = wfGetDB( DB_MASTER
);
2913 $dbw->startAtomic( __METHOD__
);
2915 $this->loadPageData( self
::READ_LATEST
);
2916 $id = $this->getId();
2917 // T98706: lock the page from various other updates but avoid using
2918 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2919 // the revisions queries (which also JOIN on user). Only lock the page
2920 // row and CAS check on page_latest to see if the trx snapshot matches.
2921 $lockedLatest = $this->lockAndGetLatest();
2922 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2923 $dbw->endAtomic( __METHOD__
);
2924 // Page not there or trx snapshot is stale
2925 $status->error( 'cannotdelete',
2926 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2930 // Given the lock above, we can be confident in the title and page ID values
2931 $namespace = $this->getTitle()->getNamespace();
2932 $dbKey = $this->getTitle()->getDBkey();
2934 // At this point we are now comitted to returning an OK
2935 // status unless some DB query error or other exception comes up.
2936 // This way callers don't have to call rollback() if $status is bad
2937 // unless they actually try to catch exceptions (which is rare).
2939 // we need to remember the old content so we can use it to generate all deletion updates.
2941 $content = $this->getContent( Revision
::RAW
);
2942 } catch ( Exception
$ex ) {
2943 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2944 . $ex->getMessage() );
2949 // Bitfields to further suppress the content
2952 // This should be 15...
2953 $bitfield |
= Revision
::DELETED_TEXT
;
2954 $bitfield |
= Revision
::DELETED_COMMENT
;
2955 $bitfield |
= Revision
::DELETED_USER
;
2956 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2957 $deletionFields = [ $dbw->addQuotes( $bitfield ) . ' AS deleted' ];
2959 $deletionFields = [ 'rev_deleted AS deleted' ];
2962 // For now, shunt the revision data into the archive table.
2963 // Text is *not* removed from the text table; bulk storage
2964 // is left intact to avoid breaking block-compression or
2965 // immutable storage schemes.
2966 // In the future, we may keep revisions and mark them with
2967 // the rev_deleted field, which is reserved for this purpose.
2969 // Get all of the page revisions
2970 $fields = array_diff( Revision
::selectFields(), [ 'rev_deleted' ] );
2971 $res = $dbw->select(
2973 array_merge( $fields, $deletionFields ),
2974 [ 'rev_page' => $id ],
2978 // Build their equivalent archive rows
2980 foreach ( $res as $row ) {
2982 'ar_namespace' => $namespace,
2983 'ar_title' => $dbKey,
2984 'ar_comment' => $row->rev_comment
,
2985 'ar_user' => $row->rev_user
,
2986 'ar_user_text' => $row->rev_user_text
,
2987 'ar_timestamp' => $row->rev_timestamp
,
2988 'ar_minor_edit' => $row->rev_minor_edit
,
2989 'ar_rev_id' => $row->rev_id
,
2990 'ar_parent_id' => $row->rev_parent_id
,
2991 'ar_text_id' => $row->rev_text_id
,
2994 'ar_len' => $row->rev_len
,
2995 'ar_page_id' => $id,
2996 'ar_deleted' => $row->deleted
,
2997 'ar_sha1' => $row->rev_sha1
,
2999 if ( $wgContentHandlerUseDB ) {
3000 $rowInsert['ar_content_model'] = $row->rev_content_model
;
3001 $rowInsert['ar_content_format'] = $row->rev_content_format
;
3003 $rowsInsert[] = $rowInsert;
3005 // Copy them into the archive table
3006 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
3007 // Save this so we can pass it to the ArticleDeleteComplete hook.
3008 $archivedRevisionCount = $dbw->affectedRows();
3010 // Clone the title and wikiPage, so we have the information we need when
3011 // we log and run the ArticleDeleteComplete hook.
3012 $logTitle = clone $this->mTitle
;
3013 $wikiPageBeforeDelete = clone $this;
3015 // Now that it's safely backed up, delete it
3016 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
3018 if ( !$dbw->cascadingDeletes() ) {
3019 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
3022 // Log the deletion, if the page was suppressed, put it in the suppression log instead
3023 $logtype = $suppress ?
'suppress' : 'delete';
3025 $logEntry = new ManualLogEntry( $logtype, 'delete' );
3026 $logEntry->setPerformer( $user );
3027 $logEntry->setTarget( $logTitle );
3028 $logEntry->setComment( $reason );
3029 $logid = $logEntry->insert();
3031 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
3032 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
3033 $logEntry->publish( $logid );
3036 $dbw->endAtomic( __METHOD__
);
3038 $this->doDeleteUpdates( $id, $content );
3040 Hooks
::run( 'ArticleDeleteComplete', [
3041 &$wikiPageBeforeDelete,
3047 $archivedRevisionCount
3049 $status->value
= $logid;
3051 // Show log excerpt on 404 pages rather than just a link
3052 $cache = ObjectCache
::getMainStashInstance();
3053 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
3054 $cache->set( $key, 1, $cache::TTL_DAY
);
3060 * Lock the page row for this title+id and return page_latest (or 0)
3062 * @return integer Returns 0 if no row was found with this title+id
3065 public function lockAndGetLatest() {
3066 return (int)wfGetDB( DB_MASTER
)->selectField(
3070 'page_id' => $this->getId(),
3071 // Typically page_id is enough, but some code might try to do
3072 // updates assuming the title is the same, so verify that
3073 'page_namespace' => $this->getTitle()->getNamespace(),
3074 'page_title' => $this->getTitle()->getDBkey()
3082 * Do some database updates after deletion
3084 * @param int $id The page_id value of the page being deleted
3085 * @param Content $content Optional page content to be used when determining
3086 * the required updates. This may be needed because $this->getContent()
3087 * may already return null when the page proper was deleted.
3089 public function doDeleteUpdates( $id, Content
$content = null ) {
3091 $countable = $this->isCountable();
3092 } catch ( Exception
$ex ) {
3093 // fallback for deleting broken pages for which we cannot load the content for
3094 // some reason. Note that doDeleteArticleReal() already logged this problem.
3098 // Update site status
3099 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3101 // Delete pagelinks, update secondary indexes, etc
3102 $updates = $this->getDeletionUpdates( $content );
3103 foreach ( $updates as $update ) {
3104 DeferredUpdates
::addUpdate( $update );
3107 // Reparse any pages transcluding this page
3108 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
3110 // Reparse any pages including this image
3111 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3112 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
3116 WikiPage
::onArticleDelete( $this->mTitle
);
3118 // Reset this object and the Title object
3119 $this->loadFromRow( false, self
::READ_LATEST
);
3122 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3126 * Roll back the most recent consecutive set of edits to a page
3127 * from the same user; fails if there are no eligible edits to
3128 * roll back to, e.g. user is the sole contributor. This function
3129 * performs permissions checks on $user, then calls commitRollback()
3130 * to do the dirty work
3132 * @todo Separate the business/permission stuff out from backend code
3133 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3135 * @param string $fromP Name of the user whose edits to rollback.
3136 * @param string $summary Custom summary. Set to default summary if empty.
3137 * @param string $token Rollback token.
3138 * @param bool $bot If true, mark all reverted edits as bot.
3140 * @param array $resultDetails Array contains result-specific array of additional values
3141 * 'alreadyrolled' : 'current' (rev)
3142 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3144 * @param User $user The user performing the rollback
3145 * @param array|null $tags Change tags to apply to the rollback
3146 * Callers are responsible for permission checks
3147 * (with ChangeTags::canAddTagsAccompanyingChange)
3149 * @return array Array of errors, each error formatted as
3150 * array(messagekey, param1, param2, ...).
3151 * On success, the array is empty. This array can also be passed to
3152 * OutputPage::showPermissionsErrorPage().
3154 public function doRollback(
3155 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3157 $resultDetails = null;
3159 // Check permissions
3160 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3161 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3162 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3164 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3165 $errors[] = [ 'sessionfailure' ];
3168 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3169 $errors[] = [ 'actionthrottledtext' ];
3172 // If there were errors, bail out now
3173 if ( !empty( $errors ) ) {
3177 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3181 * Backend implementation of doRollback(), please refer there for parameter
3182 * and return value documentation
3184 * NOTE: This function does NOT check ANY permissions, it just commits the
3185 * rollback to the DB. Therefore, you should only call this function direct-
3186 * ly if you want to use custom permissions checks. If you don't, use
3187 * doRollback() instead.
3188 * @param string $fromP Name of the user whose edits to rollback.
3189 * @param string $summary Custom summary. Set to default summary if empty.
3190 * @param bool $bot If true, mark all reverted edits as bot.
3192 * @param array $resultDetails Contains result-specific array of additional values
3193 * @param User $guser The user performing the rollback
3194 * @param array|null $tags Change tags to apply to the rollback
3195 * Callers are responsible for permission checks
3196 * (with ChangeTags::canAddTagsAccompanyingChange)
3200 public function commitRollback( $fromP, $summary, $bot,
3201 &$resultDetails, User
$guser, $tags = null
3203 global $wgUseRCPatrol, $wgContLang;
3205 $dbw = wfGetDB( DB_MASTER
);
3207 if ( wfReadOnly() ) {
3208 return [ [ 'readonlytext' ] ];
3211 // Get the last editor
3212 $current = $this->getRevision();
3213 if ( is_null( $current ) ) {
3214 // Something wrong... no page?
3215 return [ [ 'notanarticle' ] ];
3218 $from = str_replace( '_', ' ', $fromP );
3219 // User name given should match up with the top revision.
3220 // If the user was deleted then $from should be empty.
3221 if ( $from != $current->getUserText() ) {
3222 $resultDetails = [ 'current' => $current ];
3223 return [ [ 'alreadyrolled',
3224 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3225 htmlspecialchars( $fromP ),
3226 htmlspecialchars( $current->getUserText() )
3230 // Get the last edit not by this person...
3231 // Note: these may not be public values
3232 $user = intval( $current->getUser( Revision
::RAW
) );
3233 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3234 $s = $dbw->selectRow( 'revision',
3235 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3236 [ 'rev_page' => $current->getPage(),
3237 "rev_user != {$user} OR rev_user_text != {$user_text}"
3239 [ 'USE INDEX' => 'page_timestamp',
3240 'ORDER BY' => 'rev_timestamp DESC' ]
3242 if ( $s === false ) {
3243 // No one else ever edited this page
3244 return [ [ 'cantrollback' ] ];
3245 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3246 ||
$s->rev_deleted
& Revision
::DELETED_USER
3248 // Only admins can see this text
3249 return [ [ 'notvisiblerev' ] ];
3252 // Generate the edit summary if necessary
3253 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3254 if ( empty( $summary ) ) {
3255 if ( $from == '' ) { // no public user name
3256 $summary = wfMessage( 'revertpage-nouser' );
3258 $summary = wfMessage( 'revertpage' );
3262 // Allow the custom summary to use the same args as the default message
3264 $target->getUserText(), $from, $s->rev_id
,
3265 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3266 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3268 if ( $summary instanceof Message
) {
3269 $summary = $summary->params( $args )->inContentLanguage()->text();
3271 $summary = wfMsgReplaceArgs( $summary, $args );
3274 // Trim spaces on user supplied text
3275 $summary = trim( $summary );
3277 // Truncate for whole multibyte characters.
3278 $summary = $wgContLang->truncate( $summary, 255 );
3281 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3283 if ( $guser->isAllowed( 'minoredit' ) ) {
3284 $flags |
= EDIT_MINOR
;
3287 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3288 $flags |
= EDIT_FORCE_BOT
;
3291 $targetContent = $target->getContent();
3292 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3294 // Actually store the edit
3295 $status = $this->doEditContent(
3305 // Set patrolling and bot flag on the edits, which gets rollbacked.
3306 // This is done even on edit failure to have patrolling in that case (bug 62157).
3308 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3309 // Mark all reverted edits as bot
3313 if ( $wgUseRCPatrol ) {
3314 // Mark all reverted edits as patrolled
3315 $set['rc_patrolled'] = 1;
3318 if ( count( $set ) ) {
3319 $dbw->update( 'recentchanges', $set,
3321 'rc_cur_id' => $current->getPage(),
3322 'rc_user_text' => $current->getUserText(),
3323 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3329 if ( !$status->isOK() ) {
3330 return $status->getErrorsArray();
3333 // raise error, when the edit is an edit without a new version
3334 $statusRev = isset( $status->value
['revision'] )
3335 ?
$status->value
['revision']
3337 if ( !( $statusRev instanceof Revision
) ) {
3338 $resultDetails = [ 'current' => $current ];
3339 return [ [ 'alreadyrolled',
3340 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3341 htmlspecialchars( $fromP ),
3342 htmlspecialchars( $current->getUserText() )
3346 if ( $changingContentModel ) {
3347 // If the content model changed during the rollback,
3348 // make sure it gets logged to Special:Log/contentmodel
3349 $log = new ManualLogEntry( 'contentmodel', 'change' );
3350 $log->setPerformer( $guser );
3351 $log->setTarget( $this->mTitle
);
3352 $log->setComment( $summary );
3353 $log->setParameters( [
3354 '4::oldmodel' => $current->getContentModel(),
3355 '5::newmodel' => $targetContent->getModel(),
3358 $logId = $log->insert( $dbw );
3359 $log->publish( $logId );
3362 $revId = $statusRev->getId();
3364 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3367 'summary' => $summary,
3368 'current' => $current,
3369 'target' => $target,
3377 * The onArticle*() functions are supposed to be a kind of hooks
3378 * which should be called whenever any of the specified actions
3381 * This is a good place to put code to clear caches, for instance.
3383 * This is called on page move and undelete, as well as edit
3385 * @param Title $title
3387 public static function onArticleCreate( Title
$title ) {
3388 // Update existence markers on article/talk tabs...
3389 $other = $title->getOtherPage();
3391 $other->purgeSquid();
3393 $title->touchLinks();
3394 $title->purgeSquid();
3395 $title->deleteTitleProtection();
3397 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3399 if ( $title->getNamespace() == NS_CATEGORY
) {
3400 // Load the Category object, which will schedule a job to create
3401 // the category table row if necessary. Checking a replica DB is ok
3402 // here, in the worst case it'll run an unnecessary recount job on
3403 // a category that probably doesn't have many members.
3404 Category
::newFromTitle( $title )->getID();
3409 * Clears caches when article is deleted
3411 * @param Title $title
3413 public static function onArticleDelete( Title
$title ) {
3416 // Update existence markers on article/talk tabs...
3417 $other = $title->getOtherPage();
3419 $other->purgeSquid();
3421 $title->touchLinks();
3422 $title->purgeSquid();
3424 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3427 HTMLFileCache
::clearFileCache( $title );
3428 InfoAction
::invalidateCache( $title );
3431 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3432 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3434 if ( $wgContLang->hasVariants() ) {
3435 $wgContLang->updateConversionTable( $title );
3440 if ( $title->getNamespace() == NS_FILE
) {
3441 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3445 if ( $title->getNamespace() == NS_USER_TALK
) {
3446 $user = User
::newFromName( $title->getText(), false );
3448 $user->setNewtalk( false );
3453 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3457 * Purge caches on page update etc
3459 * @param Title $title
3460 * @param Revision|null $revision Revision that was just saved, may be null
3462 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3463 // Invalidate caches of articles which include this page
3464 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3466 // Invalidate the caches of all pages which redirect here
3467 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3469 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3471 // Purge CDN for this page only
3472 $title->purgeSquid();
3473 // Clear file cache for this page only
3474 HTMLFileCache
::clearFileCache( $title );
3476 $revid = $revision ?
$revision->getId() : null;
3477 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3478 InfoAction
::invalidateCache( $title, $revid );
3485 * Returns a list of categories this page is a member of.
3486 * Results will include hidden categories
3488 * @return TitleArray
3490 public function getCategories() {
3491 $id = $this->getId();
3493 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3496 $dbr = wfGetDB( DB_REPLICA
);
3497 $res = $dbr->select( 'categorylinks',
3498 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3499 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3500 // as not being aliases, and NS_CATEGORY is numeric
3501 [ 'cl_from' => $id ],
3504 return TitleArray
::newFromResult( $res );
3508 * Returns a list of hidden categories this page is a member of.
3509 * Uses the page_props and categorylinks tables.
3511 * @return array Array of Title objects
3513 public function getHiddenCategories() {
3515 $id = $this->getId();
3521 $dbr = wfGetDB( DB_REPLICA
);
3522 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3524 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3525 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3528 if ( $res !== false ) {
3529 foreach ( $res as $row ) {
3530 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3538 * Return an applicable autosummary if one exists for the given edit.
3539 * @param string|null $oldtext The previous text of the page.
3540 * @param string|null $newtext The submitted text of the page.
3541 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3542 * @return string An appropriate autosummary, or an empty string.
3544 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3546 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3547 // NOTE: stub for backwards-compatibility. assumes the given text is
3548 // wikitext. will break horribly if it isn't.
3550 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3552 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3553 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3554 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3556 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3560 * Auto-generates a deletion reason
3562 * @param bool &$hasHistory Whether the page has a history
3563 * @return string|bool String containing deletion reason or empty string, or boolean false
3564 * if no revision occurred
3566 public function getAutoDeleteReason( &$hasHistory ) {
3567 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3571 * Update all the appropriate counts in the category table, given that
3572 * we've added the categories $added and deleted the categories $deleted.
3574 * @param array $added The names of categories that were added
3575 * @param array $deleted The names of categories that were deleted
3576 * @param integer $id Page ID (this should be the original deleted page ID)
3578 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3579 $id = $id ?
: $this->getId();
3580 $dbw = wfGetDB( DB_MASTER
);
3581 $method = __METHOD__
;
3582 // Do this at the end of the commit to reduce lock wait timeouts
3583 $dbw->onTransactionPreCommitOrIdle(
3584 function () use ( $dbw, $added, $deleted, $id, $method ) {
3585 $ns = $this->getTitle()->getNamespace();
3587 $addFields = [ 'cat_pages = cat_pages + 1' ];
3588 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3589 if ( $ns == NS_CATEGORY
) {
3590 $addFields[] = 'cat_subcats = cat_subcats + 1';
3591 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3592 } elseif ( $ns == NS_FILE
) {
3593 $addFields[] = 'cat_files = cat_files + 1';
3594 $removeFields[] = 'cat_files = cat_files - 1';
3597 if ( count( $added ) ) {
3598 $existingAdded = $dbw->selectFieldValues(
3601 [ 'cat_title' => $added ],
3605 // For category rows that already exist, do a plain
3606 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3607 // to avoid creating gaps in the cat_id sequence.
3608 if ( count( $existingAdded ) ) {
3612 [ 'cat_title' => $existingAdded ],
3617 $missingAdded = array_diff( $added, $existingAdded );
3618 if ( count( $missingAdded ) ) {
3620 foreach ( $missingAdded as $cat ) {
3622 'cat_title' => $cat,
3624 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3625 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3638 if ( count( $deleted ) ) {
3642 [ 'cat_title' => $deleted ],
3647 foreach ( $added as $catName ) {
3648 $cat = Category
::newFromName( $catName );
3649 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3652 foreach ( $deleted as $catName ) {
3653 $cat = Category
::newFromName( $catName );
3654 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3657 // Refresh counts on categories that should be empty now, to
3658 // trigger possible deletion. Check master for the most
3659 // up-to-date cat_pages.
3660 if ( count( $deleted ) ) {
3661 $rows = $dbw->select(
3663 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3664 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3667 foreach ( $rows as $row ) {
3668 $cat = Category
::newFromRow( $row );
3669 $cat->refreshCounts();
3677 * Opportunistically enqueue link update jobs given fresh parser output if useful
3679 * @param ParserOutput $parserOutput Current version page output
3682 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3683 if ( wfReadOnly() ) {
3687 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3688 [ $this, $this->mTitle
, $parserOutput ]
3693 $config = RequestContext
::getMain()->getConfig();
3696 'isOpportunistic' => true,
3697 'rootJobTimestamp' => $parserOutput->getCacheTime()
3700 if ( $this->mTitle
->areRestrictionsCascading() ) {
3701 // If the page is cascade protecting, the links should really be up-to-date
3702 JobQueueGroup
::singleton()->lazyPush(
3703 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3705 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3706 // Assume the output contains "dynamic" time/random based magic words.
3707 // Only update pages that expired due to dynamic content and NOT due to edits
3708 // to referenced templates/files. When the cache expires due to dynamic content,
3709 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3710 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3711 // template/file edit already triggered recursive RefreshLinksJob jobs.
3712 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3713 // If a page is uncacheable, do not keep spamming a job for it.
3714 // Although it would be de-duplicated, it would still waste I/O.
3715 $cache = ObjectCache
::getLocalClusterInstance();
3716 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3717 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3718 if ( $cache->add( $key, time(), $ttl ) ) {
3719 JobQueueGroup
::singleton()->lazyPush(
3720 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3728 * Returns a list of updates to be performed when this page is deleted. The
3729 * updates should remove any information about this page from secondary data
3730 * stores such as links tables.
3732 * @param Content|null $content Optional Content object for determining the
3733 * necessary updates.
3734 * @return DataUpdate[]
3736 public function getDeletionUpdates( Content
$content = null ) {
3738 // load content object, which may be used to determine the necessary updates.
3739 // XXX: the content may not be needed to determine the updates.
3741 $content = $this->getContent( Revision
::RAW
);
3742 } catch ( Exception
$ex ) {
3743 // If we can't load the content, something is wrong. Perhaps that's why
3744 // the user is trying to delete the page, so let's not fail in that case.
3745 // Note that doDeleteArticleReal() will already have logged an issue with
3746 // loading the content.
3753 $updates = $content->getDeletionUpdates( $this );
3756 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3761 * Whether this content displayed on this page
3762 * comes from the local database
3767 public function isLocal() {