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." );
125 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
131 $page = new WikiFilePage( $title );
134 $page = new WikiCategoryPage( $title );
137 $page = new WikiPage( $title );
144 * Constructor from a page id
146 * @param int $id Article ID to load
147 * @param string|int $from One of the following values:
148 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
151 * @return WikiPage|null
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 // page id's are never 0 or negative, see bug 61166
159 $from = self
::convertSelectType( $from );
160 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
161 $row = $db->selectRow(
162 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
166 return self
::newFromRow( $row, $from );
170 * Constructor from a database row
173 * @param object $row Database row containing at least fields returned by selectFields().
174 * @param string|int $from Source of $data:
175 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
176 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
177 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
180 public static function newFromRow( $row, $from = 'fromdb' ) {
181 $page = self
::factory( Title
::newFromRow( $row ) );
182 $page->loadFromRow( $row, $from );
187 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
189 * @param object|string|int $type
192 private static function convertSelectType( $type ) {
195 return self
::READ_NORMAL
;
197 return self
::READ_LATEST
;
199 return self
::READ_LOCKING
;
201 // It may already be an integer or whatever else
207 * @todo Move this UI stuff somewhere else
209 * @see ContentHandler::getActionOverrides
211 public function getActionOverrides() {
212 return $this->getContentHandler()->getActionOverrides();
216 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
218 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
220 * @return ContentHandler
224 public function getContentHandler() {
225 return ContentHandler
::getForModelID( $this->getContentModel() );
229 * Get the title object of the article
230 * @return Title Title object of this page
232 public function getTitle() {
233 return $this->mTitle
;
240 public function clear() {
241 $this->mDataLoaded
= false;
242 $this->mDataLoadedFrom
= self
::READ_NONE
;
244 $this->clearCacheFields();
248 * Clear the object cache fields
251 protected function clearCacheFields() {
253 $this->mRedirectTarget
= null; // Title object if set
254 $this->mLastRevision
= null; // Latest revision
255 $this->mTouched
= '19700101000000';
256 $this->mLinksUpdated
= '19700101000000';
257 $this->mTimestamp
= '';
258 $this->mIsRedirect
= false;
259 $this->mLatest
= false;
260 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
261 // the requested rev ID and content against the cached one for equality. For most
262 // content types, the output should not change during the lifetime of this cache.
263 // Clearing it can cause extra parses on edit for no reason.
267 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
271 public function clearPreparedEdit() {
272 $this->mPreparedEdit
= false;
276 * Return the list of revision fields that should be selected to create
281 public static function selectFields() {
282 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
293 'page_links_updated',
298 if ( $wgContentHandlerUseDB ) {
299 $fields[] = 'page_content_model';
302 if ( $wgPageLanguageUseDB ) {
303 $fields[] = 'page_lang';
310 * Fetch a page record with the given conditions
311 * @param IDatabase $dbr
312 * @param array $conditions
313 * @param array $options
314 * @return object|bool Database result resource, or false on failure
316 protected function pageData( $dbr, $conditions, $options = [] ) {
317 $fields = self
::selectFields();
319 Hooks
::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
321 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
323 Hooks
::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
329 * Fetch a page record matching the Title object's namespace and title
330 * using a sanitized title string
332 * @param IDatabase $dbr
333 * @param Title $title
334 * @param array $options
335 * @return object|bool Database result resource, or false on failure
337 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
338 return $this->pageData( $dbr, [
339 'page_namespace' => $title->getNamespace(),
340 'page_title' => $title->getDBkey() ], $options );
344 * Fetch a page record matching the requested ID
346 * @param IDatabase $dbr
348 * @param array $options
349 * @return object|bool Database result resource, or false on failure
351 public function pageDataFromId( $dbr, $id, $options = [] ) {
352 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
356 * Load the object from a given source by title
358 * @param object|string|int $from One of the following:
359 * - A DB query result object.
360 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
361 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
362 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
363 * using SELECT FOR UPDATE.
367 public function loadPageData( $from = 'fromdb' ) {
368 $from = self
::convertSelectType( $from );
369 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
370 // We already have the data from the correct location, no need to load it twice.
374 if ( is_int( $from ) ) {
375 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
376 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
379 && $index == DB_REPLICA
380 && wfGetLB()->getServerCount() > 1
381 && wfGetLB()->hasOrMadeRecentMasterChanges()
383 $from = self
::READ_LATEST
;
384 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
385 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
388 // No idea from where the caller got this data, assume replica DB.
390 $from = self
::READ_NORMAL
;
393 $this->loadFromRow( $data, $from );
397 * Load the object from a database row
400 * @param object|bool $data DB row containing fields returned by selectFields() or false
401 * @param string|int $from One of the following:
402 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
403 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
404 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
405 * the master DB using SELECT FOR UPDATE
407 public function loadFromRow( $data, $from ) {
408 $lc = LinkCache
::singleton();
409 $lc->clearLink( $this->mTitle
);
412 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
414 $this->mTitle
->loadFromRow( $data );
416 // Old-fashioned restrictions
417 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
419 $this->mId
= intval( $data->page_id
);
420 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
421 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
422 $this->mIsRedirect
= intval( $data->page_is_redirect
);
423 $this->mLatest
= intval( $data->page_latest
);
424 // Bug 37225: $latest may no longer match the cached latest Revision object.
425 // Double-check the ID of any cached latest Revision object for consistency.
426 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
427 $this->mLastRevision
= null;
428 $this->mTimestamp
= '';
431 $lc->addBadLinkObj( $this->mTitle
);
433 $this->mTitle
->loadFromRow( false );
435 $this->clearCacheFields();
440 $this->mDataLoaded
= true;
441 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
445 * @return int Page ID
447 public function getId() {
448 if ( !$this->mDataLoaded
) {
449 $this->loadPageData();
455 * @return bool Whether or not the page exists in the database
457 public function exists() {
458 if ( !$this->mDataLoaded
) {
459 $this->loadPageData();
461 return $this->mId
> 0;
465 * Check if this page is something we're going to be showing
466 * some sort of sensible content for. If we return false, page
467 * views (plain action=view) will return an HTTP 404 response,
468 * so spiders and robots can know they're following a bad link.
472 public function hasViewableContent() {
473 return $this->mTitle
->isKnown();
477 * Tests if the article content represents a redirect
481 public function isRedirect() {
482 if ( !$this->mDataLoaded
) {
483 $this->loadPageData();
486 return (bool)$this->mIsRedirect
;
490 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
492 * Will use the revisions actual content model if the page exists,
493 * and the page's default if the page doesn't exist yet.
499 public function getContentModel() {
500 if ( $this->exists() ) {
501 $cache = ObjectCache
::getMainWANInstance();
503 return $cache->getWithSetCallback(
504 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
507 $rev = $this->getRevision();
509 // Look at the revision's actual content model
510 return $rev->getContentModel();
512 $title = $this->mTitle
->getPrefixedDBkey();
513 wfWarn( "Page $title exists but has no (visible) revisions!" );
514 return $this->mTitle
->getContentModel();
520 // use the default model for this page
521 return $this->mTitle
->getContentModel();
525 * Loads page_touched and returns a value indicating if it should be used
526 * @return bool True if this page exists and is not a redirect
528 public function checkTouched() {
529 if ( !$this->mDataLoaded
) {
530 $this->loadPageData();
532 return ( $this->mId
&& !$this->mIsRedirect
);
536 * Get the page_touched field
537 * @return string Containing GMT timestamp
539 public function getTouched() {
540 if ( !$this->mDataLoaded
) {
541 $this->loadPageData();
543 return $this->mTouched
;
547 * Get the page_links_updated field
548 * @return string|null Containing GMT timestamp
550 public function getLinksTimestamp() {
551 if ( !$this->mDataLoaded
) {
552 $this->loadPageData();
554 return $this->mLinksUpdated
;
558 * Get the page_latest field
559 * @return int The rev_id of current revision
561 public function getLatest() {
562 if ( !$this->mDataLoaded
) {
563 $this->loadPageData();
565 return (int)$this->mLatest
;
569 * Get the Revision object of the oldest revision
570 * @return Revision|null
572 public function getOldestRevision() {
574 // Try using the replica DB first, then try the master
576 $db = wfGetDB( DB_REPLICA
);
577 $revSelectFields = Revision
::selectFields();
580 while ( $continue ) {
581 $row = $db->selectRow(
582 [ 'page', 'revision' ],
585 'page_namespace' => $this->mTitle
->getNamespace(),
586 'page_title' => $this->mTitle
->getDBkey(),
591 'ORDER BY' => 'rev_timestamp ASC'
598 $db = wfGetDB( DB_MASTER
);
603 return $row ? Revision
::newFromRow( $row ) : null;
607 * Loads everything except the text
608 * This isn't necessary for all uses, so it's only done if needed.
610 protected function loadLastEdit() {
611 if ( $this->mLastRevision
!== null ) {
612 return; // already loaded
615 $latest = $this->getLatest();
617 return; // page doesn't exist or is missing page_latest info
620 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
621 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
622 // includes the latest changes committed. This is true even within REPEATABLE-READ
623 // transactions, where S1 normally only sees changes committed before the first S1
624 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
625 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
626 // happened after the first S1 SELECT.
627 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
628 $flags = Revision
::READ_LOCKING
;
629 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
630 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
631 // Bug T93976: if page_latest was loaded from the master, fetch the
632 // revision from there as well, as it may not exist yet on a replica DB.
633 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
634 $flags = Revision
::READ_LATEST
;
635 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
637 $dbr = wfGetDB( DB_REPLICA
);
638 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
641 if ( $revision ) { // sanity
642 $this->setLastEdit( $revision );
647 * Set the latest revision
648 * @param Revision $revision
650 protected function setLastEdit( Revision
$revision ) {
651 $this->mLastRevision
= $revision;
652 $this->mTimestamp
= $revision->getTimestamp();
656 * Get the latest revision
657 * @return Revision|null
659 public function getRevision() {
660 $this->loadLastEdit();
661 if ( $this->mLastRevision
) {
662 return $this->mLastRevision
;
668 * Get the content of the current revision. No side-effects...
670 * @param int $audience One of:
671 * Revision::FOR_PUBLIC to be displayed to all users
672 * Revision::FOR_THIS_USER to be displayed to $wgUser
673 * Revision::RAW get the text regardless of permissions
674 * @param User $user User object to check for, only if FOR_THIS_USER is passed
675 * to the $audience parameter
676 * @return Content|null The content of the current revision
680 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
681 $this->loadLastEdit();
682 if ( $this->mLastRevision
) {
683 return $this->mLastRevision
->getContent( $audience, $user );
689 * @return string MW timestamp of last article revision
691 public function getTimestamp() {
692 // Check if the field has been filled by WikiPage::setTimestamp()
693 if ( !$this->mTimestamp
) {
694 $this->loadLastEdit();
697 return wfTimestamp( TS_MW
, $this->mTimestamp
);
701 * Set the page timestamp (use only to avoid DB queries)
702 * @param string $ts MW timestamp of last article revision
705 public function setTimestamp( $ts ) {
706 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
710 * @param int $audience One of:
711 * Revision::FOR_PUBLIC to be displayed to all users
712 * Revision::FOR_THIS_USER to be displayed to the given user
713 * Revision::RAW get the text regardless of permissions
714 * @param User $user User object to check for, only if FOR_THIS_USER is passed
715 * to the $audience parameter
716 * @return int User ID for the user that made the last article revision
718 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
719 $this->loadLastEdit();
720 if ( $this->mLastRevision
) {
721 return $this->mLastRevision
->getUser( $audience, $user );
728 * Get the User object of the user who created the page
729 * @param int $audience One of:
730 * Revision::FOR_PUBLIC to be displayed to all users
731 * Revision::FOR_THIS_USER to be displayed to the given user
732 * Revision::RAW get the text regardless of permissions
733 * @param User $user User object to check for, only if FOR_THIS_USER is passed
734 * to the $audience parameter
737 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
738 $revision = $this->getOldestRevision();
740 $userName = $revision->getUserText( $audience, $user );
741 return User
::newFromName( $userName, false );
748 * @param int $audience One of:
749 * Revision::FOR_PUBLIC to be displayed to all users
750 * Revision::FOR_THIS_USER to be displayed to the given user
751 * Revision::RAW get the text regardless of permissions
752 * @param User $user User object to check for, only if FOR_THIS_USER is passed
753 * to the $audience parameter
754 * @return string Username of the user that made the last article revision
756 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
757 $this->loadLastEdit();
758 if ( $this->mLastRevision
) {
759 return $this->mLastRevision
->getUserText( $audience, $user );
766 * @param int $audience One of:
767 * Revision::FOR_PUBLIC to be displayed to all users
768 * Revision::FOR_THIS_USER to be displayed to the given user
769 * Revision::RAW get the text regardless of permissions
770 * @param User $user User object to check for, only if FOR_THIS_USER is passed
771 * to the $audience parameter
772 * @return string Comment stored for the last article revision
774 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
775 $this->loadLastEdit();
776 if ( $this->mLastRevision
) {
777 return $this->mLastRevision
->getComment( $audience, $user );
784 * Returns true if last revision was marked as "minor edit"
786 * @return bool Minor edit indicator for the last article revision.
788 public function getMinorEdit() {
789 $this->loadLastEdit();
790 if ( $this->mLastRevision
) {
791 return $this->mLastRevision
->isMinor();
798 * Determine whether a page would be suitable for being counted as an
799 * article in the site_stats table based on the title & its content
801 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
802 * if false, the current database state will be used
805 public function isCountable( $editInfo = false ) {
806 global $wgArticleCountMethod;
808 if ( !$this->mTitle
->isContentPage() ) {
813 $content = $editInfo->pstContent
;
815 $content = $this->getContent();
818 if ( !$content ||
$content->isRedirect() ) {
824 if ( $wgArticleCountMethod === 'link' ) {
825 // nasty special case to avoid re-parsing to detect links
828 // ParserOutput::getLinks() is a 2D array of page links, so
829 // to be really correct we would need to recurse in the array
830 // but the main array should only have items in it if there are
832 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
834 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
835 [ 'pl_from' => $this->getId() ], __METHOD__
);
839 return $content->isCountable( $hasLinks );
843 * If this page is a redirect, get its target
845 * The target will be fetched from the redirect table if possible.
846 * If this page doesn't have an entry there, call insertRedirect()
847 * @return Title|null Title object, or null if this page is not a redirect
849 public function getRedirectTarget() {
850 if ( !$this->mTitle
->isRedirect() ) {
854 if ( $this->mRedirectTarget
!== null ) {
855 return $this->mRedirectTarget
;
858 // Query the redirect table
859 $dbr = wfGetDB( DB_REPLICA
);
860 $row = $dbr->selectRow( 'redirect',
861 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
862 [ 'rd_from' => $this->getId() ],
866 // rd_fragment and rd_interwiki were added later, populate them if empty
867 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
868 $this->mRedirectTarget
= Title
::makeTitle(
869 $row->rd_namespace
, $row->rd_title
,
870 $row->rd_fragment
, $row->rd_interwiki
872 return $this->mRedirectTarget
;
875 // This page doesn't have an entry in the redirect table
876 $this->mRedirectTarget
= $this->insertRedirect();
877 return $this->mRedirectTarget
;
881 * Insert an entry for this page into the redirect table if the content is a redirect
883 * The database update will be deferred via DeferredUpdates
885 * Don't call this function directly unless you know what you're doing.
886 * @return Title|null Title object or null if not a redirect
888 public function insertRedirect() {
889 $content = $this->getContent();
890 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
895 // Update the DB post-send if the page has not cached since now
897 $latest = $this->getLatest();
898 DeferredUpdates
::addCallableUpdate(
899 function () use ( $that, $retval, $latest ) {
900 $that->insertRedirectEntry( $retval, $latest );
902 DeferredUpdates
::POSTSEND
,
910 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
911 * @param Title $rt Redirect target
912 * @param int|null $oldLatest Prior page_latest for check and set
914 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
915 $dbw = wfGetDB( DB_MASTER
);
916 $dbw->startAtomic( __METHOD__
);
918 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
922 'rd_from' => $this->getId(),
923 'rd_namespace' => $rt->getNamespace(),
924 'rd_title' => $rt->getDBkey(),
925 'rd_fragment' => $rt->getFragment(),
926 'rd_interwiki' => $rt->getInterwiki(),
930 'rd_namespace' => $rt->getNamespace(),
931 'rd_title' => $rt->getDBkey(),
932 'rd_fragment' => $rt->getFragment(),
933 'rd_interwiki' => $rt->getInterwiki(),
939 $dbw->endAtomic( __METHOD__
);
943 * Get the Title object or URL this page redirects to
945 * @return bool|Title|string False, Title of in-wiki target, or string with URL
947 public function followRedirect() {
948 return $this->getRedirectURL( $this->getRedirectTarget() );
952 * Get the Title object or URL to use for a redirect. We use Title
953 * objects for same-wiki, non-special redirects and URLs for everything
955 * @param Title $rt Redirect target
956 * @return bool|Title|string False, Title object of local target, or string with URL
958 public function getRedirectURL( $rt ) {
963 if ( $rt->isExternal() ) {
964 if ( $rt->isLocal() ) {
965 // Offsite wikis need an HTTP redirect.
966 // This can be hard to reverse and may produce loops,
967 // so they may be disabled in the site configuration.
968 $source = $this->mTitle
->getFullURL( 'redirect=no' );
969 return $rt->getFullURL( [ 'rdfrom' => $source ] );
971 // External pages without "local" bit set are not valid
977 if ( $rt->isSpecialPage() ) {
978 // Gotta handle redirects to special pages differently:
979 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
980 // Some pages are not valid targets.
981 if ( $rt->isValidRedirectTarget() ) {
982 return $rt->getFullURL();
992 * Get a list of users who have edited this article, not including the user who made
993 * the most recent revision, which you can get from $article->getUser() if you want it
994 * @return UserArrayFromResult
996 public function getContributors() {
997 // @todo FIXME: This is expensive; cache this info somewhere.
999 $dbr = wfGetDB( DB_REPLICA
);
1001 if ( $dbr->implicitGroupby() ) {
1002 $realNameField = 'user_real_name';
1004 $realNameField = 'MIN(user_real_name) AS user_real_name';
1007 $tables = [ 'revision', 'user' ];
1010 'user_id' => 'rev_user',
1011 'user_name' => 'rev_user_text',
1013 'timestamp' => 'MAX(rev_timestamp)',
1016 $conds = [ 'rev_page' => $this->getId() ];
1018 // The user who made the top revision gets credited as "this page was last edited by
1019 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1020 $user = $this->getUser();
1022 $conds[] = "rev_user != $user";
1024 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1028 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1031 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1035 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1036 'ORDER BY' => 'timestamp DESC',
1039 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1040 return new UserArrayFromResult( $res );
1044 * Should the parser cache be used?
1046 * @param ParserOptions $parserOptions ParserOptions to check
1050 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1051 return $parserOptions->getStubThreshold() == 0
1053 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1054 && $this->getContentHandler()->isParserCacheSupported();
1058 * Get a ParserOutput for the given ParserOptions and revision ID.
1060 * The parser cache will be used if possible. Cache misses that result
1061 * in parser runs are debounced with PoolCounter.
1064 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1065 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1066 * get the current revision (default value)
1067 * @param bool $forceParse Force reindexing, regardless of cache settings
1068 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1070 public function getParserOutput(
1071 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1074 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1075 wfDebug( __METHOD__
.
1076 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1077 if ( $parserOptions->getStubThreshold() ) {
1078 wfIncrStats( 'pcache.miss.stub' );
1081 if ( $useParserCache ) {
1082 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1083 if ( $parserOutput !== false ) {
1084 return $parserOutput;
1088 if ( $oldid === null ||
$oldid === 0 ) {
1089 $oldid = $this->getLatest();
1092 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1095 return $pool->getParserOutput();
1099 * Do standard deferred updates after page view (existing or missing page)
1100 * @param User $user The relevant user
1101 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1103 public function doViewUpdates( User
$user, $oldid = 0 ) {
1104 if ( wfReadOnly() ) {
1108 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1109 // Update newtalk / watchlist notification status
1111 $user->clearNotification( $this->mTitle
, $oldid );
1112 } catch ( DBError
$e ) {
1113 // Avoid outage if the master is not reachable
1114 MWExceptionHandler
::logException( $e );
1119 * Perform the actions of a page purging
1120 * @param integer $flags Bitfield of WikiPage::PURGE_* constants
1123 public function doPurge( $flags = self
::PURGE_ALL
) {
1124 if ( !Hooks
::run( 'ArticlePurge', [ &$this ] ) ) {
1128 if ( ( $flags & self
::PURGE_GLOBAL_PCACHE
) == self
::PURGE_GLOBAL_PCACHE
) {
1129 // Set page_touched in the database to invalidate all DC caches
1130 $this->mTitle
->invalidateCache();
1131 } elseif ( ( $flags & self
::PURGE_CLUSTER_PCACHE
) == self
::PURGE_CLUSTER_PCACHE
) {
1132 // Delete the parser options key in the local cluster to invalidate the DC cache
1133 ParserCache
::singleton()->deleteOptionsKey( $this );
1134 // Avoid sending HTTP 304s in ViewAction to the client who just issued the purge
1135 $cache = ObjectCache
::getLocalClusterInstance();
1137 $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ),
1138 wfTimestamp( TS_MW
),
1143 if ( ( $flags & self
::PURGE_CDN_CACHE
) == self
::PURGE_CDN_CACHE
) {
1144 // Clear any HTML file cache
1145 HTMLFileCache
::clearFileCache( $this->getTitle() );
1146 // Send purge after any page_touched above update was committed
1147 DeferredUpdates
::addUpdate(
1148 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1149 DeferredUpdates
::PRESEND
1153 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1154 // @todo move this logic to MessageCache
1155 if ( $this->exists() ) {
1156 // NOTE: use transclusion text for messages.
1157 // This is consistent with MessageCache::getMsgFromNamespace()
1159 $content = $this->getContent();
1160 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1162 if ( $text === null ) {
1169 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1176 * Get the last time a user explicitly purged the page via action=purge
1178 * @return string|bool TS_MW timestamp or false
1181 public function getLastPurgeTimestamp() {
1182 $cache = ObjectCache
::getLocalClusterInstance();
1184 return $cache->get( $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ) );
1188 * Insert a new empty page record for this article.
1189 * This *must* be followed up by creating a revision
1190 * and running $this->updateRevisionOn( ... );
1191 * or else the record will be left in a funky state.
1192 * Best if all done inside a transaction.
1194 * @param IDatabase $dbw
1195 * @param int|null $pageId Custom page ID that will be used for the insert statement
1197 * @return bool|int The newly created page_id key; false if the row was not
1198 * inserted, e.g. because the title already existed or because the specified
1199 * page ID is already in use.
1201 public function insertOn( $dbw, $pageId = null ) {
1202 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1206 'page_id' => $pageIdForInsert,
1207 'page_namespace' => $this->mTitle
->getNamespace(),
1208 'page_title' => $this->mTitle
->getDBkey(),
1209 'page_restrictions' => '',
1210 'page_is_redirect' => 0, // Will set this shortly...
1212 'page_random' => wfRandom(),
1213 'page_touched' => $dbw->timestamp(),
1214 'page_latest' => 0, // Fill this in shortly...
1215 'page_len' => 0, // Fill this in shortly...
1221 if ( $dbw->affectedRows() > 0 ) {
1222 $newid = $pageId ?
: $dbw->insertId();
1223 $this->mId
= $newid;
1224 $this->mTitle
->resetArticleID( $newid );
1228 return false; // nothing changed
1233 * Update the page record to point to a newly saved revision.
1235 * @param IDatabase $dbw
1236 * @param Revision $revision For ID number, and text used to set
1237 * length and redirect status fields
1238 * @param int $lastRevision If given, will not overwrite the page field
1239 * when different from the currently set value.
1240 * Giving 0 indicates the new page flag should be set on.
1241 * @param bool $lastRevIsRedirect If given, will optimize adding and
1242 * removing rows in redirect table.
1243 * @return bool Success; false if the page row was missing or page_latest changed
1245 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1246 $lastRevIsRedirect = null
1248 global $wgContentHandlerUseDB;
1250 // Assertion to try to catch T92046
1251 if ( (int)$revision->getId() === 0 ) {
1252 throw new InvalidArgumentException(
1253 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1257 $content = $revision->getContent();
1258 $len = $content ?
$content->getSize() : 0;
1259 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1261 $conditions = [ 'page_id' => $this->getId() ];
1263 if ( !is_null( $lastRevision ) ) {
1264 // An extra check against threads stepping on each other
1265 $conditions['page_latest'] = $lastRevision;
1269 'page_latest' => $revision->getId(),
1270 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1271 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1272 'page_is_redirect' => $rt !== null ?
1 : 0,
1276 if ( $wgContentHandlerUseDB ) {
1277 $row['page_content_model'] = $revision->getContentModel();
1280 $dbw->update( 'page',
1285 $result = $dbw->affectedRows() > 0;
1287 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1288 $this->setLastEdit( $revision );
1289 $this->mLatest
= $revision->getId();
1290 $this->mIsRedirect
= (bool)$rt;
1291 // Update the LinkCache.
1292 LinkCache
::singleton()->addGoodLinkObj(
1298 $revision->getContentModel()
1306 * Add row to the redirect table if this is a redirect, remove otherwise.
1308 * @param IDatabase $dbw
1309 * @param Title $redirectTitle Title object pointing to the redirect target,
1310 * or NULL if this is not a redirect
1311 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1312 * removing rows in redirect table.
1313 * @return bool True on success, false on failure
1316 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1317 // Always update redirects (target link might have changed)
1318 // Update/Insert if we don't know if the last revision was a redirect or not
1319 // Delete if changing from redirect to non-redirect
1320 $isRedirect = !is_null( $redirectTitle );
1322 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1326 if ( $isRedirect ) {
1327 $this->insertRedirectEntry( $redirectTitle );
1329 // This is not a redirect, remove row from redirect table
1330 $where = [ 'rd_from' => $this->getId() ];
1331 $dbw->delete( 'redirect', $where, __METHOD__
);
1334 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1335 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1338 return ( $dbw->affectedRows() != 0 );
1342 * If the given revision is newer than the currently set page_latest,
1343 * update the page record. Otherwise, do nothing.
1345 * @deprecated since 1.24, use updateRevisionOn instead
1347 * @param IDatabase $dbw
1348 * @param Revision $revision
1351 public function updateIfNewerOn( $dbw, $revision ) {
1353 $row = $dbw->selectRow(
1354 [ 'revision', 'page' ],
1355 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1357 'page_id' => $this->getId(),
1358 'page_latest=rev_id' ],
1362 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1365 $prev = $row->rev_id
;
1366 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1368 // No or missing previous revision; mark the page as new
1370 $lastRevIsRedirect = null;
1373 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1379 * Get the content that needs to be saved in order to undo all revisions
1380 * between $undo and $undoafter. Revisions must belong to the same page,
1381 * must exist and must not be deleted
1382 * @param Revision $undo
1383 * @param Revision $undoafter Must be an earlier revision than $undo
1384 * @return Content|bool Content on success, false on failure
1386 * Before we had the Content object, this was done in getUndoText
1388 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1389 $handler = $undo->getContentHandler();
1390 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1394 * Returns true if this page's content model supports sections.
1398 * @todo The skin should check this and not offer section functionality if
1399 * sections are not supported.
1400 * @todo The EditPage should check this and not offer section functionality
1401 * if sections are not supported.
1403 public function supportsSections() {
1404 return $this->getContentHandler()->supportsSections();
1408 * @param string|number|null|bool $sectionId Section identifier as a number or string
1409 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1410 * or 'new' for a new section.
1411 * @param Content $sectionContent New content of the section.
1412 * @param string $sectionTitle New section's subject, only if $section is "new".
1413 * @param string $edittime Revision timestamp or null to use the current revision.
1415 * @throws MWException
1416 * @return Content|null New complete article content, or null if error.
1419 * @deprecated since 1.24, use replaceSectionAtRev instead
1421 public function replaceSectionContent(
1422 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1426 if ( $edittime && $sectionId !== 'new' ) {
1427 $dbr = wfGetDB( DB_REPLICA
);
1428 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1429 // Try the master if this thread may have just added it.
1430 // This could be abstracted into a Revision method, but we don't want
1431 // to encourage loading of revisions by timestamp.
1433 && wfGetLB()->getServerCount() > 1
1434 && wfGetLB()->hasOrMadeRecentMasterChanges()
1436 $dbw = wfGetDB( DB_MASTER
);
1437 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1440 $baseRevId = $rev->getId();
1444 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1448 * @param string|number|null|bool $sectionId Section identifier as a number or string
1449 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1450 * or 'new' for a new section.
1451 * @param Content $sectionContent New content of the section.
1452 * @param string $sectionTitle New section's subject, only if $section is "new".
1453 * @param int|null $baseRevId
1455 * @throws MWException
1456 * @return Content|null New complete article content, or null if error.
1460 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1461 $sectionTitle = '', $baseRevId = null
1464 if ( strval( $sectionId ) === '' ) {
1465 // Whole-page edit; let the whole text through
1466 $newContent = $sectionContent;
1468 if ( !$this->supportsSections() ) {
1469 throw new MWException( "sections not supported for content model " .
1470 $this->getContentHandler()->getModelID() );
1473 // Bug 30711: always use current version when adding a new section
1474 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1475 $oldContent = $this->getContent();
1477 $rev = Revision
::newFromId( $baseRevId );
1479 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1480 $this->getId() . "; section: $sectionId)\n" );
1484 $oldContent = $rev->getContent();
1487 if ( !$oldContent ) {
1488 wfDebug( __METHOD__
. ": no page text\n" );
1492 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1499 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1501 * @return int Updated $flags
1503 public function checkFlags( $flags ) {
1504 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1505 if ( $this->exists() ) {
1506 $flags |
= EDIT_UPDATE
;
1516 * Change an existing article or create a new article. Updates RC and all necessary caches,
1517 * optionally via the deferred update array.
1519 * @param string $text New text
1520 * @param string $summary Edit summary
1521 * @param int $flags Bitfield:
1523 * Article is known or assumed to be non-existent, create a new one
1525 * Article is known or assumed to be pre-existing, update it
1527 * Mark this edit minor, if the user is allowed to do so
1529 * Do not log the change in recentchanges
1531 * Mark the edit a "bot" edit regardless of user rights
1533 * Fill in blank summaries with generated text where possible
1535 * Signal that the page retrieve/save cycle happened entirely in this request.
1537 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1538 * article will be detected. If EDIT_UPDATE is specified and the article
1539 * doesn't exist, the function will return an edit-gone-missing error. If
1540 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1541 * error will be returned. These two conditions are also possible with
1542 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1544 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1545 * This is not the parent revision ID, rather the revision ID for older
1546 * content used as the source for a rollback, for example.
1547 * @param User $user The user doing the edit
1549 * @throws MWException
1550 * @return Status Possible errors:
1551 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1552 * set the fatal flag of $status
1553 * edit-gone-missing: In update mode, but the article didn't exist.
1554 * edit-conflict: In update mode, the article changed unexpectedly.
1555 * edit-no-change: Warning that the text was the same as before.
1556 * edit-already-exists: In creation mode, but the article already exists.
1558 * Extensions may define additional errors.
1560 * $return->value will contain an associative array with members as follows:
1561 * new: Boolean indicating if the function attempted to create a new article.
1562 * revision: The revision object for the inserted revision, or null.
1564 * Compatibility note: this function previously returned a boolean value
1565 * indicating success/failure
1567 * @deprecated since 1.21: use doEditContent() instead.
1569 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1570 wfDeprecated( __METHOD__
, '1.21' );
1572 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1574 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1578 * Change an existing article or create a new article. Updates RC and all necessary caches,
1579 * optionally via the deferred update array.
1581 * @param Content $content New content
1582 * @param string $summary Edit summary
1583 * @param int $flags Bitfield:
1585 * Article is known or assumed to be non-existent, create a new one
1587 * Article is known or assumed to be pre-existing, update it
1589 * Mark this edit minor, if the user is allowed to do so
1591 * Do not log the change in recentchanges
1593 * Mark the edit a "bot" edit regardless of user rights
1595 * Fill in blank summaries with generated text where possible
1597 * Signal that the page retrieve/save cycle happened entirely in this request.
1599 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1600 * article will be detected. If EDIT_UPDATE is specified and the article
1601 * doesn't exist, the function will return an edit-gone-missing error. If
1602 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1603 * error will be returned. These two conditions are also possible with
1604 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1606 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1607 * This is not the parent revision ID, rather the revision ID for older
1608 * content used as the source for a rollback, for example.
1609 * @param User $user The user doing the edit
1610 * @param string $serialFormat Format for storing the content in the
1612 * @param array|null $tags Change tags to apply to this edit
1613 * Callers are responsible for permission checks
1614 * (with ChangeTags::canAddTagsAccompanyingChange)
1616 * @throws MWException
1617 * @return Status Possible errors:
1618 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1619 * set the fatal flag of $status.
1620 * edit-gone-missing: In update mode, but the article didn't exist.
1621 * edit-conflict: In update mode, the article changed unexpectedly.
1622 * edit-no-change: Warning that the text was the same as before.
1623 * edit-already-exists: In creation mode, but the article already exists.
1625 * Extensions may define additional errors.
1627 * $return->value will contain an associative array with members as follows:
1628 * new: Boolean indicating if the function attempted to create a new article.
1629 * revision: The revision object for the inserted revision, or null.
1632 * @throws MWException
1634 public function doEditContent(
1635 Content
$content, $summary, $flags = 0, $baseRevId = false,
1636 User
$user = null, $serialFormat = null, $tags = []
1638 global $wgUser, $wgUseAutomaticEditSummaries;
1640 // Old default parameter for $tags was null
1641 if ( $tags === null ) {
1645 // Low-level sanity check
1646 if ( $this->mTitle
->getText() === '' ) {
1647 throw new MWException( 'Something is trying to edit an article with an empty title' );
1649 // Make sure the given content type is allowed for this page
1650 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1651 return Status
::newFatal( 'content-not-allowed-here',
1652 ContentHandler
::getLocalizedName( $content->getModel() ),
1653 $this->mTitle
->getPrefixedText()
1657 // Load the data from the master database if needed.
1658 // The caller may already loaded it from the master or even loaded it using
1659 // SELECT FOR UPDATE, so do not override that using clear().
1660 $this->loadPageData( 'fromdbmaster' );
1662 $user = $user ?
: $wgUser;
1663 $flags = $this->checkFlags( $flags );
1665 // Trigger pre-save hook (using provided edit summary)
1666 $hookStatus = Status
::newGood( [] );
1667 $hook_args = [ &$this, &$user, &$content, &$summary,
1668 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1669 // Check if the hook rejected the attempted save
1670 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1671 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args, '1.21' )
1673 if ( $hookStatus->isOK() ) {
1674 // Hook returned false but didn't call fatal(); use generic message
1675 $hookStatus->fatal( 'edit-hook-aborted' );
1681 $old_revision = $this->getRevision(); // current revision
1682 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1684 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1685 $tags[] = 'mw-contentmodelchange';
1688 // Provide autosummaries if one is not provided and autosummaries are enabled
1689 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1690 $handler = $content->getContentHandler();
1691 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1694 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1695 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1701 // Get the pre-save transform content and final parser output
1702 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1703 $pstContent = $editInfo->pstContent
; // Content object
1705 'bot' => ( $flags & EDIT_FORCE_BOT
),
1706 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1707 'serialized' => $editInfo->pst
,
1708 'serialFormat' => $serialFormat,
1709 'baseRevId' => $baseRevId,
1710 'oldRevision' => $old_revision,
1711 'oldContent' => $old_content,
1712 'oldId' => $this->getLatest(),
1713 'oldIsRedirect' => $this->isRedirect(),
1714 'oldCountable' => $this->isCountable(),
1715 'tags' => ( $tags !== null ) ?
(array)$tags : []
1718 // Actually create the revision and create/update the page
1719 if ( $flags & EDIT_UPDATE
) {
1720 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1722 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1725 // Promote user to any groups they meet the criteria for
1726 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1727 $user->addAutopromoteOnceGroups( 'onEdit' );
1728 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1735 * @param Content $content Pre-save transform content
1736 * @param integer $flags
1738 * @param string $summary
1739 * @param array $meta
1741 * @throws DBUnexpectedError
1743 * @throws FatalError
1744 * @throws MWException
1746 private function doModify(
1747 Content
$content, $flags, User
$user, $summary, array $meta
1749 global $wgUseRCPatrol;
1751 // Update article, but only if changed.
1752 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1754 // Convenience variables
1755 $now = wfTimestampNow();
1756 $oldid = $meta['oldId'];
1757 /** @var $oldContent Content|null */
1758 $oldContent = $meta['oldContent'];
1759 $newsize = $content->getSize();
1762 // Article gone missing
1763 $status->fatal( 'edit-gone-missing' );
1766 } elseif ( !$oldContent ) {
1767 // Sanity check for bug 37225
1768 throw new MWException( "Could not find text for current revision {$oldid}." );
1771 // @TODO: pass content object?!
1772 $revision = new Revision( [
1773 'page' => $this->getId(),
1774 'title' => $this->mTitle
, // for determining the default content model
1775 'comment' => $summary,
1776 'minor_edit' => $meta['minor'],
1777 'text' => $meta['serialized'],
1779 'parent_id' => $oldid,
1780 'user' => $user->getId(),
1781 'user_text' => $user->getName(),
1782 'timestamp' => $now,
1783 'content_model' => $content->getModel(),
1784 'content_format' => $meta['serialFormat'],
1787 $changed = !$content->equals( $oldContent );
1789 $dbw = wfGetDB( DB_MASTER
);
1792 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1793 $status->merge( $prepStatus );
1794 if ( !$status->isOK() ) {
1798 $dbw->startAtomic( __METHOD__
);
1799 // Get the latest page_latest value while locking it.
1800 // Do a CAS style check to see if it's the same as when this method
1801 // started. If it changed then bail out before touching the DB.
1802 $latestNow = $this->lockAndGetLatest();
1803 if ( $latestNow != $oldid ) {
1804 $dbw->endAtomic( __METHOD__
);
1805 // Page updated or deleted in the mean time
1806 $status->fatal( 'edit-conflict' );
1811 // At this point we are now comitted to returning an OK
1812 // status unless some DB query error or other exception comes up.
1813 // This way callers don't have to call rollback() if $status is bad
1814 // unless they actually try to catch exceptions (which is rare).
1816 // Save the revision text
1817 $revisionId = $revision->insertOn( $dbw );
1818 // Update page_latest and friends to reflect the new revision
1819 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1820 throw new MWException( "Failed to update page row to use new revision." );
1823 Hooks
::run( 'NewRevisionFromEditComplete',
1824 [ $this, $revision, $meta['baseRevId'], $user ] );
1826 // Update recentchanges
1827 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1828 // Mark as patrolled if the user can do so
1829 $patrolled = $wgUseRCPatrol && !count(
1830 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1831 // Add RC row to the DB
1832 RecentChange
::notifyEdit(
1835 $revision->isMinor(),
1839 $this->getTimestamp(),
1842 $oldContent ?
$oldContent->getSize() : 0,
1850 $user->incEditCount();
1852 $dbw->endAtomic( __METHOD__
);
1853 $this->mTimestamp
= $now;
1855 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1856 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1857 $revision->setId( $this->getLatest() );
1858 $revision->setUserIdAndName(
1859 $this->getUser( Revision
::RAW
),
1860 $this->getUserText( Revision
::RAW
)
1865 // Return the new revision to the caller
1866 $status->value
['revision'] = $revision;
1868 $status->warning( 'edit-no-change' );
1869 // Update page_touched as updateRevisionOn() was not called.
1870 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1871 $this->mTitle
->invalidateCache( $now );
1874 // Do secondary updates once the main changes have been committed...
1875 DeferredUpdates
::addUpdate(
1876 new AtomicSectionUpdate(
1880 $revision, &$user, $content, $summary, &$flags,
1881 $changed, $meta, &$status
1883 // Update links tables, site stats, etc.
1884 $this->doEditUpdates(
1888 'changed' => $changed,
1889 'oldcountable' => $meta['oldCountable'],
1890 'oldrevision' => $meta['oldRevision']
1893 // Trigger post-save hook
1894 $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR
,
1895 null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1896 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
1897 Hooks
::run( 'PageContentSaveComplete', $params );
1900 DeferredUpdates
::PRESEND
1907 * @param Content $content Pre-save transform content
1908 * @param integer $flags
1910 * @param string $summary
1911 * @param array $meta
1913 * @throws DBUnexpectedError
1915 * @throws FatalError
1916 * @throws MWException
1918 private function doCreate(
1919 Content
$content, $flags, User
$user, $summary, array $meta
1921 global $wgUseRCPatrol, $wgUseNPPatrol;
1923 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1925 $now = wfTimestampNow();
1926 $newsize = $content->getSize();
1927 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1928 $status->merge( $prepStatus );
1929 if ( !$status->isOK() ) {
1933 $dbw = wfGetDB( DB_MASTER
);
1934 $dbw->startAtomic( __METHOD__
);
1936 // Add the page record unless one already exists for the title
1937 $newid = $this->insertOn( $dbw );
1938 if ( $newid === false ) {
1939 $dbw->endAtomic( __METHOD__
); // nothing inserted
1940 $status->fatal( 'edit-already-exists' );
1942 return $status; // nothing done
1945 // At this point we are now comitted to returning an OK
1946 // status unless some DB query error or other exception comes up.
1947 // This way callers don't have to call rollback() if $status is bad
1948 // unless they actually try to catch exceptions (which is rare).
1950 // @TODO: pass content object?!
1951 $revision = new Revision( [
1953 'title' => $this->mTitle
, // for determining the default content model
1954 'comment' => $summary,
1955 'minor_edit' => $meta['minor'],
1956 'text' => $meta['serialized'],
1958 'user' => $user->getId(),
1959 'user_text' => $user->getName(),
1960 'timestamp' => $now,
1961 'content_model' => $content->getModel(),
1962 'content_format' => $meta['serialFormat'],
1965 // Save the revision text...
1966 $revisionId = $revision->insertOn( $dbw );
1967 // Update the page record with revision data
1968 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1969 throw new MWException( "Failed to update page row to use new revision." );
1972 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1974 // Update recentchanges
1975 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1976 // Mark as patrolled if the user can do so
1977 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1978 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1979 // Add RC row to the DB
1980 RecentChange
::notifyNew(
1983 $revision->isMinor(),
1995 $user->incEditCount();
1997 $dbw->endAtomic( __METHOD__
);
1998 $this->mTimestamp
= $now;
2000 // Return the new revision to the caller
2001 $status->value
['revision'] = $revision;
2003 // Do secondary updates once the main changes have been committed...
2004 DeferredUpdates
::addUpdate(
2005 new AtomicSectionUpdate(
2009 $revision, &$user, $content, $summary, &$flags, $meta, &$status
2011 // Update links, etc.
2012 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
2013 // Trigger post-create hook
2014 $params = [ &$this, &$user, $content, $summary,
2015 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
2016 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $params, '1.21' );
2017 Hooks
::run( 'PageContentInsertComplete', $params );
2018 // Trigger post-save hook
2019 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
2020 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params, '1.21' );
2021 Hooks
::run( 'PageContentSaveComplete', $params );
2025 DeferredUpdates
::PRESEND
2032 * Get parser options suitable for rendering the primary article wikitext
2034 * @see ContentHandler::makeParserOptions
2036 * @param IContextSource|User|string $context One of the following:
2037 * - IContextSource: Use the User and the Language of the provided
2039 * - User: Use the provided User object and $wgLang for the language,
2040 * so use an IContextSource object if possible.
2041 * - 'canonical': Canonical options (anonymous user with default
2042 * preferences and content language).
2043 * @return ParserOptions
2045 public function makeParserOptions( $context ) {
2046 $options = $this->getContentHandler()->makeParserOptions( $context );
2048 if ( $this->getTitle()->isConversionTable() ) {
2049 // @todo ConversionTable should become a separate content model, so
2050 // we don't need special cases like this one.
2051 $options->disableContentConversion();
2058 * Prepare content which is about to be saved.
2059 * Returns a stdClass with source, pst and output members
2061 * @param Content $content
2062 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2063 * revision ID is also accepted, but this is deprecated.
2064 * @param User|null $user
2065 * @param string|null $serialFormat
2066 * @param bool $useCache Check shared prepared edit cache
2072 public function prepareContentForEdit(
2073 Content
$content, $revision = null, User
$user = null,
2074 $serialFormat = null, $useCache = true
2076 global $wgContLang, $wgUser, $wgAjaxEditStash;
2078 if ( is_object( $revision ) ) {
2079 $revid = $revision->getId();
2082 // This code path is deprecated, and nothing is known to
2083 // use it, so performance here shouldn't be a worry.
2084 if ( $revid !== null ) {
2085 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2091 $user = is_null( $user ) ?
$wgUser : $user;
2092 // XXX: check $user->getId() here???
2094 // Use a sane default for $serialFormat, see bug 57026
2095 if ( $serialFormat === null ) {
2096 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2099 if ( $this->mPreparedEdit
2100 && isset( $this->mPreparedEdit
->newContent
)
2101 && $this->mPreparedEdit
->newContent
->equals( $content )
2102 && $this->mPreparedEdit
->revid
== $revid
2103 && $this->mPreparedEdit
->format
== $serialFormat
2104 // XXX: also check $user here?
2107 return $this->mPreparedEdit
;
2110 // The edit may have already been prepared via api.php?action=stashedit
2111 $cachedEdit = $useCache && $wgAjaxEditStash
2112 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2115 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2116 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2119 if ( $cachedEdit ) {
2120 $edit->timestamp
= $cachedEdit->timestamp
;
2122 $edit->timestamp
= wfTimestampNow();
2124 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2125 $edit->revid
= $revid;
2127 if ( $cachedEdit ) {
2128 $edit->pstContent
= $cachedEdit->pstContent
;
2130 $edit->pstContent
= $content
2131 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2135 $edit->format
= $serialFormat;
2136 $edit->popts
= $this->makeParserOptions( 'canonical' );
2137 if ( $cachedEdit ) {
2138 $edit->output
= $cachedEdit->output
;
2141 // We get here if vary-revision is set. This means that this page references
2142 // itself (such as via self-transclusion). In this case, we need to make sure
2143 // that any such self-references refer to the newly-saved revision, and not
2144 // to the previous one, which could otherwise happen due to replica DB lag.
2145 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2146 $edit->popts
->setCurrentRevisionCallback(
2147 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2148 if ( $title->equals( $revision->getTitle() ) ) {
2151 return call_user_func( $oldCallback, $title, $parser );
2156 // Try to avoid a second parse if {{REVISIONID}} is used
2157 $edit->popts
->setSpeculativeRevIdCallback( function () {
2158 return 1 +
(int)wfGetDB( DB_MASTER
)->selectField(
2166 $edit->output
= $edit->pstContent
2167 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2171 $edit->newContent
= $content;
2172 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2174 // NOTE: B/C for hooks! don't use these fields!
2175 $edit->newText
= $edit->newContent
2176 ? ContentHandler
::getContentText( $edit->newContent
)
2178 $edit->oldText
= $edit->oldContent
2179 ? ContentHandler
::getContentText( $edit->oldContent
)
2181 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2183 if ( $edit->output
) {
2184 $edit->output
->setCacheTime( wfTimestampNow() );
2187 // Process cache the result
2188 $this->mPreparedEdit
= $edit;
2194 * Do standard deferred updates after page edit.
2195 * Update links tables, site stats, search index and message cache.
2196 * Purges pages that include this page if the text was changed here.
2197 * Every 100th edit, prune the recent changes table.
2199 * @param Revision $revision
2200 * @param User $user User object that did the revision
2201 * @param array $options Array of options, following indexes are used:
2202 * - changed: boolean, whether the revision changed the content (default true)
2203 * - created: boolean, whether the revision created the page (default false)
2204 * - moved: boolean, whether the page was moved (default false)
2205 * - restored: boolean, whether the page was undeleted (default false)
2206 * - oldrevision: Revision object for the pre-update revision (default null)
2207 * - oldcountable: boolean, null, or string 'no-change' (default null):
2208 * - boolean: whether the page was counted as an article before that
2209 * revision, only used in changed is true and created is false
2210 * - null: if created is false, don't update the article count; if created
2211 * is true, do update the article count
2212 * - 'no-change': don't update the article count, ever
2214 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2215 global $wgRCWatchCategoryMembership, $wgContLang;
2221 'restored' => false,
2222 'oldrevision' => null,
2223 'oldcountable' => null
2225 $content = $revision->getContent();
2227 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2229 // See if the parser output before $revision was inserted is still valid
2231 if ( !$this->mPreparedEdit
) {
2232 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2233 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2234 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2235 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2236 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2238 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2239 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2240 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2242 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2243 $editInfo = $this->mPreparedEdit
;
2247 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2248 // $text is usually already pre-save transformed once. Avoid using the edit stash
2249 // as any prepared content from there or in doEditContent() was already rejected.
2250 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2253 // Save it to the parser cache.
2254 // Make sure the cache time matches page_touched to avoid double parsing.
2255 ParserCache
::singleton()->save(
2256 $editInfo->output
, $this, $editInfo->popts
,
2257 $revision->getTimestamp(), $editInfo->revid
2260 // Update the links tables and other secondary data
2262 $recursive = $options['changed']; // bug 50785
2263 $updates = $content->getSecondaryDataUpdates(
2264 $this->getTitle(), null, $recursive, $editInfo->output
2266 foreach ( $updates as $update ) {
2267 if ( $update instanceof LinksUpdate
) {
2268 $update->setRevision( $revision );
2269 $update->setTriggeringUser( $user );
2271 DeferredUpdates
::addUpdate( $update );
2273 if ( $wgRCWatchCategoryMembership
2274 && $this->getContentHandler()->supportsCategories() === true
2275 && ( $options['changed'] ||
$options['created'] )
2276 && !$options['restored']
2278 // Note: jobs are pushed after deferred updates, so the job should be able to see
2279 // the recent change entry (also done via deferred updates) and carry over any
2280 // bot/deletion/IP flags, ect.
2281 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2284 'pageId' => $this->getId(),
2285 'revTimestamp' => $revision->getTimestamp()
2291 Hooks
::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2293 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2294 // Flush old entries from the `recentchanges` table
2295 if ( mt_rand( 0, 9 ) == 0 ) {
2296 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2300 if ( !$this->exists() ) {
2304 $id = $this->getId();
2305 $title = $this->mTitle
->getPrefixedDBkey();
2306 $shortTitle = $this->mTitle
->getDBkey();
2308 if ( $options['oldcountable'] === 'no-change' ||
2309 ( !$options['changed'] && !$options['moved'] )
2312 } elseif ( $options['created'] ) {
2313 $good = (int)$this->isCountable( $editInfo );
2314 } elseif ( $options['oldcountable'] !== null ) {
2315 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2319 $edits = $options['changed'] ?
1 : 0;
2320 $total = $options['created'] ?
1 : 0;
2322 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2323 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2325 // If this is another user's talk page, update newtalk.
2326 // Don't do this if $options['changed'] = false (null-edits) nor if
2327 // it's a minor edit and the user doesn't want notifications for those.
2328 if ( $options['changed']
2329 && $this->mTitle
->getNamespace() == NS_USER_TALK
2330 && $shortTitle != $user->getTitleKey()
2331 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2333 $recipient = User
::newFromName( $shortTitle, false );
2334 if ( !$recipient ) {
2335 wfDebug( __METHOD__
. ": invalid username\n" );
2337 // Allow extensions to prevent user notification
2338 // when a new message is added to their talk page
2339 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2340 if ( User
::isIP( $shortTitle ) ) {
2341 // An anonymous user
2342 $recipient->setNewtalk( true, $revision );
2343 } elseif ( $recipient->isLoggedIn() ) {
2344 $recipient->setNewtalk( true, $revision );
2346 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2352 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2353 // XXX: could skip pseudo-messages like js/css here, based on content model.
2354 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2355 if ( $msgtext === false ||
$msgtext === null ) {
2359 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2361 if ( $wgContLang->hasVariants() ) {
2362 $wgContLang->updateConversionTable( $this->mTitle
);
2366 if ( $options['created'] ) {
2367 self
::onArticleCreate( $this->mTitle
);
2368 } elseif ( $options['changed'] ) { // bug 50785
2369 self
::onArticleEdit( $this->mTitle
, $revision );
2372 ResourceLoaderWikiModule
::invalidateModuleCache(
2373 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2378 * Update the article's restriction field, and leave a log entry.
2379 * This works for protection both existing and non-existing pages.
2381 * @param array $limit Set of restriction keys
2382 * @param array $expiry Per restriction type expiration
2383 * @param int &$cascade Set to false if cascading protection isn't allowed.
2384 * @param string $reason
2385 * @param User $user The user updating the restrictions
2386 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2387 * ($user should be able to add the specified tags before this is called)
2388 * @return Status Status object; if action is taken, $status->value is the log_id of the
2389 * protection log entry.
2391 public function doUpdateRestrictions( array $limit, array $expiry,
2392 &$cascade, $reason, User
$user, $tags = null
2394 global $wgCascadingRestrictionLevels, $wgContLang;
2396 if ( wfReadOnly() ) {
2397 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2400 $this->loadPageData( 'fromdbmaster' );
2401 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2402 $id = $this->getId();
2408 // Take this opportunity to purge out expired restrictions
2409 Title
::purgeExpiredRestrictions();
2411 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2412 // we expect a single selection, but the schema allows otherwise.
2413 $isProtected = false;
2417 $dbw = wfGetDB( DB_MASTER
);
2419 foreach ( $restrictionTypes as $action ) {
2420 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2421 $expiry[$action] = 'infinity';
2423 if ( !isset( $limit[$action] ) ) {
2424 $limit[$action] = '';
2425 } elseif ( $limit[$action] != '' ) {
2429 // Get current restrictions on $action
2430 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2431 if ( $current != '' ) {
2432 $isProtected = true;
2435 if ( $limit[$action] != $current ) {
2437 } elseif ( $limit[$action] != '' ) {
2438 // Only check expiry change if the action is actually being
2439 // protected, since expiry does nothing on an not-protected
2441 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2447 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2451 // If nothing has changed, do nothing
2453 return Status
::newGood();
2456 if ( !$protect ) { // No protection at all means unprotection
2457 $revCommentMsg = 'unprotectedarticle-comment';
2458 $logAction = 'unprotect';
2459 } elseif ( $isProtected ) {
2460 $revCommentMsg = 'modifiedarticleprotection-comment';
2461 $logAction = 'modify';
2463 $revCommentMsg = 'protectedarticle-comment';
2464 $logAction = 'protect';
2467 // Truncate for whole multibyte characters
2468 $reason = $wgContLang->truncate( $reason, 255 );
2470 $logRelationsValues = [];
2471 $logRelationsField = null;
2472 $logParamsDetails = [];
2474 // Null revision (used for change tag insertion)
2475 $nullRevision = null;
2477 if ( $id ) { // Protection of existing page
2478 if ( !Hooks
::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2479 return Status
::newGood();
2482 // Only certain restrictions can cascade...
2483 $editrestriction = isset( $limit['edit'] )
2484 ?
[ $limit['edit'] ]
2485 : $this->mTitle
->getRestrictions( 'edit' );
2486 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2487 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2489 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2490 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2493 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2494 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2495 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2497 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2498 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2501 // The schema allows multiple restrictions
2502 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2506 // insert null revision to identify the page protection change as edit summary
2507 $latest = $this->getLatest();
2508 $nullRevision = $this->insertProtectNullRevision(
2517 if ( $nullRevision === null ) {
2518 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2521 $logRelationsField = 'pr_id';
2523 // Update restrictions table
2524 foreach ( $limit as $action => $restrictions ) {
2526 'page_restrictions',
2529 'pr_type' => $action
2533 if ( $restrictions != '' ) {
2534 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2536 'page_restrictions',
2538 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2540 'pr_type' => $action,
2541 'pr_level' => $restrictions,
2542 'pr_cascade' => $cascadeValue,
2543 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2547 $logRelationsValues[] = $dbw->insertId();
2548 $logParamsDetails[] = [
2550 'level' => $restrictions,
2551 'expiry' => $expiry[$action],
2552 'cascade' => (bool)$cascadeValue,
2557 // Clear out legacy restriction fields
2560 [ 'page_restrictions' => '' ],
2561 [ 'page_id' => $id ],
2565 Hooks
::run( 'NewRevisionFromEditComplete',
2566 [ $this, $nullRevision, $latest, $user ] );
2567 Hooks
::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2568 } else { // Protection of non-existing page (also known as "title protection")
2569 // Cascade protection is meaningless in this case
2572 if ( $limit['create'] != '' ) {
2573 $dbw->replace( 'protected_titles',
2574 [ [ 'pt_namespace', 'pt_title' ] ],
2576 'pt_namespace' => $this->mTitle
->getNamespace(),
2577 'pt_title' => $this->mTitle
->getDBkey(),
2578 'pt_create_perm' => $limit['create'],
2579 'pt_timestamp' => $dbw->timestamp(),
2580 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2581 'pt_user' => $user->getId(),
2582 'pt_reason' => $reason,
2585 $logParamsDetails[] = [
2587 'level' => $limit['create'],
2588 'expiry' => $expiry['create'],
2591 $dbw->delete( 'protected_titles',
2593 'pt_namespace' => $this->mTitle
->getNamespace(),
2594 'pt_title' => $this->mTitle
->getDBkey()
2600 $this->mTitle
->flushRestrictions();
2601 InfoAction
::invalidateCache( $this->mTitle
);
2603 if ( $logAction == 'unprotect' ) {
2606 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2608 '4::description' => $protectDescriptionLog, // parameter for IRC
2609 '5:bool:cascade' => $cascade,
2610 'details' => $logParamsDetails, // parameter for localize and api
2614 // Update the protection log
2615 $logEntry = new ManualLogEntry( 'protect', $logAction );
2616 $logEntry->setTarget( $this->mTitle
);
2617 $logEntry->setComment( $reason );
2618 $logEntry->setPerformer( $user );
2619 $logEntry->setParameters( $params );
2620 if ( !is_null( $nullRevision ) ) {
2621 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2623 $logEntry->setTags( $tags );
2624 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2625 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2627 $logId = $logEntry->insert();
2628 $logEntry->publish( $logId );
2630 return Status
::newGood( $logId );
2634 * Insert a new null revision for this page.
2636 * @param string $revCommentMsg Comment message key for the revision
2637 * @param array $limit Set of restriction keys
2638 * @param array $expiry Per restriction type expiration
2639 * @param int $cascade Set to false if cascading protection isn't allowed.
2640 * @param string $reason
2641 * @param User|null $user
2642 * @return Revision|null Null on error
2644 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2645 array $expiry, $cascade, $reason, $user = null
2647 $dbw = wfGetDB( DB_MASTER
);
2649 // Prepare a null revision to be added to the history
2650 $editComment = wfMessage(
2652 $this->mTitle
->getPrefixedText(),
2653 $user ?
$user->getName() : ''
2654 )->inContentLanguage()->text();
2656 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2658 $protectDescription = $this->protectDescription( $limit, $expiry );
2659 if ( $protectDescription ) {
2660 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2661 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2662 ->inContentLanguage()->text();
2665 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2666 $editComment .= wfMessage( 'brackets' )->params(
2667 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2668 )->inContentLanguage()->text();
2671 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2673 $nullRev->insertOn( $dbw );
2675 // Update page record and touch page
2676 $oldLatest = $nullRev->getParentId();
2677 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2684 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2687 protected function formatExpiry( $expiry ) {
2690 if ( $expiry != 'infinity' ) {
2693 $wgContLang->timeanddate( $expiry, false, false ),
2694 $wgContLang->date( $expiry, false, false ),
2695 $wgContLang->time( $expiry, false, false )
2696 )->inContentLanguage()->text();
2698 return wfMessage( 'protect-expiry-indefinite' )
2699 ->inContentLanguage()->text();
2704 * Builds the description to serve as comment for the edit.
2706 * @param array $limit Set of restriction keys
2707 * @param array $expiry Per restriction type expiration
2710 public function protectDescription( array $limit, array $expiry ) {
2711 $protectDescription = '';
2713 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2714 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2715 # All possible message keys are listed here for easier grepping:
2716 # * restriction-create
2717 # * restriction-edit
2718 # * restriction-move
2719 # * restriction-upload
2720 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2721 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2722 # with '' filtered out. All possible message keys are listed below:
2723 # * protect-level-autoconfirmed
2724 # * protect-level-sysop
2725 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2726 ->inContentLanguage()->text();
2728 $expiryText = $this->formatExpiry( $expiry[$action] );
2730 if ( $protectDescription !== '' ) {
2731 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2733 $protectDescription .= wfMessage( 'protect-summary-desc' )
2734 ->params( $actionText, $restrictionsText, $expiryText )
2735 ->inContentLanguage()->text();
2738 return $protectDescription;
2742 * Builds the description to serve as comment for the log entry.
2744 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2745 * protect description text. Keep them in old format to avoid breaking compatibility.
2746 * TODO: Fix protection log to store structured description and format it on-the-fly.
2748 * @param array $limit Set of restriction keys
2749 * @param array $expiry Per restriction type expiration
2752 public function protectDescriptionLog( array $limit, array $expiry ) {
2755 $protectDescriptionLog = '';
2757 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2758 $expiryText = $this->formatExpiry( $expiry[$action] );
2759 $protectDescriptionLog .= $wgContLang->getDirMark() .
2760 "[$action=$restrictions] ($expiryText)";
2763 return trim( $protectDescriptionLog );
2767 * Take an array of page restrictions and flatten it to a string
2768 * suitable for insertion into the page_restrictions field.
2770 * @param string[] $limit
2772 * @throws MWException
2775 protected static function flattenRestrictions( $limit ) {
2776 if ( !is_array( $limit ) ) {
2777 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2783 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2784 $bits[] = "$action=$restrictions";
2787 return implode( ':', $bits );
2791 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2792 * backwards compatibility, if you care about error reporting you should use
2793 * doDeleteArticleReal() instead.
2795 * Deletes the article with database consistency, writes logs, purges caches
2797 * @param string $reason Delete reason for deletion log
2798 * @param bool $suppress Suppress all revisions and log the deletion in
2799 * the suppression log instead of the deletion log
2800 * @param int $u1 Unused
2801 * @param bool $u2 Unused
2802 * @param array|string &$error Array of errors to append to
2803 * @param User $user The deleting user
2804 * @return bool True if successful
2806 public function doDeleteArticle(
2807 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2809 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2810 return $status->isGood();
2814 * Back-end article deletion
2815 * Deletes the article with database consistency, writes logs, purges caches
2819 * @param string $reason Delete reason for deletion log
2820 * @param bool $suppress Suppress all revisions and log the deletion in
2821 * the suppression log instead of the deletion log
2822 * @param int $u1 Unused
2823 * @param bool $u2 Unused
2824 * @param array|string &$error Array of errors to append to
2825 * @param User $user The deleting user
2826 * @param array $tags Tags to apply to the deletion action
2827 * @return Status Status object; if successful, $status->value is the log_id of the
2828 * deletion log entry. If the page couldn't be deleted because it wasn't
2829 * found, $status is a non-fatal 'cannotdelete' error
2831 public function doDeleteArticleReal(
2832 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2833 $tags = [], $logsubtype = 'delete'
2835 global $wgUser, $wgContentHandlerUseDB;
2837 wfDebug( __METHOD__
. "\n" );
2839 $status = Status
::newGood();
2841 if ( $this->mTitle
->getDBkey() === '' ) {
2842 $status->error( 'cannotdelete',
2843 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2847 $user = is_null( $user ) ?
$wgUser : $user;
2848 if ( !Hooks
::run( 'ArticleDelete',
2849 [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2851 if ( $status->isOK() ) {
2852 // Hook aborted but didn't set a fatal status
2853 $status->fatal( 'delete-hook-aborted' );
2858 $dbw = wfGetDB( DB_MASTER
);
2859 $dbw->startAtomic( __METHOD__
);
2861 $this->loadPageData( self
::READ_LATEST
);
2862 $id = $this->getId();
2863 // T98706: lock the page from various other updates but avoid using
2864 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2865 // the revisions queries (which also JOIN on user). Only lock the page
2866 // row and CAS check on page_latest to see if the trx snapshot matches.
2867 $lockedLatest = $this->lockAndGetLatest();
2868 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2869 $dbw->endAtomic( __METHOD__
);
2870 // Page not there or trx snapshot is stale
2871 $status->error( 'cannotdelete',
2872 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2876 // Given the lock above, we can be confident in the title and page ID values
2877 $namespace = $this->getTitle()->getNamespace();
2878 $dbKey = $this->getTitle()->getDBkey();
2880 // At this point we are now comitted to returning an OK
2881 // status unless some DB query error or other exception comes up.
2882 // This way callers don't have to call rollback() if $status is bad
2883 // unless they actually try to catch exceptions (which is rare).
2885 // we need to remember the old content so we can use it to generate all deletion updates.
2886 $revision = $this->getRevision();
2888 $content = $this->getContent( Revision
::RAW
);
2889 } catch ( Exception
$ex ) {
2890 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2891 . $ex->getMessage() );
2896 $fields = Revision
::selectFields();
2899 // Bitfields to further suppress the content
2901 $bitfield = Revision
::SUPPRESSED_ALL
;
2902 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2905 // For now, shunt the revision data into the archive table.
2906 // Text is *not* removed from the text table; bulk storage
2907 // is left intact to avoid breaking block-compression or
2908 // immutable storage schemes.
2909 // In the future, we may keep revisions and mark them with
2910 // the rev_deleted field, which is reserved for this purpose.
2912 // Get all of the page revisions
2913 $res = $dbw->select(
2916 [ 'rev_page' => $id ],
2920 // Build their equivalent archive rows
2922 foreach ( $res as $row ) {
2924 'ar_namespace' => $namespace,
2925 'ar_title' => $dbKey,
2926 'ar_comment' => $row->rev_comment
,
2927 'ar_user' => $row->rev_user
,
2928 'ar_user_text' => $row->rev_user_text
,
2929 'ar_timestamp' => $row->rev_timestamp
,
2930 'ar_minor_edit' => $row->rev_minor_edit
,
2931 'ar_rev_id' => $row->rev_id
,
2932 'ar_parent_id' => $row->rev_parent_id
,
2933 'ar_text_id' => $row->rev_text_id
,
2936 'ar_len' => $row->rev_len
,
2937 'ar_page_id' => $id,
2938 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2939 'ar_sha1' => $row->rev_sha1
,
2941 if ( $wgContentHandlerUseDB ) {
2942 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2943 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2945 $rowsInsert[] = $rowInsert;
2947 // Copy them into the archive table
2948 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2949 // Save this so we can pass it to the ArticleDeleteComplete hook.
2950 $archivedRevisionCount = $dbw->affectedRows();
2952 // Clone the title and wikiPage, so we have the information we need when
2953 // we log and run the ArticleDeleteComplete hook.
2954 $logTitle = clone $this->mTitle
;
2955 $wikiPageBeforeDelete = clone $this;
2957 // Now that it's safely backed up, delete it
2958 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2959 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2961 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2962 $logtype = $suppress ?
'suppress' : 'delete';
2964 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2965 $logEntry->setPerformer( $user );
2966 $logEntry->setTarget( $logTitle );
2967 $logEntry->setComment( $reason );
2968 $logEntry->setTags( $tags );
2969 $logid = $logEntry->insert();
2971 $dbw->onTransactionPreCommitOrIdle(
2972 function () use ( $dbw, $logEntry, $logid ) {
2973 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2974 $logEntry->publish( $logid );
2979 $dbw->endAtomic( __METHOD__
);
2981 $this->doDeleteUpdates( $id, $content, $revision );
2983 Hooks
::run( 'ArticleDeleteComplete', [
2984 &$wikiPageBeforeDelete,
2990 $archivedRevisionCount
2992 $status->value
= $logid;
2994 // Show log excerpt on 404 pages rather than just a link
2995 $cache = ObjectCache
::getMainStashInstance();
2996 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2997 $cache->set( $key, 1, $cache::TTL_DAY
);
3003 * Lock the page row for this title+id and return page_latest (or 0)
3005 * @return integer Returns 0 if no row was found with this title+id
3008 public function lockAndGetLatest() {
3009 return (int)wfGetDB( DB_MASTER
)->selectField(
3013 'page_id' => $this->getId(),
3014 // Typically page_id is enough, but some code might try to do
3015 // updates assuming the title is the same, so verify that
3016 'page_namespace' => $this->getTitle()->getNamespace(),
3017 'page_title' => $this->getTitle()->getDBkey()
3025 * Do some database updates after deletion
3027 * @param int $id The page_id value of the page being deleted
3028 * @param Content|null $content Optional page content to be used when determining
3029 * the required updates. This may be needed because $this->getContent()
3030 * may already return null when the page proper was deleted.
3031 * @param Revision|null $revision The latest page revision
3033 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
3035 $countable = $this->isCountable();
3036 } catch ( Exception
$ex ) {
3037 // fallback for deleting broken pages for which we cannot load the content for
3038 // some reason. Note that doDeleteArticleReal() already logged this problem.
3042 // Update site status
3043 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3045 // Delete pagelinks, update secondary indexes, etc
3046 $updates = $this->getDeletionUpdates( $content );
3047 foreach ( $updates as $update ) {
3048 DeferredUpdates
::addUpdate( $update );
3051 // Reparse any pages transcluding this page
3052 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
3054 // Reparse any pages including this image
3055 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3056 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
3060 WikiPage
::onArticleDelete( $this->mTitle
);
3061 ResourceLoaderWikiModule
::invalidateModuleCache(
3062 $this->mTitle
, $revision, null, wfWikiID()
3065 // Reset this object and the Title object
3066 $this->loadFromRow( false, self
::READ_LATEST
);
3069 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3073 * Roll back the most recent consecutive set of edits to a page
3074 * from the same user; fails if there are no eligible edits to
3075 * roll back to, e.g. user is the sole contributor. This function
3076 * performs permissions checks on $user, then calls commitRollback()
3077 * to do the dirty work
3079 * @todo Separate the business/permission stuff out from backend code
3080 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3082 * @param string $fromP Name of the user whose edits to rollback.
3083 * @param string $summary Custom summary. Set to default summary if empty.
3084 * @param string $token Rollback token.
3085 * @param bool $bot If true, mark all reverted edits as bot.
3087 * @param array $resultDetails Array contains result-specific array of additional values
3088 * 'alreadyrolled' : 'current' (rev)
3089 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3091 * @param User $user The user performing the rollback
3092 * @param array|null $tags Change tags to apply to the rollback
3093 * Callers are responsible for permission checks
3094 * (with ChangeTags::canAddTagsAccompanyingChange)
3096 * @return array Array of errors, each error formatted as
3097 * array(messagekey, param1, param2, ...).
3098 * On success, the array is empty. This array can also be passed to
3099 * OutputPage::showPermissionsErrorPage().
3101 public function doRollback(
3102 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3104 $resultDetails = null;
3106 // Check permissions
3107 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3108 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3109 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3111 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3112 $errors[] = [ 'sessionfailure' ];
3115 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3116 $errors[] = [ 'actionthrottledtext' ];
3119 // If there were errors, bail out now
3120 if ( !empty( $errors ) ) {
3124 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3128 * Backend implementation of doRollback(), please refer there for parameter
3129 * and return value documentation
3131 * NOTE: This function does NOT check ANY permissions, it just commits the
3132 * rollback to the DB. Therefore, you should only call this function direct-
3133 * ly if you want to use custom permissions checks. If you don't, use
3134 * doRollback() instead.
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 bool $bot If true, mark all reverted edits as bot.
3139 * @param array $resultDetails Contains result-specific array of additional values
3140 * @param User $guser The user performing the rollback
3141 * @param array|null $tags Change tags to apply to the rollback
3142 * Callers are responsible for permission checks
3143 * (with ChangeTags::canAddTagsAccompanyingChange)
3147 public function commitRollback( $fromP, $summary, $bot,
3148 &$resultDetails, User
$guser, $tags = null
3150 global $wgUseRCPatrol, $wgContLang;
3152 $dbw = wfGetDB( DB_MASTER
);
3154 if ( wfReadOnly() ) {
3155 return [ [ 'readonlytext' ] ];
3158 // Get the last editor
3159 $current = $this->getRevision();
3160 if ( is_null( $current ) ) {
3161 // Something wrong... no page?
3162 return [ [ 'notanarticle' ] ];
3165 $from = str_replace( '_', ' ', $fromP );
3166 // User name given should match up with the top revision.
3167 // If the user was deleted then $from should be empty.
3168 if ( $from != $current->getUserText() ) {
3169 $resultDetails = [ 'current' => $current ];
3170 return [ [ 'alreadyrolled',
3171 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3172 htmlspecialchars( $fromP ),
3173 htmlspecialchars( $current->getUserText() )
3177 // Get the last edit not by this person...
3178 // Note: these may not be public values
3179 $user = intval( $current->getUser( Revision
::RAW
) );
3180 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3181 $s = $dbw->selectRow( 'revision',
3182 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3183 [ 'rev_page' => $current->getPage(),
3184 "rev_user != {$user} OR rev_user_text != {$user_text}"
3186 [ 'USE INDEX' => 'page_timestamp',
3187 'ORDER BY' => 'rev_timestamp DESC' ]
3189 if ( $s === false ) {
3190 // No one else ever edited this page
3191 return [ [ 'cantrollback' ] ];
3192 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3193 ||
$s->rev_deleted
& Revision
::DELETED_USER
3195 // Only admins can see this text
3196 return [ [ 'notvisiblerev' ] ];
3199 // Generate the edit summary if necessary
3200 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3201 if ( empty( $summary ) ) {
3202 if ( $from == '' ) { // no public user name
3203 $summary = wfMessage( 'revertpage-nouser' );
3205 $summary = wfMessage( 'revertpage' );
3209 // Allow the custom summary to use the same args as the default message
3211 $target->getUserText(), $from, $s->rev_id
,
3212 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3213 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3215 if ( $summary instanceof Message
) {
3216 $summary = $summary->params( $args )->inContentLanguage()->text();
3218 $summary = wfMsgReplaceArgs( $summary, $args );
3221 // Trim spaces on user supplied text
3222 $summary = trim( $summary );
3224 // Truncate for whole multibyte characters.
3225 $summary = $wgContLang->truncate( $summary, 255 );
3228 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3230 if ( $guser->isAllowed( 'minoredit' ) ) {
3231 $flags |
= EDIT_MINOR
;
3234 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3235 $flags |
= EDIT_FORCE_BOT
;
3238 $targetContent = $target->getContent();
3239 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3241 // Actually store the edit
3242 $status = $this->doEditContent(
3252 // Set patrolling and bot flag on the edits, which gets rollbacked.
3253 // This is done even on edit failure to have patrolling in that case (bug 62157).
3255 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3256 // Mark all reverted edits as bot
3260 if ( $wgUseRCPatrol ) {
3261 // Mark all reverted edits as patrolled
3262 $set['rc_patrolled'] = 1;
3265 if ( count( $set ) ) {
3266 $dbw->update( 'recentchanges', $set,
3268 'rc_cur_id' => $current->getPage(),
3269 'rc_user_text' => $current->getUserText(),
3270 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3276 if ( !$status->isOK() ) {
3277 return $status->getErrorsArray();
3280 // raise error, when the edit is an edit without a new version
3281 $statusRev = isset( $status->value
['revision'] )
3282 ?
$status->value
['revision']
3284 if ( !( $statusRev instanceof Revision
) ) {
3285 $resultDetails = [ 'current' => $current ];
3286 return [ [ 'alreadyrolled',
3287 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3288 htmlspecialchars( $fromP ),
3289 htmlspecialchars( $current->getUserText() )
3293 if ( $changingContentModel ) {
3294 // If the content model changed during the rollback,
3295 // make sure it gets logged to Special:Log/contentmodel
3296 $log = new ManualLogEntry( 'contentmodel', 'change' );
3297 $log->setPerformer( $guser );
3298 $log->setTarget( $this->mTitle
);
3299 $log->setComment( $summary );
3300 $log->setParameters( [
3301 '4::oldmodel' => $current->getContentModel(),
3302 '5::newmodel' => $targetContent->getModel(),
3305 $logId = $log->insert( $dbw );
3306 $log->publish( $logId );
3309 $revId = $statusRev->getId();
3311 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3314 'summary' => $summary,
3315 'current' => $current,
3316 'target' => $target,
3324 * The onArticle*() functions are supposed to be a kind of hooks
3325 * which should be called whenever any of the specified actions
3328 * This is a good place to put code to clear caches, for instance.
3330 * This is called on page move and undelete, as well as edit
3332 * @param Title $title
3334 public static function onArticleCreate( Title
$title ) {
3335 // Update existence markers on article/talk tabs...
3336 $other = $title->getOtherPage();
3338 $other->purgeSquid();
3340 $title->touchLinks();
3341 $title->purgeSquid();
3342 $title->deleteTitleProtection();
3344 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3346 if ( $title->getNamespace() == NS_CATEGORY
) {
3347 // Load the Category object, which will schedule a job to create
3348 // the category table row if necessary. Checking a replica DB is ok
3349 // here, in the worst case it'll run an unnecessary recount job on
3350 // a category that probably doesn't have many members.
3351 Category
::newFromTitle( $title )->getID();
3356 * Clears caches when article is deleted
3358 * @param Title $title
3360 public static function onArticleDelete( Title
$title ) {
3363 // Update existence markers on article/talk tabs...
3364 $other = $title->getOtherPage();
3366 $other->purgeSquid();
3368 $title->touchLinks();
3369 $title->purgeSquid();
3371 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3374 HTMLFileCache
::clearFileCache( $title );
3375 InfoAction
::invalidateCache( $title );
3378 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3379 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3381 if ( $wgContLang->hasVariants() ) {
3382 $wgContLang->updateConversionTable( $title );
3387 if ( $title->getNamespace() == NS_FILE
) {
3388 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3392 if ( $title->getNamespace() == NS_USER_TALK
) {
3393 $user = User
::newFromName( $title->getText(), false );
3395 $user->setNewtalk( false );
3400 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3404 * Purge caches on page update etc
3406 * @param Title $title
3407 * @param Revision|null $revision Revision that was just saved, may be null
3409 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3410 // Invalidate caches of articles which include this page
3411 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3413 // Invalidate the caches of all pages which redirect here
3414 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3416 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3418 // Purge CDN for this page only
3419 $title->purgeSquid();
3420 // Clear file cache for this page only
3421 HTMLFileCache
::clearFileCache( $title );
3423 $revid = $revision ?
$revision->getId() : null;
3424 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3425 InfoAction
::invalidateCache( $title, $revid );
3432 * Returns a list of categories this page is a member of.
3433 * Results will include hidden categories
3435 * @return TitleArray
3437 public function getCategories() {
3438 $id = $this->getId();
3440 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3443 $dbr = wfGetDB( DB_REPLICA
);
3444 $res = $dbr->select( 'categorylinks',
3445 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3446 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3447 // as not being aliases, and NS_CATEGORY is numeric
3448 [ 'cl_from' => $id ],
3451 return TitleArray
::newFromResult( $res );
3455 * Returns a list of hidden categories this page is a member of.
3456 * Uses the page_props and categorylinks tables.
3458 * @return array Array of Title objects
3460 public function getHiddenCategories() {
3462 $id = $this->getId();
3468 $dbr = wfGetDB( DB_REPLICA
);
3469 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3471 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3472 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3475 if ( $res !== false ) {
3476 foreach ( $res as $row ) {
3477 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3485 * Auto-generates a deletion reason
3487 * @param bool &$hasHistory Whether the page has a history
3488 * @return string|bool String containing deletion reason or empty string, or boolean false
3489 * if no revision occurred
3491 public function getAutoDeleteReason( &$hasHistory ) {
3492 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3496 * Update all the appropriate counts in the category table, given that
3497 * we've added the categories $added and deleted the categories $deleted.
3499 * This should only be called from deferred updates or jobs to avoid contention.
3501 * @param array $added The names of categories that were added
3502 * @param array $deleted The names of categories that were deleted
3503 * @param integer $id Page ID (this should be the original deleted page ID)
3505 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3506 $id = $id ?
: $this->getId();
3507 $ns = $this->getTitle()->getNamespace();
3509 $addFields = [ 'cat_pages = cat_pages + 1' ];
3510 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3511 if ( $ns == NS_CATEGORY
) {
3512 $addFields[] = 'cat_subcats = cat_subcats + 1';
3513 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3514 } elseif ( $ns == NS_FILE
) {
3515 $addFields[] = 'cat_files = cat_files + 1';
3516 $removeFields[] = 'cat_files = cat_files - 1';
3519 $dbw = wfGetDB( DB_MASTER
);
3521 if ( count( $added ) ) {
3522 $existingAdded = $dbw->selectFieldValues(
3525 [ 'cat_title' => $added ],
3529 // For category rows that already exist, do a plain
3530 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3531 // to avoid creating gaps in the cat_id sequence.
3532 if ( count( $existingAdded ) ) {
3536 [ 'cat_title' => $existingAdded ],
3541 $missingAdded = array_diff( $added, $existingAdded );
3542 if ( count( $missingAdded ) ) {
3544 foreach ( $missingAdded as $cat ) {
3546 'cat_title' => $cat,
3548 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3549 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3562 if ( count( $deleted ) ) {
3566 [ 'cat_title' => $deleted ],
3571 foreach ( $added as $catName ) {
3572 $cat = Category
::newFromName( $catName );
3573 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3576 foreach ( $deleted as $catName ) {
3577 $cat = Category
::newFromName( $catName );
3578 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3581 // Refresh counts on categories that should be empty now, to
3582 // trigger possible deletion. Check master for the most
3583 // up-to-date cat_pages.
3584 if ( count( $deleted ) ) {
3585 $rows = $dbw->select(
3587 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3588 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3591 foreach ( $rows as $row ) {
3592 $cat = Category
::newFromRow( $row );
3593 $cat->refreshCounts();
3599 * Opportunistically enqueue link update jobs given fresh parser output if useful
3601 * @param ParserOutput $parserOutput Current version page output
3604 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3605 if ( wfReadOnly() ) {
3609 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3610 [ $this, $this->mTitle
, $parserOutput ]
3615 $config = RequestContext
::getMain()->getConfig();
3618 'isOpportunistic' => true,
3619 'rootJobTimestamp' => $parserOutput->getCacheTime()
3622 if ( $this->mTitle
->areRestrictionsCascading() ) {
3623 // If the page is cascade protecting, the links should really be up-to-date
3624 JobQueueGroup
::singleton()->lazyPush(
3625 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3627 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3628 // Assume the output contains "dynamic" time/random based magic words.
3629 // Only update pages that expired due to dynamic content and NOT due to edits
3630 // to referenced templates/files. When the cache expires due to dynamic content,
3631 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3632 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3633 // template/file edit already triggered recursive RefreshLinksJob jobs.
3634 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3635 // If a page is uncacheable, do not keep spamming a job for it.
3636 // Although it would be de-duplicated, it would still waste I/O.
3637 $cache = ObjectCache
::getLocalClusterInstance();
3638 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3639 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3640 if ( $cache->add( $key, time(), $ttl ) ) {
3641 JobQueueGroup
::singleton()->lazyPush(
3642 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3650 * Returns a list of updates to be performed when this page is deleted. The
3651 * updates should remove any information about this page from secondary data
3652 * stores such as links tables.
3654 * @param Content|null $content Optional Content object for determining the
3655 * necessary updates.
3656 * @return DeferrableUpdate[]
3658 public function getDeletionUpdates( Content
$content = null ) {
3660 // load content object, which may be used to determine the necessary updates.
3661 // XXX: the content may not be needed to determine the updates.
3663 $content = $this->getContent( Revision
::RAW
);
3664 } catch ( Exception
$ex ) {
3665 // If we can't load the content, something is wrong. Perhaps that's why
3666 // the user is trying to delete the page, so let's not fail in that case.
3667 // Note that doDeleteArticleReal() will already have logged an issue with
3668 // loading the content.
3675 $updates = $content->getDeletionUpdates( $this );
3678 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3683 * Whether this content displayed on this page
3684 * comes from the local database
3689 public function isLocal() {
3694 * The display name for the site this content
3695 * come from. If a subclass overrides isLocal(),
3696 * this could return something other than the
3702 public function getWikiDisplayName() {
3708 * Get the source URL for the content on this page,
3709 * typically the canonical URL, but may be a remote
3710 * link if the content comes from another site
3715 public function getSourceURL() {
3716 return $this->getTitle()->getCanonicalURL();