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
;
25 use Wikimedia\Rdbms\FakeResultWrapper
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use Wikimedia\Rdbms\DBError
;
28 use Wikimedia\Rdbms\DBUnexpectedError
;
31 * Class representing a MediaWiki article and history.
33 * Some fields are public only for backwards-compatibility. Use accessors.
34 * In the past, this class was part of Article.php and everything was public.
36 class WikiPage
implements Page
, IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
52 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
53 public $mPreparedEdit = false;
58 protected $mId = null;
61 * @var int One of the READ_* constants
63 protected $mDataLoadedFrom = self
::READ_NONE
;
68 protected $mRedirectTarget = null;
73 protected $mLastRevision = null;
76 * @var string Timestamp of the current revision or empty string if not loaded
78 protected $mTimestamp = '';
83 protected $mTouched = '19700101000000';
88 protected $mLinksUpdated = '19700101000000';
90 /** @deprecated since 1.29. Added in 1.28 for partial purging, no longer used. */
91 const PURGE_CDN_CACHE
= 1;
92 const PURGE_CLUSTER_PCACHE
= 2;
93 const PURGE_GLOBAL_PCACHE
= 4;
97 * Constructor and clear the article
98 * @param Title $title Reference to a Title object.
100 public function __construct( Title
$title ) {
101 $this->mTitle
= $title;
105 * Makes sure that the mTitle object is cloned
106 * to the newly cloned WikiPage.
108 public function __clone() {
109 $this->mTitle
= clone $this->mTitle
;
113 * Create a WikiPage object of the appropriate class for the given title.
115 * @param Title $title
117 * @throws MWException
118 * @return WikiPage|WikiCategoryPage|WikiFilePage
120 public static function factory( Title
$title ) {
121 $ns = $title->getNamespace();
123 if ( $ns == NS_MEDIA
) {
124 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
125 } elseif ( $ns < 0 ) {
126 throw new MWException( "Invalid or virtual namespace $ns given." );
130 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
136 $page = new WikiFilePage( $title );
139 $page = new WikiCategoryPage( $title );
142 $page = new WikiPage( $title );
149 * Constructor from a page id
151 * @param int $id Article ID to load
152 * @param string|int $from One of the following values:
153 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
154 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
156 * @return WikiPage|null
158 public static function newFromID( $id, $from = 'fromdb' ) {
159 // page ids are never 0 or negative, see T63166
164 $from = self
::convertSelectType( $from );
165 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
166 $row = $db->selectRow(
167 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
171 return self
::newFromRow( $row, $from );
175 * Constructor from a database row
178 * @param object $row Database row containing at least fields returned by selectFields().
179 * @param string|int $from Source of $data:
180 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
181 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
182 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
185 public static function newFromRow( $row, $from = 'fromdb' ) {
186 $page = self
::factory( Title
::newFromRow( $row ) );
187 $page->loadFromRow( $row, $from );
192 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
194 * @param object|string|int $type
197 private static function convertSelectType( $type ) {
200 return self
::READ_NORMAL
;
202 return self
::READ_LATEST
;
204 return self
::READ_LOCKING
;
206 // It may already be an integer or whatever else
212 * @todo Move this UI stuff somewhere else
214 * @see ContentHandler::getActionOverrides
216 public function getActionOverrides() {
217 return $this->getContentHandler()->getActionOverrides();
221 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
223 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
225 * @return ContentHandler
229 public function getContentHandler() {
230 return ContentHandler
::getForModelID( $this->getContentModel() );
234 * Get the title object of the article
235 * @return Title Title object of this page
237 public function getTitle() {
238 return $this->mTitle
;
245 public function clear() {
246 $this->mDataLoaded
= false;
247 $this->mDataLoadedFrom
= self
::READ_NONE
;
249 $this->clearCacheFields();
253 * Clear the object cache fields
256 protected function clearCacheFields() {
258 $this->mRedirectTarget
= null; // Title object if set
259 $this->mLastRevision
= null; // Latest revision
260 $this->mTouched
= '19700101000000';
261 $this->mLinksUpdated
= '19700101000000';
262 $this->mTimestamp
= '';
263 $this->mIsRedirect
= false;
264 $this->mLatest
= false;
265 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
266 // the requested rev ID and content against the cached one for equality. For most
267 // content types, the output should not change during the lifetime of this cache.
268 // Clearing it can cause extra parses on edit for no reason.
272 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
276 public function clearPreparedEdit() {
277 $this->mPreparedEdit
= false;
281 * Return the list of revision fields that should be selected to create
286 public static function selectFields() {
287 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
298 'page_links_updated',
303 if ( $wgContentHandlerUseDB ) {
304 $fields[] = 'page_content_model';
307 if ( $wgPageLanguageUseDB ) {
308 $fields[] = 'page_lang';
315 * Fetch a page record with the given conditions
316 * @param IDatabase $dbr
317 * @param array $conditions
318 * @param array $options
319 * @return object|bool Database result resource, or false on failure
321 protected function pageData( $dbr, $conditions, $options = [] ) {
322 $fields = self
::selectFields();
324 // Avoid PHP 7.1 warning of passing $this by reference
327 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
329 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
331 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
337 * Fetch a page record matching the Title object's namespace and title
338 * using a sanitized title string
340 * @param IDatabase $dbr
341 * @param Title $title
342 * @param array $options
343 * @return object|bool Database result resource, or false on failure
345 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
346 return $this->pageData( $dbr, [
347 'page_namespace' => $title->getNamespace(),
348 'page_title' => $title->getDBkey() ], $options );
352 * Fetch a page record matching the requested ID
354 * @param IDatabase $dbr
356 * @param array $options
357 * @return object|bool Database result resource, or false on failure
359 public function pageDataFromId( $dbr, $id, $options = [] ) {
360 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
364 * Load the object from a given source by title
366 * @param object|string|int $from One of the following:
367 * - A DB query result object.
368 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
369 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
370 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
371 * using SELECT FOR UPDATE.
375 public function loadPageData( $from = 'fromdb' ) {
376 $from = self
::convertSelectType( $from );
377 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
378 // We already have the data from the correct location, no need to load it twice.
382 if ( is_int( $from ) ) {
383 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
384 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
387 && $index == DB_REPLICA
388 && wfGetLB()->getServerCount() > 1
389 && wfGetLB()->hasOrMadeRecentMasterChanges()
391 $from = self
::READ_LATEST
;
392 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
393 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
396 // No idea from where the caller got this data, assume replica DB.
398 $from = self
::READ_NORMAL
;
401 $this->loadFromRow( $data, $from );
405 * Load the object from a database row
408 * @param object|bool $data DB row containing fields returned by selectFields() or false
409 * @param string|int $from One of the following:
410 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
411 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
412 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
413 * the master DB using SELECT FOR UPDATE
415 public function loadFromRow( $data, $from ) {
416 $lc = LinkCache
::singleton();
417 $lc->clearLink( $this->mTitle
);
420 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
422 $this->mTitle
->loadFromRow( $data );
424 // Old-fashioned restrictions
425 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
427 $this->mId
= intval( $data->page_id
);
428 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
429 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
430 $this->mIsRedirect
= intval( $data->page_is_redirect
);
431 $this->mLatest
= intval( $data->page_latest
);
432 // T39225: $latest may no longer match the cached latest Revision object.
433 // Double-check the ID of any cached latest Revision object for consistency.
434 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
435 $this->mLastRevision
= null;
436 $this->mTimestamp
= '';
439 $lc->addBadLinkObj( $this->mTitle
);
441 $this->mTitle
->loadFromRow( false );
443 $this->clearCacheFields();
448 $this->mDataLoaded
= true;
449 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
453 * @return int Page ID
455 public function getId() {
456 if ( !$this->mDataLoaded
) {
457 $this->loadPageData();
463 * @return bool Whether or not the page exists in the database
465 public function exists() {
466 if ( !$this->mDataLoaded
) {
467 $this->loadPageData();
469 return $this->mId
> 0;
473 * Check if this page is something we're going to be showing
474 * some sort of sensible content for. If we return false, page
475 * views (plain action=view) will return an HTTP 404 response,
476 * so spiders and robots can know they're following a bad link.
480 public function hasViewableContent() {
481 return $this->mTitle
->isKnown();
485 * Tests if the article content represents a redirect
489 public function isRedirect() {
490 if ( !$this->mDataLoaded
) {
491 $this->loadPageData();
494 return (bool)$this->mIsRedirect
;
498 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
500 * Will use the revisions actual content model if the page exists,
501 * and the page's default if the page doesn't exist yet.
507 public function getContentModel() {
508 if ( $this->exists() ) {
509 $cache = ObjectCache
::getMainWANInstance();
511 return $cache->getWithSetCallback(
512 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
515 $rev = $this->getRevision();
517 // Look at the revision's actual content model
518 return $rev->getContentModel();
520 $title = $this->mTitle
->getPrefixedDBkey();
521 wfWarn( "Page $title exists but has no (visible) revisions!" );
522 return $this->mTitle
->getContentModel();
528 // use the default model for this page
529 return $this->mTitle
->getContentModel();
533 * Loads page_touched and returns a value indicating if it should be used
534 * @return bool True if this page exists and is not a redirect
536 public function checkTouched() {
537 if ( !$this->mDataLoaded
) {
538 $this->loadPageData();
540 return ( $this->mId
&& !$this->mIsRedirect
);
544 * Get the page_touched field
545 * @return string Containing GMT timestamp
547 public function getTouched() {
548 if ( !$this->mDataLoaded
) {
549 $this->loadPageData();
551 return $this->mTouched
;
555 * Get the page_links_updated field
556 * @return string|null Containing GMT timestamp
558 public function getLinksTimestamp() {
559 if ( !$this->mDataLoaded
) {
560 $this->loadPageData();
562 return $this->mLinksUpdated
;
566 * Get the page_latest field
567 * @return int The rev_id of current revision
569 public function getLatest() {
570 if ( !$this->mDataLoaded
) {
571 $this->loadPageData();
573 return (int)$this->mLatest
;
577 * Get the Revision object of the oldest revision
578 * @return Revision|null
580 public function getOldestRevision() {
581 // Try using the replica DB first, then try the master
582 $rev = $this->mTitle
->getFirstRevision();
584 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
590 * Loads everything except the text
591 * This isn't necessary for all uses, so it's only done if needed.
593 protected function loadLastEdit() {
594 if ( $this->mLastRevision
!== null ) {
595 return; // already loaded
598 $latest = $this->getLatest();
600 return; // page doesn't exist or is missing page_latest info
603 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
604 // T39225: if session S1 loads the page row FOR UPDATE, the result always
605 // includes the latest changes committed. This is true even within REPEATABLE-READ
606 // transactions, where S1 normally only sees changes committed before the first S1
607 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
608 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
609 // happened after the first S1 SELECT.
610 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
611 $flags = Revision
::READ_LOCKING
;
612 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
613 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
614 // Bug T93976: if page_latest was loaded from the master, fetch the
615 // revision from there as well, as it may not exist yet on a replica DB.
616 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
617 $flags = Revision
::READ_LATEST
;
618 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
620 $dbr = wfGetDB( DB_REPLICA
);
621 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
624 if ( $revision ) { // sanity
625 $this->setLastEdit( $revision );
630 * Set the latest revision
631 * @param Revision $revision
633 protected function setLastEdit( Revision
$revision ) {
634 $this->mLastRevision
= $revision;
635 $this->mTimestamp
= $revision->getTimestamp();
639 * Get the latest revision
640 * @return Revision|null
642 public function getRevision() {
643 $this->loadLastEdit();
644 if ( $this->mLastRevision
) {
645 return $this->mLastRevision
;
651 * Get the content of the current revision. No side-effects...
653 * @param int $audience One of:
654 * Revision::FOR_PUBLIC to be displayed to all users
655 * Revision::FOR_THIS_USER to be displayed to $wgUser
656 * Revision::RAW get the text regardless of permissions
657 * @param User $user User object to check for, only if FOR_THIS_USER is passed
658 * to the $audience parameter
659 * @return Content|null The content of the current revision
663 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
664 $this->loadLastEdit();
665 if ( $this->mLastRevision
) {
666 return $this->mLastRevision
->getContent( $audience, $user );
672 * @return string MW timestamp of last article revision
674 public function getTimestamp() {
675 // Check if the field has been filled by WikiPage::setTimestamp()
676 if ( !$this->mTimestamp
) {
677 $this->loadLastEdit();
680 return wfTimestamp( TS_MW
, $this->mTimestamp
);
684 * Set the page timestamp (use only to avoid DB queries)
685 * @param string $ts MW timestamp of last article revision
688 public function setTimestamp( $ts ) {
689 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
693 * @param int $audience One of:
694 * Revision::FOR_PUBLIC to be displayed to all users
695 * Revision::FOR_THIS_USER to be displayed to the given user
696 * Revision::RAW get the text regardless of permissions
697 * @param User $user User object to check for, only if FOR_THIS_USER is passed
698 * to the $audience parameter
699 * @return int User ID for the user that made the last article revision
701 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
702 $this->loadLastEdit();
703 if ( $this->mLastRevision
) {
704 return $this->mLastRevision
->getUser( $audience, $user );
711 * Get the User object of the user who created the page
712 * @param int $audience One of:
713 * Revision::FOR_PUBLIC to be displayed to all users
714 * Revision::FOR_THIS_USER to be displayed to the given user
715 * Revision::RAW get the text regardless of permissions
716 * @param User $user User object to check for, only if FOR_THIS_USER is passed
717 * to the $audience parameter
720 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
721 $revision = $this->getOldestRevision();
723 $userName = $revision->getUserText( $audience, $user );
724 return User
::newFromName( $userName, false );
731 * @param int $audience One of:
732 * Revision::FOR_PUBLIC to be displayed to all users
733 * Revision::FOR_THIS_USER to be displayed to the given user
734 * Revision::RAW get the text regardless of permissions
735 * @param User $user User object to check for, only if FOR_THIS_USER is passed
736 * to the $audience parameter
737 * @return string Username of the user that made the last article revision
739 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
740 $this->loadLastEdit();
741 if ( $this->mLastRevision
) {
742 return $this->mLastRevision
->getUserText( $audience, $user );
749 * @param int $audience One of:
750 * Revision::FOR_PUBLIC to be displayed to all users
751 * Revision::FOR_THIS_USER to be displayed to the given user
752 * Revision::RAW get the text regardless of permissions
753 * @param User $user User object to check for, only if FOR_THIS_USER is passed
754 * to the $audience parameter
755 * @return string Comment stored for the last article revision
757 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
758 $this->loadLastEdit();
759 if ( $this->mLastRevision
) {
760 return $this->mLastRevision
->getComment( $audience, $user );
767 * Returns true if last revision was marked as "minor edit"
769 * @return bool Minor edit indicator for the last article revision.
771 public function getMinorEdit() {
772 $this->loadLastEdit();
773 if ( $this->mLastRevision
) {
774 return $this->mLastRevision
->isMinor();
781 * Determine whether a page would be suitable for being counted as an
782 * article in the site_stats table based on the title & its content
784 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
785 * if false, the current database state will be used
788 public function isCountable( $editInfo = false ) {
789 global $wgArticleCountMethod;
791 if ( !$this->mTitle
->isContentPage() ) {
796 $content = $editInfo->pstContent
;
798 $content = $this->getContent();
801 if ( !$content ||
$content->isRedirect() ) {
807 if ( $wgArticleCountMethod === 'link' ) {
808 // nasty special case to avoid re-parsing to detect links
811 // ParserOutput::getLinks() is a 2D array of page links, so
812 // to be really correct we would need to recurse in the array
813 // but the main array should only have items in it if there are
815 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
817 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
818 [ 'pl_from' => $this->getId() ], __METHOD__
);
822 return $content->isCountable( $hasLinks );
826 * If this page is a redirect, get its target
828 * The target will be fetched from the redirect table if possible.
829 * If this page doesn't have an entry there, call insertRedirect()
830 * @return Title|null Title object, or null if this page is not a redirect
832 public function getRedirectTarget() {
833 if ( !$this->mTitle
->isRedirect() ) {
837 if ( $this->mRedirectTarget
!== null ) {
838 return $this->mRedirectTarget
;
841 // Query the redirect table
842 $dbr = wfGetDB( DB_REPLICA
);
843 $row = $dbr->selectRow( 'redirect',
844 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
845 [ 'rd_from' => $this->getId() ],
849 // rd_fragment and rd_interwiki were added later, populate them if empty
850 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
851 $this->mRedirectTarget
= Title
::makeTitle(
852 $row->rd_namespace
, $row->rd_title
,
853 $row->rd_fragment
, $row->rd_interwiki
855 return $this->mRedirectTarget
;
858 // This page doesn't have an entry in the redirect table
859 $this->mRedirectTarget
= $this->insertRedirect();
860 return $this->mRedirectTarget
;
864 * Insert an entry for this page into the redirect table if the content is a redirect
866 * The database update will be deferred via DeferredUpdates
868 * Don't call this function directly unless you know what you're doing.
869 * @return Title|null Title object or null if not a redirect
871 public function insertRedirect() {
872 $content = $this->getContent();
873 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
878 // Update the DB post-send if the page has not cached since now
880 $latest = $this->getLatest();
881 DeferredUpdates
::addCallableUpdate(
882 function () use ( $that, $retval, $latest ) {
883 $that->insertRedirectEntry( $retval, $latest );
885 DeferredUpdates
::POSTSEND
,
893 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
894 * @param Title $rt Redirect target
895 * @param int|null $oldLatest Prior page_latest for check and set
897 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
898 $dbw = wfGetDB( DB_MASTER
);
899 $dbw->startAtomic( __METHOD__
);
901 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
905 'rd_from' => $this->getId(),
906 'rd_namespace' => $rt->getNamespace(),
907 'rd_title' => $rt->getDBkey(),
908 'rd_fragment' => $rt->getFragment(),
909 'rd_interwiki' => $rt->getInterwiki(),
913 'rd_namespace' => $rt->getNamespace(),
914 'rd_title' => $rt->getDBkey(),
915 'rd_fragment' => $rt->getFragment(),
916 'rd_interwiki' => $rt->getInterwiki(),
922 $dbw->endAtomic( __METHOD__
);
926 * Get the Title object or URL this page redirects to
928 * @return bool|Title|string False, Title of in-wiki target, or string with URL
930 public function followRedirect() {
931 return $this->getRedirectURL( $this->getRedirectTarget() );
935 * Get the Title object or URL to use for a redirect. We use Title
936 * objects for same-wiki, non-special redirects and URLs for everything
938 * @param Title $rt Redirect target
939 * @return bool|Title|string False, Title object of local target, or string with URL
941 public function getRedirectURL( $rt ) {
946 if ( $rt->isExternal() ) {
947 if ( $rt->isLocal() ) {
948 // Offsite wikis need an HTTP redirect.
949 // This can be hard to reverse and may produce loops,
950 // so they may be disabled in the site configuration.
951 $source = $this->mTitle
->getFullURL( 'redirect=no' );
952 return $rt->getFullURL( [ 'rdfrom' => $source ] );
954 // External pages without "local" bit set are not valid
960 if ( $rt->isSpecialPage() ) {
961 // Gotta handle redirects to special pages differently:
962 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
963 // Some pages are not valid targets.
964 if ( $rt->isValidRedirectTarget() ) {
965 return $rt->getFullURL();
975 * Get a list of users who have edited this article, not including the user who made
976 * the most recent revision, which you can get from $article->getUser() if you want it
977 * @return UserArrayFromResult
979 public function getContributors() {
980 // @todo FIXME: This is expensive; cache this info somewhere.
982 $dbr = wfGetDB( DB_REPLICA
);
984 if ( $dbr->implicitGroupby() ) {
985 $realNameField = 'user_real_name';
987 $realNameField = 'MIN(user_real_name) AS user_real_name';
990 $tables = [ 'revision', 'user' ];
993 'user_id' => 'rev_user',
994 'user_name' => 'rev_user_text',
996 'timestamp' => 'MAX(rev_timestamp)',
999 $conds = [ 'rev_page' => $this->getId() ];
1001 // The user who made the top revision gets credited as "this page was last edited by
1002 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1003 $user = $this->getUser();
1005 $conds[] = "rev_user != $user";
1007 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1011 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1014 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1018 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1019 'ORDER BY' => 'timestamp DESC',
1022 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1023 return new UserArrayFromResult( $res );
1027 * Should the parser cache be used?
1029 * @param ParserOptions $parserOptions ParserOptions to check
1033 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1034 return $parserOptions->getStubThreshold() == 0
1036 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1037 && $this->getContentHandler()->isParserCacheSupported();
1041 * Get a ParserOutput for the given ParserOptions and revision ID.
1043 * The parser cache will be used if possible. Cache misses that result
1044 * in parser runs are debounced with PoolCounter.
1047 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1048 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1049 * get the current revision (default value)
1050 * @param bool $forceParse Force reindexing, regardless of cache settings
1051 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1053 public function getParserOutput(
1054 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1057 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1059 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1060 throw new InvalidArgumentException(
1061 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1065 wfDebug( __METHOD__
.
1066 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1067 if ( $parserOptions->getStubThreshold() ) {
1068 wfIncrStats( 'pcache.miss.stub' );
1071 if ( $useParserCache ) {
1072 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1073 if ( $parserOutput !== false ) {
1074 return $parserOutput;
1078 if ( $oldid === null ||
$oldid === 0 ) {
1079 $oldid = $this->getLatest();
1082 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1085 return $pool->getParserOutput();
1089 * Do standard deferred updates after page view (existing or missing page)
1090 * @param User $user The relevant user
1091 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1093 public function doViewUpdates( User
$user, $oldid = 0 ) {
1094 if ( wfReadOnly() ) {
1098 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1099 // Update newtalk / watchlist notification status
1101 $user->clearNotification( $this->mTitle
, $oldid );
1102 } catch ( DBError
$e ) {
1103 // Avoid outage if the master is not reachable
1104 MWExceptionHandler
::logException( $e );
1109 * Perform the actions of a page purging
1111 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1112 * controlled how much purging was done.
1114 public function doPurge() {
1115 // Avoid PHP 7.1 warning of passing $this by reference
1118 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1122 $this->mTitle
->invalidateCache();
1125 HTMLFileCache
::clearFileCache( $this->getTitle() );
1126 // Send purge after above page_touched update was committed
1127 DeferredUpdates
::addUpdate(
1128 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1129 DeferredUpdates
::PRESEND
1132 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1133 $messageCache = MessageCache
::singleton();
1134 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1141 * Get the last time a user explicitly purged the page via action=purge
1143 * @return string|bool TS_MW timestamp or false
1145 * @deprecated since 1.29. It will always return false.
1147 public function getLastPurgeTimestamp() {
1148 wfDeprecated( __METHOD__
, '1.29' );
1153 * Insert a new empty page record for this article.
1154 * This *must* be followed up by creating a revision
1155 * and running $this->updateRevisionOn( ... );
1156 * or else the record will be left in a funky state.
1157 * Best if all done inside a transaction.
1159 * @param IDatabase $dbw
1160 * @param int|null $pageId Custom page ID that will be used for the insert statement
1162 * @return bool|int The newly created page_id key; false if the row was not
1163 * inserted, e.g. because the title already existed or because the specified
1164 * page ID is already in use.
1166 public function insertOn( $dbw, $pageId = null ) {
1167 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1171 'page_id' => $pageIdForInsert,
1172 'page_namespace' => $this->mTitle
->getNamespace(),
1173 'page_title' => $this->mTitle
->getDBkey(),
1174 'page_restrictions' => '',
1175 'page_is_redirect' => 0, // Will set this shortly...
1177 'page_random' => wfRandom(),
1178 'page_touched' => $dbw->timestamp(),
1179 'page_latest' => 0, // Fill this in shortly...
1180 'page_len' => 0, // Fill this in shortly...
1186 if ( $dbw->affectedRows() > 0 ) {
1187 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1188 $this->mId
= $newid;
1189 $this->mTitle
->resetArticleID( $newid );
1193 return false; // nothing changed
1198 * Update the page record to point to a newly saved revision.
1200 * @param IDatabase $dbw
1201 * @param Revision $revision For ID number, and text used to set
1202 * length and redirect status fields
1203 * @param int $lastRevision If given, will not overwrite the page field
1204 * when different from the currently set value.
1205 * Giving 0 indicates the new page flag should be set on.
1206 * @param bool $lastRevIsRedirect If given, will optimize adding and
1207 * removing rows in redirect table.
1208 * @return bool Success; false if the page row was missing or page_latest changed
1210 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1211 $lastRevIsRedirect = null
1213 global $wgContentHandlerUseDB;
1215 // Assertion to try to catch T92046
1216 if ( (int)$revision->getId() === 0 ) {
1217 throw new InvalidArgumentException(
1218 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1222 $content = $revision->getContent();
1223 $len = $content ?
$content->getSize() : 0;
1224 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1226 $conditions = [ 'page_id' => $this->getId() ];
1228 if ( !is_null( $lastRevision ) ) {
1229 // An extra check against threads stepping on each other
1230 $conditions['page_latest'] = $lastRevision;
1234 'page_latest' => $revision->getId(),
1235 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1236 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1237 'page_is_redirect' => $rt !== null ?
1 : 0,
1241 if ( $wgContentHandlerUseDB ) {
1242 $row['page_content_model'] = $revision->getContentModel();
1245 $dbw->update( 'page',
1250 $result = $dbw->affectedRows() > 0;
1252 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1253 $this->setLastEdit( $revision );
1254 $this->mLatest
= $revision->getId();
1255 $this->mIsRedirect
= (bool)$rt;
1256 // Update the LinkCache.
1257 LinkCache
::singleton()->addGoodLinkObj(
1263 $revision->getContentModel()
1271 * Add row to the redirect table if this is a redirect, remove otherwise.
1273 * @param IDatabase $dbw
1274 * @param Title $redirectTitle Title object pointing to the redirect target,
1275 * or NULL if this is not a redirect
1276 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1277 * removing rows in redirect table.
1278 * @return bool True on success, false on failure
1281 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1282 // Always update redirects (target link might have changed)
1283 // Update/Insert if we don't know if the last revision was a redirect or not
1284 // Delete if changing from redirect to non-redirect
1285 $isRedirect = !is_null( $redirectTitle );
1287 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1291 if ( $isRedirect ) {
1292 $this->insertRedirectEntry( $redirectTitle );
1294 // This is not a redirect, remove row from redirect table
1295 $where = [ 'rd_from' => $this->getId() ];
1296 $dbw->delete( 'redirect', $where, __METHOD__
);
1299 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1300 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1303 return ( $dbw->affectedRows() != 0 );
1307 * If the given revision is newer than the currently set page_latest,
1308 * update the page record. Otherwise, do nothing.
1310 * @deprecated since 1.24, use updateRevisionOn instead
1312 * @param IDatabase $dbw
1313 * @param Revision $revision
1316 public function updateIfNewerOn( $dbw, $revision ) {
1317 $row = $dbw->selectRow(
1318 [ 'revision', 'page' ],
1319 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1321 'page_id' => $this->getId(),
1322 'page_latest=rev_id' ],
1326 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1329 $prev = $row->rev_id
;
1330 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1332 // No or missing previous revision; mark the page as new
1334 $lastRevIsRedirect = null;
1337 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1343 * Get the content that needs to be saved in order to undo all revisions
1344 * between $undo and $undoafter. Revisions must belong to the same page,
1345 * must exist and must not be deleted
1346 * @param Revision $undo
1347 * @param Revision $undoafter Must be an earlier revision than $undo
1348 * @return Content|bool Content on success, false on failure
1350 * Before we had the Content object, this was done in getUndoText
1352 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1353 $handler = $undo->getContentHandler();
1354 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1358 * Returns true if this page's content model supports sections.
1362 * @todo The skin should check this and not offer section functionality if
1363 * sections are not supported.
1364 * @todo The EditPage should check this and not offer section functionality
1365 * if sections are not supported.
1367 public function supportsSections() {
1368 return $this->getContentHandler()->supportsSections();
1372 * @param string|int|null|bool $sectionId Section identifier as a number or string
1373 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1374 * or 'new' for a new section.
1375 * @param Content $sectionContent New content of the section.
1376 * @param string $sectionTitle New section's subject, only if $section is "new".
1377 * @param string $edittime Revision timestamp or null to use the current revision.
1379 * @throws MWException
1380 * @return Content|null New complete article content, or null if error.
1383 * @deprecated since 1.24, use replaceSectionAtRev instead
1385 public function replaceSectionContent(
1386 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1389 if ( $edittime && $sectionId !== 'new' ) {
1390 $dbr = wfGetDB( DB_REPLICA
);
1391 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1392 // Try the master if this thread may have just added it.
1393 // This could be abstracted into a Revision method, but we don't want
1394 // to encourage loading of revisions by timestamp.
1396 && wfGetLB()->getServerCount() > 1
1397 && wfGetLB()->hasOrMadeRecentMasterChanges()
1399 $dbw = wfGetDB( DB_MASTER
);
1400 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1403 $baseRevId = $rev->getId();
1407 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1411 * @param string|int|null|bool $sectionId Section identifier as a number or string
1412 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1413 * or 'new' for a new section.
1414 * @param Content $sectionContent New content of the section.
1415 * @param string $sectionTitle New section's subject, only if $section is "new".
1416 * @param int|null $baseRevId
1418 * @throws MWException
1419 * @return Content|null New complete article content, or null if error.
1423 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1424 $sectionTitle = '', $baseRevId = null
1426 if ( strval( $sectionId ) === '' ) {
1427 // Whole-page edit; let the whole text through
1428 $newContent = $sectionContent;
1430 if ( !$this->supportsSections() ) {
1431 throw new MWException( "sections not supported for content model " .
1432 $this->getContentHandler()->getModelID() );
1435 // T32711: always use current version when adding a new section
1436 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1437 $oldContent = $this->getContent();
1439 $rev = Revision
::newFromId( $baseRevId );
1441 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1442 $this->getId() . "; section: $sectionId)\n" );
1446 $oldContent = $rev->getContent();
1449 if ( !$oldContent ) {
1450 wfDebug( __METHOD__
. ": no page text\n" );
1454 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1461 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1463 * @return int Updated $flags
1465 public function checkFlags( $flags ) {
1466 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1467 if ( $this->exists() ) {
1468 $flags |
= EDIT_UPDATE
;
1478 * Change an existing article or create a new article. Updates RC and all necessary caches,
1479 * optionally via the deferred update array.
1481 * @param Content $content New content
1482 * @param string $summary Edit summary
1483 * @param int $flags Bitfield:
1485 * Article is known or assumed to be non-existent, create a new one
1487 * Article is known or assumed to be pre-existing, update it
1489 * Mark this edit minor, if the user is allowed to do so
1491 * Do not log the change in recentchanges
1493 * Mark the edit a "bot" edit regardless of user rights
1495 * Fill in blank summaries with generated text where possible
1497 * Signal that the page retrieve/save cycle happened entirely in this request.
1499 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1500 * article will be detected. If EDIT_UPDATE is specified and the article
1501 * doesn't exist, the function will return an edit-gone-missing error. If
1502 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1503 * error will be returned. These two conditions are also possible with
1504 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1506 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1507 * This is not the parent revision ID, rather the revision ID for older
1508 * content used as the source for a rollback, for example.
1509 * @param User $user The user doing the edit
1510 * @param string $serialFormat Format for storing the content in the
1512 * @param array|null $tags Change tags to apply to this edit
1513 * Callers are responsible for permission checks
1514 * (with ChangeTags::canAddTagsAccompanyingChange)
1515 * @param Int $undidRevId Id of revision that was undone or 0
1517 * @throws MWException
1518 * @return Status Possible errors:
1519 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1520 * set the fatal flag of $status.
1521 * edit-gone-missing: In update mode, but the article didn't exist.
1522 * edit-conflict: In update mode, the article changed unexpectedly.
1523 * edit-no-change: Warning that the text was the same as before.
1524 * edit-already-exists: In creation mode, but the article already exists.
1526 * Extensions may define additional errors.
1528 * $return->value will contain an associative array with members as follows:
1529 * new: Boolean indicating if the function attempted to create a new article.
1530 * revision: The revision object for the inserted revision, or null.
1533 * @throws MWException
1535 public function doEditContent(
1536 Content
$content, $summary, $flags = 0, $baseRevId = false,
1537 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1539 global $wgUser, $wgUseAutomaticEditSummaries;
1541 // Old default parameter for $tags was null
1542 if ( $tags === null ) {
1546 // Low-level sanity check
1547 if ( $this->mTitle
->getText() === '' ) {
1548 throw new MWException( 'Something is trying to edit an article with an empty title' );
1550 // Make sure the given content type is allowed for this page
1551 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1552 return Status
::newFatal( 'content-not-allowed-here',
1553 ContentHandler
::getLocalizedName( $content->getModel() ),
1554 $this->mTitle
->getPrefixedText()
1558 // Load the data from the master database if needed.
1559 // The caller may already loaded it from the master or even loaded it using
1560 // SELECT FOR UPDATE, so do not override that using clear().
1561 $this->loadPageData( 'fromdbmaster' );
1563 $user = $user ?
: $wgUser;
1564 $flags = $this->checkFlags( $flags );
1566 // Avoid PHP 7.1 warning of passing $this by reference
1569 // Trigger pre-save hook (using provided edit summary)
1570 $hookStatus = Status
::newGood( [] );
1571 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1572 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1573 // Check if the hook rejected the attempted save
1574 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1575 if ( $hookStatus->isOK() ) {
1576 // Hook returned false but didn't call fatal(); use generic message
1577 $hookStatus->fatal( 'edit-hook-aborted' );
1583 $old_revision = $this->getRevision(); // current revision
1584 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1586 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1587 $tags[] = 'mw-contentmodelchange';
1590 // Provide autosummaries if one is not provided and autosummaries are enabled
1591 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1592 $handler = $content->getContentHandler();
1593 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1596 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1597 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1603 // Get the pre-save transform content and final parser output
1604 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1605 $pstContent = $editInfo->pstContent
; // Content object
1607 'bot' => ( $flags & EDIT_FORCE_BOT
),
1608 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1609 'serialized' => $editInfo->pst
,
1610 'serialFormat' => $serialFormat,
1611 'baseRevId' => $baseRevId,
1612 'oldRevision' => $old_revision,
1613 'oldContent' => $old_content,
1614 'oldId' => $this->getLatest(),
1615 'oldIsRedirect' => $this->isRedirect(),
1616 'oldCountable' => $this->isCountable(),
1617 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1618 'undidRevId' => $undidRevId
1621 // Actually create the revision and create/update the page
1622 if ( $flags & EDIT_UPDATE
) {
1623 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1625 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1628 // Promote user to any groups they meet the criteria for
1629 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1630 $user->addAutopromoteOnceGroups( 'onEdit' );
1631 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1638 * @param Content $content Pre-save transform content
1639 * @param integer $flags
1641 * @param string $summary
1642 * @param array $meta
1644 * @throws DBUnexpectedError
1646 * @throws FatalError
1647 * @throws MWException
1649 private function doModify(
1650 Content
$content, $flags, User
$user, $summary, array $meta
1652 global $wgUseRCPatrol;
1654 // Update article, but only if changed.
1655 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1657 // Convenience variables
1658 $now = wfTimestampNow();
1659 $oldid = $meta['oldId'];
1660 /** @var $oldContent Content|null */
1661 $oldContent = $meta['oldContent'];
1662 $newsize = $content->getSize();
1665 // Article gone missing
1666 $status->fatal( 'edit-gone-missing' );
1669 } elseif ( !$oldContent ) {
1670 // Sanity check for T39225
1671 throw new MWException( "Could not find text for current revision {$oldid}." );
1674 // @TODO: pass content object?!
1675 $revision = new Revision( [
1676 'page' => $this->getId(),
1677 'title' => $this->mTitle
, // for determining the default content model
1678 'comment' => $summary,
1679 'minor_edit' => $meta['minor'],
1680 'text' => $meta['serialized'],
1682 'parent_id' => $oldid,
1683 'user' => $user->getId(),
1684 'user_text' => $user->getName(),
1685 'timestamp' => $now,
1686 'content_model' => $content->getModel(),
1687 'content_format' => $meta['serialFormat'],
1690 $changed = !$content->equals( $oldContent );
1692 $dbw = wfGetDB( DB_MASTER
);
1695 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1696 $status->merge( $prepStatus );
1697 if ( !$status->isOK() ) {
1701 $dbw->startAtomic( __METHOD__
);
1702 // Get the latest page_latest value while locking it.
1703 // Do a CAS style check to see if it's the same as when this method
1704 // started. If it changed then bail out before touching the DB.
1705 $latestNow = $this->lockAndGetLatest();
1706 if ( $latestNow != $oldid ) {
1707 $dbw->endAtomic( __METHOD__
);
1708 // Page updated or deleted in the mean time
1709 $status->fatal( 'edit-conflict' );
1714 // At this point we are now comitted to returning an OK
1715 // status unless some DB query error or other exception comes up.
1716 // This way callers don't have to call rollback() if $status is bad
1717 // unless they actually try to catch exceptions (which is rare).
1719 // Save the revision text
1720 $revisionId = $revision->insertOn( $dbw );
1721 // Update page_latest and friends to reflect the new revision
1722 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1723 throw new MWException( "Failed to update page row to use new revision." );
1726 Hooks
::run( 'NewRevisionFromEditComplete',
1727 [ $this, $revision, $meta['baseRevId'], $user ] );
1729 // Update recentchanges
1730 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1731 // Mark as patrolled if the user can do so
1732 $patrolled = $wgUseRCPatrol && !count(
1733 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1734 // Add RC row to the DB
1735 RecentChange
::notifyEdit(
1738 $revision->isMinor(),
1742 $this->getTimestamp(),
1745 $oldContent ?
$oldContent->getSize() : 0,
1753 $user->incEditCount();
1755 $dbw->endAtomic( __METHOD__
);
1756 $this->mTimestamp
= $now;
1758 // T34948: revision ID must be set to page {{REVISIONID}} and
1759 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1760 $revision->setId( $this->getLatest() );
1761 $revision->setUserIdAndName(
1762 $this->getUser( Revision
::RAW
),
1763 $this->getUserText( Revision
::RAW
)
1768 // Return the new revision to the caller
1769 $status->value
['revision'] = $revision;
1771 $status->warning( 'edit-no-change' );
1772 // Update page_touched as updateRevisionOn() was not called.
1773 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1774 $this->mTitle
->invalidateCache( $now );
1777 // Do secondary updates once the main changes have been committed...
1778 DeferredUpdates
::addUpdate(
1779 new AtomicSectionUpdate(
1783 $revision, &$user, $content, $summary, &$flags,
1784 $changed, $meta, &$status
1786 // Update links tables, site stats, etc.
1787 $this->doEditUpdates(
1791 'changed' => $changed,
1792 'oldcountable' => $meta['oldCountable'],
1793 'oldrevision' => $meta['oldRevision']
1796 // Avoid PHP 7.1 warning of passing $this by reference
1798 // Trigger post-save hook
1799 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1800 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1801 $meta['undidRevId'] ];
1802 Hooks
::run( 'PageContentSaveComplete', $params );
1805 DeferredUpdates
::PRESEND
1812 * @param Content $content Pre-save transform content
1813 * @param integer $flags
1815 * @param string $summary
1816 * @param array $meta
1818 * @throws DBUnexpectedError
1820 * @throws FatalError
1821 * @throws MWException
1823 private function doCreate(
1824 Content
$content, $flags, User
$user, $summary, array $meta
1826 global $wgUseRCPatrol, $wgUseNPPatrol;
1828 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1830 $now = wfTimestampNow();
1831 $newsize = $content->getSize();
1832 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1833 $status->merge( $prepStatus );
1834 if ( !$status->isOK() ) {
1838 $dbw = wfGetDB( DB_MASTER
);
1839 $dbw->startAtomic( __METHOD__
);
1841 // Add the page record unless one already exists for the title
1842 $newid = $this->insertOn( $dbw );
1843 if ( $newid === false ) {
1844 $dbw->endAtomic( __METHOD__
); // nothing inserted
1845 $status->fatal( 'edit-already-exists' );
1847 return $status; // nothing done
1850 // At this point we are now comitted to returning an OK
1851 // status unless some DB query error or other exception comes up.
1852 // This way callers don't have to call rollback() if $status is bad
1853 // unless they actually try to catch exceptions (which is rare).
1855 // @TODO: pass content object?!
1856 $revision = new Revision( [
1858 'title' => $this->mTitle
, // for determining the default content model
1859 'comment' => $summary,
1860 'minor_edit' => $meta['minor'],
1861 'text' => $meta['serialized'],
1863 'user' => $user->getId(),
1864 'user_text' => $user->getName(),
1865 'timestamp' => $now,
1866 'content_model' => $content->getModel(),
1867 'content_format' => $meta['serialFormat'],
1870 // Save the revision text...
1871 $revisionId = $revision->insertOn( $dbw );
1872 // Update the page record with revision data
1873 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1874 throw new MWException( "Failed to update page row to use new revision." );
1877 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1879 // Update recentchanges
1880 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1881 // Mark as patrolled if the user can do so
1882 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1883 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1884 // Add RC row to the DB
1885 RecentChange
::notifyNew(
1888 $revision->isMinor(),
1900 $user->incEditCount();
1902 $dbw->endAtomic( __METHOD__
);
1903 $this->mTimestamp
= $now;
1905 // Return the new revision to the caller
1906 $status->value
['revision'] = $revision;
1908 // Do secondary updates once the main changes have been committed...
1909 DeferredUpdates
::addUpdate(
1910 new AtomicSectionUpdate(
1914 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1916 // Update links, etc.
1917 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1918 // Avoid PHP 7.1 warning of passing $this by reference
1920 // Trigger post-create hook
1921 $params = [ &$wikiPage, &$user, $content, $summary,
1922 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1923 Hooks
::run( 'PageContentInsertComplete', $params );
1924 // Trigger post-save hook
1925 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1926 Hooks
::run( 'PageContentSaveComplete', $params );
1929 DeferredUpdates
::PRESEND
1936 * Get parser options suitable for rendering the primary article wikitext
1938 * @see ContentHandler::makeParserOptions
1940 * @param IContextSource|User|string $context One of the following:
1941 * - IContextSource: Use the User and the Language of the provided
1943 * - User: Use the provided User object and $wgLang for the language,
1944 * so use an IContextSource object if possible.
1945 * - 'canonical': Canonical options (anonymous user with default
1946 * preferences and content language).
1947 * @return ParserOptions
1949 public function makeParserOptions( $context ) {
1950 $options = $this->getContentHandler()->makeParserOptions( $context );
1952 if ( $this->getTitle()->isConversionTable() ) {
1953 // @todo ConversionTable should become a separate content model, so
1954 // we don't need special cases like this one.
1955 $options->disableContentConversion();
1962 * Prepare content which is about to be saved.
1963 * Returns a stdClass with source, pst and output members
1965 * @param Content $content
1966 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1967 * revision ID is also accepted, but this is deprecated.
1968 * @param User|null $user
1969 * @param string|null $serialFormat
1970 * @param bool $useCache Check shared prepared edit cache
1976 public function prepareContentForEdit(
1977 Content
$content, $revision = null, User
$user = null,
1978 $serialFormat = null, $useCache = true
1980 global $wgContLang, $wgUser, $wgAjaxEditStash;
1982 if ( is_object( $revision ) ) {
1983 $revid = $revision->getId();
1986 // This code path is deprecated, and nothing is known to
1987 // use it, so performance here shouldn't be a worry.
1988 if ( $revid !== null ) {
1989 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
1995 $user = is_null( $user ) ?
$wgUser : $user;
1996 // XXX: check $user->getId() here???
1998 // Use a sane default for $serialFormat, see T59026
1999 if ( $serialFormat === null ) {
2000 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2003 if ( $this->mPreparedEdit
2004 && isset( $this->mPreparedEdit
->newContent
)
2005 && $this->mPreparedEdit
->newContent
->equals( $content )
2006 && $this->mPreparedEdit
->revid
== $revid
2007 && $this->mPreparedEdit
->format
== $serialFormat
2008 // XXX: also check $user here?
2011 return $this->mPreparedEdit
;
2014 // The edit may have already been prepared via api.php?action=stashedit
2015 $cachedEdit = $useCache && $wgAjaxEditStash
2016 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2019 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2020 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2023 if ( $cachedEdit ) {
2024 $edit->timestamp
= $cachedEdit->timestamp
;
2026 $edit->timestamp
= wfTimestampNow();
2028 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2029 $edit->revid
= $revid;
2031 if ( $cachedEdit ) {
2032 $edit->pstContent
= $cachedEdit->pstContent
;
2034 $edit->pstContent
= $content
2035 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2039 $edit->format
= $serialFormat;
2040 $edit->popts
= $this->makeParserOptions( 'canonical' );
2041 if ( $cachedEdit ) {
2042 $edit->output
= $cachedEdit->output
;
2045 // We get here if vary-revision is set. This means that this page references
2046 // itself (such as via self-transclusion). In this case, we need to make sure
2047 // that any such self-references refer to the newly-saved revision, and not
2048 // to the previous one, which could otherwise happen due to replica DB lag.
2049 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2050 $edit->popts
->setCurrentRevisionCallback(
2051 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2052 if ( $title->equals( $revision->getTitle() ) ) {
2055 return call_user_func( $oldCallback, $title, $parser );
2060 // Try to avoid a second parse if {{REVISIONID}} is used
2061 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2062 ? DB_MASTER
// use the best possible guess
2063 : DB_REPLICA
; // T154554
2065 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2066 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2074 $edit->output
= $edit->pstContent
2075 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2079 $edit->newContent
= $content;
2080 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2082 // NOTE: B/C for hooks! don't use these fields!
2083 $edit->newText
= $edit->newContent
2084 ? ContentHandler
::getContentText( $edit->newContent
)
2086 $edit->oldText
= $edit->oldContent
2087 ? ContentHandler
::getContentText( $edit->oldContent
)
2089 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2091 if ( $edit->output
) {
2092 $edit->output
->setCacheTime( wfTimestampNow() );
2095 // Process cache the result
2096 $this->mPreparedEdit
= $edit;
2102 * Do standard deferred updates after page edit.
2103 * Update links tables, site stats, search index and message cache.
2104 * Purges pages that include this page if the text was changed here.
2105 * Every 100th edit, prune the recent changes table.
2107 * @param Revision $revision
2108 * @param User $user User object that did the revision
2109 * @param array $options Array of options, following indexes are used:
2110 * - changed: boolean, whether the revision changed the content (default true)
2111 * - created: boolean, whether the revision created the page (default false)
2112 * - moved: boolean, whether the page was moved (default false)
2113 * - restored: boolean, whether the page was undeleted (default false)
2114 * - oldrevision: Revision object for the pre-update revision (default null)
2115 * - oldcountable: boolean, null, or string 'no-change' (default null):
2116 * - boolean: whether the page was counted as an article before that
2117 * revision, only used in changed is true and created is false
2118 * - null: if created is false, don't update the article count; if created
2119 * is true, do update the article count
2120 * - 'no-change': don't update the article count, ever
2122 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2123 global $wgRCWatchCategoryMembership;
2129 'restored' => false,
2130 'oldrevision' => null,
2131 'oldcountable' => null
2133 $content = $revision->getContent();
2135 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2137 // See if the parser output before $revision was inserted is still valid
2139 if ( !$this->mPreparedEdit
) {
2140 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2141 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2142 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2143 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2144 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2146 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2147 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2148 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2150 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2151 $editInfo = $this->mPreparedEdit
;
2155 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2156 // $text is usually already pre-save transformed once. Avoid using the edit stash
2157 // as any prepared content from there or in doEditContent() was already rejected.
2158 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2161 // Save it to the parser cache.
2162 // Make sure the cache time matches page_touched to avoid double parsing.
2163 ParserCache
::singleton()->save(
2164 $editInfo->output
, $this, $editInfo->popts
,
2165 $revision->getTimestamp(), $editInfo->revid
2168 // Update the links tables and other secondary data
2170 $recursive = $options['changed']; // T52785
2171 $updates = $content->getSecondaryDataUpdates(
2172 $this->getTitle(), null, $recursive, $editInfo->output
2174 foreach ( $updates as $update ) {
2175 if ( $update instanceof LinksUpdate
) {
2176 $update->setRevision( $revision );
2177 $update->setTriggeringUser( $user );
2179 DeferredUpdates
::addUpdate( $update );
2181 if ( $wgRCWatchCategoryMembership
2182 && $this->getContentHandler()->supportsCategories() === true
2183 && ( $options['changed'] ||
$options['created'] )
2184 && !$options['restored']
2186 // Note: jobs are pushed after deferred updates, so the job should be able to see
2187 // the recent change entry (also done via deferred updates) and carry over any
2188 // bot/deletion/IP flags, ect.
2189 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2192 'pageId' => $this->getId(),
2193 'revTimestamp' => $revision->getTimestamp()
2199 // Avoid PHP 7.1 warning of passing $this by reference
2202 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2204 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2205 // Flush old entries from the `recentchanges` table
2206 if ( mt_rand( 0, 9 ) == 0 ) {
2207 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2211 if ( !$this->exists() ) {
2215 $id = $this->getId();
2216 $title = $this->mTitle
->getPrefixedDBkey();
2217 $shortTitle = $this->mTitle
->getDBkey();
2219 if ( $options['oldcountable'] === 'no-change' ||
2220 ( !$options['changed'] && !$options['moved'] )
2223 } elseif ( $options['created'] ) {
2224 $good = (int)$this->isCountable( $editInfo );
2225 } elseif ( $options['oldcountable'] !== null ) {
2226 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2230 $edits = $options['changed'] ?
1 : 0;
2231 $total = $options['created'] ?
1 : 0;
2233 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2234 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2236 // If this is another user's talk page, update newtalk.
2237 // Don't do this if $options['changed'] = false (null-edits) nor if
2238 // it's a minor edit and the user doesn't want notifications for those.
2239 if ( $options['changed']
2240 && $this->mTitle
->getNamespace() == NS_USER_TALK
2241 && $shortTitle != $user->getTitleKey()
2242 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2244 $recipient = User
::newFromName( $shortTitle, false );
2245 if ( !$recipient ) {
2246 wfDebug( __METHOD__
. ": invalid username\n" );
2248 // Avoid PHP 7.1 warning of passing $this by reference
2251 // Allow extensions to prevent user notification
2252 // when a new message is added to their talk page
2253 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2254 if ( User
::isIP( $shortTitle ) ) {
2255 // An anonymous user
2256 $recipient->setNewtalk( true, $revision );
2257 } elseif ( $recipient->isLoggedIn() ) {
2258 $recipient->setNewtalk( true, $revision );
2260 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2266 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2267 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2270 if ( $options['created'] ) {
2271 self
::onArticleCreate( $this->mTitle
);
2272 } elseif ( $options['changed'] ) { // T52785
2273 self
::onArticleEdit( $this->mTitle
, $revision );
2276 ResourceLoaderWikiModule
::invalidateModuleCache(
2277 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2282 * Update the article's restriction field, and leave a log entry.
2283 * This works for protection both existing and non-existing pages.
2285 * @param array $limit Set of restriction keys
2286 * @param array $expiry Per restriction type expiration
2287 * @param int &$cascade Set to false if cascading protection isn't allowed.
2288 * @param string $reason
2289 * @param User $user The user updating the restrictions
2290 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2291 * ($user should be able to add the specified tags before this is called)
2292 * @return Status Status object; if action is taken, $status->value is the log_id of the
2293 * protection log entry.
2295 public function doUpdateRestrictions( array $limit, array $expiry,
2296 &$cascade, $reason, User
$user, $tags = null
2298 global $wgCascadingRestrictionLevels, $wgContLang;
2300 if ( wfReadOnly() ) {
2301 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2304 $this->loadPageData( 'fromdbmaster' );
2305 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2306 $id = $this->getId();
2312 // Take this opportunity to purge out expired restrictions
2313 Title
::purgeExpiredRestrictions();
2315 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2316 // we expect a single selection, but the schema allows otherwise.
2317 $isProtected = false;
2321 $dbw = wfGetDB( DB_MASTER
);
2323 foreach ( $restrictionTypes as $action ) {
2324 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2325 $expiry[$action] = 'infinity';
2327 if ( !isset( $limit[$action] ) ) {
2328 $limit[$action] = '';
2329 } elseif ( $limit[$action] != '' ) {
2333 // Get current restrictions on $action
2334 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2335 if ( $current != '' ) {
2336 $isProtected = true;
2339 if ( $limit[$action] != $current ) {
2341 } elseif ( $limit[$action] != '' ) {
2342 // Only check expiry change if the action is actually being
2343 // protected, since expiry does nothing on an not-protected
2345 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2351 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2355 // If nothing has changed, do nothing
2357 return Status
::newGood();
2360 if ( !$protect ) { // No protection at all means unprotection
2361 $revCommentMsg = 'unprotectedarticle-comment';
2362 $logAction = 'unprotect';
2363 } elseif ( $isProtected ) {
2364 $revCommentMsg = 'modifiedarticleprotection-comment';
2365 $logAction = 'modify';
2367 $revCommentMsg = 'protectedarticle-comment';
2368 $logAction = 'protect';
2371 // Truncate for whole multibyte characters
2372 $reason = $wgContLang->truncate( $reason, 255 );
2374 $logRelationsValues = [];
2375 $logRelationsField = null;
2376 $logParamsDetails = [];
2378 // Null revision (used for change tag insertion)
2379 $nullRevision = null;
2381 if ( $id ) { // Protection of existing page
2382 // Avoid PHP 7.1 warning of passing $this by reference
2385 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2386 return Status
::newGood();
2389 // Only certain restrictions can cascade...
2390 $editrestriction = isset( $limit['edit'] )
2391 ?
[ $limit['edit'] ]
2392 : $this->mTitle
->getRestrictions( 'edit' );
2393 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2394 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2396 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2397 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2400 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2401 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2402 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2404 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2405 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2408 // The schema allows multiple restrictions
2409 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2413 // insert null revision to identify the page protection change as edit summary
2414 $latest = $this->getLatest();
2415 $nullRevision = $this->insertProtectNullRevision(
2424 if ( $nullRevision === null ) {
2425 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2428 $logRelationsField = 'pr_id';
2430 // Update restrictions table
2431 foreach ( $limit as $action => $restrictions ) {
2433 'page_restrictions',
2436 'pr_type' => $action
2440 if ( $restrictions != '' ) {
2441 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2443 'page_restrictions',
2445 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2447 'pr_type' => $action,
2448 'pr_level' => $restrictions,
2449 'pr_cascade' => $cascadeValue,
2450 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2454 $logRelationsValues[] = $dbw->insertId();
2455 $logParamsDetails[] = [
2457 'level' => $restrictions,
2458 'expiry' => $expiry[$action],
2459 'cascade' => (bool)$cascadeValue,
2464 // Clear out legacy restriction fields
2467 [ 'page_restrictions' => '' ],
2468 [ 'page_id' => $id ],
2472 // Avoid PHP 7.1 warning of passing $this by reference
2475 Hooks
::run( 'NewRevisionFromEditComplete',
2476 [ $this, $nullRevision, $latest, $user ] );
2477 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2478 } else { // Protection of non-existing page (also known as "title protection")
2479 // Cascade protection is meaningless in this case
2482 if ( $limit['create'] != '' ) {
2483 $dbw->replace( 'protected_titles',
2484 [ [ 'pt_namespace', 'pt_title' ] ],
2486 'pt_namespace' => $this->mTitle
->getNamespace(),
2487 'pt_title' => $this->mTitle
->getDBkey(),
2488 'pt_create_perm' => $limit['create'],
2489 'pt_timestamp' => $dbw->timestamp(),
2490 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2491 'pt_user' => $user->getId(),
2492 'pt_reason' => $reason,
2495 $logParamsDetails[] = [
2497 'level' => $limit['create'],
2498 'expiry' => $expiry['create'],
2501 $dbw->delete( 'protected_titles',
2503 'pt_namespace' => $this->mTitle
->getNamespace(),
2504 'pt_title' => $this->mTitle
->getDBkey()
2510 $this->mTitle
->flushRestrictions();
2511 InfoAction
::invalidateCache( $this->mTitle
);
2513 if ( $logAction == 'unprotect' ) {
2516 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2518 '4::description' => $protectDescriptionLog, // parameter for IRC
2519 '5:bool:cascade' => $cascade,
2520 'details' => $logParamsDetails, // parameter for localize and api
2524 // Update the protection log
2525 $logEntry = new ManualLogEntry( 'protect', $logAction );
2526 $logEntry->setTarget( $this->mTitle
);
2527 $logEntry->setComment( $reason );
2528 $logEntry->setPerformer( $user );
2529 $logEntry->setParameters( $params );
2530 if ( !is_null( $nullRevision ) ) {
2531 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2533 $logEntry->setTags( $tags );
2534 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2535 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2537 $logId = $logEntry->insert();
2538 $logEntry->publish( $logId );
2540 return Status
::newGood( $logId );
2544 * Insert a new null revision for this page.
2546 * @param string $revCommentMsg Comment message key for the revision
2547 * @param array $limit Set of restriction keys
2548 * @param array $expiry Per restriction type expiration
2549 * @param int $cascade Set to false if cascading protection isn't allowed.
2550 * @param string $reason
2551 * @param User|null $user
2552 * @return Revision|null Null on error
2554 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2555 array $expiry, $cascade, $reason, $user = null
2557 $dbw = wfGetDB( DB_MASTER
);
2559 // Prepare a null revision to be added to the history
2560 $editComment = wfMessage(
2562 $this->mTitle
->getPrefixedText(),
2563 $user ?
$user->getName() : ''
2564 )->inContentLanguage()->text();
2566 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2568 $protectDescription = $this->protectDescription( $limit, $expiry );
2569 if ( $protectDescription ) {
2570 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2571 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2572 ->inContentLanguage()->text();
2575 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2576 $editComment .= wfMessage( 'brackets' )->params(
2577 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2578 )->inContentLanguage()->text();
2581 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2583 $nullRev->insertOn( $dbw );
2585 // Update page record and touch page
2586 $oldLatest = $nullRev->getParentId();
2587 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2594 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2597 protected function formatExpiry( $expiry ) {
2600 if ( $expiry != 'infinity' ) {
2603 $wgContLang->timeanddate( $expiry, false, false ),
2604 $wgContLang->date( $expiry, false, false ),
2605 $wgContLang->time( $expiry, false, false )
2606 )->inContentLanguage()->text();
2608 return wfMessage( 'protect-expiry-indefinite' )
2609 ->inContentLanguage()->text();
2614 * Builds the description to serve as comment for the edit.
2616 * @param array $limit Set of restriction keys
2617 * @param array $expiry Per restriction type expiration
2620 public function protectDescription( array $limit, array $expiry ) {
2621 $protectDescription = '';
2623 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2624 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2625 # All possible message keys are listed here for easier grepping:
2626 # * restriction-create
2627 # * restriction-edit
2628 # * restriction-move
2629 # * restriction-upload
2630 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2631 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2632 # with '' filtered out. All possible message keys are listed below:
2633 # * protect-level-autoconfirmed
2634 # * protect-level-sysop
2635 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2636 ->inContentLanguage()->text();
2638 $expiryText = $this->formatExpiry( $expiry[$action] );
2640 if ( $protectDescription !== '' ) {
2641 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2643 $protectDescription .= wfMessage( 'protect-summary-desc' )
2644 ->params( $actionText, $restrictionsText, $expiryText )
2645 ->inContentLanguage()->text();
2648 return $protectDescription;
2652 * Builds the description to serve as comment for the log entry.
2654 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2655 * protect description text. Keep them in old format to avoid breaking compatibility.
2656 * TODO: Fix protection log to store structured description and format it on-the-fly.
2658 * @param array $limit Set of restriction keys
2659 * @param array $expiry Per restriction type expiration
2662 public function protectDescriptionLog( array $limit, array $expiry ) {
2665 $protectDescriptionLog = '';
2667 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2668 $expiryText = $this->formatExpiry( $expiry[$action] );
2669 $protectDescriptionLog .= $wgContLang->getDirMark() .
2670 "[$action=$restrictions] ($expiryText)";
2673 return trim( $protectDescriptionLog );
2677 * Take an array of page restrictions and flatten it to a string
2678 * suitable for insertion into the page_restrictions field.
2680 * @param string[] $limit
2682 * @throws MWException
2685 protected static function flattenRestrictions( $limit ) {
2686 if ( !is_array( $limit ) ) {
2687 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2693 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2694 $bits[] = "$action=$restrictions";
2697 return implode( ':', $bits );
2701 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2702 * backwards compatibility, if you care about error reporting you should use
2703 * doDeleteArticleReal() instead.
2705 * Deletes the article with database consistency, writes logs, purges caches
2707 * @param string $reason Delete reason for deletion log
2708 * @param bool $suppress Suppress all revisions and log the deletion in
2709 * the suppression log instead of the deletion log
2710 * @param int $u1 Unused
2711 * @param bool $u2 Unused
2712 * @param array|string &$error Array of errors to append to
2713 * @param User $user The deleting user
2714 * @return bool True if successful
2716 public function doDeleteArticle(
2717 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2719 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2720 return $status->isGood();
2724 * Back-end article deletion
2725 * Deletes the article with database consistency, writes logs, purges caches
2729 * @param string $reason Delete reason for deletion log
2730 * @param bool $suppress Suppress all revisions and log the deletion in
2731 * the suppression log instead of the deletion log
2732 * @param int $u1 Unused
2733 * @param bool $u2 Unused
2734 * @param array|string &$error Array of errors to append to
2735 * @param User $user The deleting user
2736 * @param array $tags Tags to apply to the deletion action
2737 * @return Status Status object; if successful, $status->value is the log_id of the
2738 * deletion log entry. If the page couldn't be deleted because it wasn't
2739 * found, $status is a non-fatal 'cannotdelete' error
2741 public function doDeleteArticleReal(
2742 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2743 $tags = [], $logsubtype = 'delete'
2745 global $wgUser, $wgContentHandlerUseDB;
2747 wfDebug( __METHOD__
. "\n" );
2749 $status = Status
::newGood();
2751 if ( $this->mTitle
->getDBkey() === '' ) {
2752 $status->error( 'cannotdelete',
2753 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2757 // Avoid PHP 7.1 warning of passing $this by reference
2760 $user = is_null( $user ) ?
$wgUser : $user;
2761 if ( !Hooks
::run( 'ArticleDelete',
2762 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2764 if ( $status->isOK() ) {
2765 // Hook aborted but didn't set a fatal status
2766 $status->fatal( 'delete-hook-aborted' );
2771 $dbw = wfGetDB( DB_MASTER
);
2772 $dbw->startAtomic( __METHOD__
);
2774 $this->loadPageData( self
::READ_LATEST
);
2775 $id = $this->getId();
2776 // T98706: lock the page from various other updates but avoid using
2777 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2778 // the revisions queries (which also JOIN on user). Only lock the page
2779 // row and CAS check on page_latest to see if the trx snapshot matches.
2780 $lockedLatest = $this->lockAndGetLatest();
2781 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2782 $dbw->endAtomic( __METHOD__
);
2783 // Page not there or trx snapshot is stale
2784 $status->error( 'cannotdelete',
2785 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2789 // Given the lock above, we can be confident in the title and page ID values
2790 $namespace = $this->getTitle()->getNamespace();
2791 $dbKey = $this->getTitle()->getDBkey();
2793 // At this point we are now comitted to returning an OK
2794 // status unless some DB query error or other exception comes up.
2795 // This way callers don't have to call rollback() if $status is bad
2796 // unless they actually try to catch exceptions (which is rare).
2798 // we need to remember the old content so we can use it to generate all deletion updates.
2799 $revision = $this->getRevision();
2801 $content = $this->getContent( Revision
::RAW
);
2802 } catch ( Exception
$ex ) {
2803 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2804 . $ex->getMessage() );
2809 $fields = Revision
::selectFields();
2812 // Bitfields to further suppress the content
2814 $bitfield = Revision
::SUPPRESSED_ALL
;
2815 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2818 // For now, shunt the revision data into the archive table.
2819 // Text is *not* removed from the text table; bulk storage
2820 // is left intact to avoid breaking block-compression or
2821 // immutable storage schemes.
2822 // In the future, we may keep revisions and mark them with
2823 // the rev_deleted field, which is reserved for this purpose.
2825 // Get all of the page revisions
2826 $res = $dbw->select(
2829 [ 'rev_page' => $id ],
2833 // Build their equivalent archive rows
2835 foreach ( $res as $row ) {
2837 'ar_namespace' => $namespace,
2838 'ar_title' => $dbKey,
2839 'ar_comment' => $row->rev_comment
,
2840 'ar_user' => $row->rev_user
,
2841 'ar_user_text' => $row->rev_user_text
,
2842 'ar_timestamp' => $row->rev_timestamp
,
2843 'ar_minor_edit' => $row->rev_minor_edit
,
2844 'ar_rev_id' => $row->rev_id
,
2845 'ar_parent_id' => $row->rev_parent_id
,
2846 'ar_text_id' => $row->rev_text_id
,
2849 'ar_len' => $row->rev_len
,
2850 'ar_page_id' => $id,
2851 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2852 'ar_sha1' => $row->rev_sha1
,
2854 if ( $wgContentHandlerUseDB ) {
2855 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2856 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2858 $rowsInsert[] = $rowInsert;
2860 // Copy them into the archive table
2861 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2862 // Save this so we can pass it to the ArticleDeleteComplete hook.
2863 $archivedRevisionCount = $dbw->affectedRows();
2865 // Clone the title and wikiPage, so we have the information we need when
2866 // we log and run the ArticleDeleteComplete hook.
2867 $logTitle = clone $this->mTitle
;
2868 $wikiPageBeforeDelete = clone $this;
2870 // Now that it's safely backed up, delete it
2871 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2872 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2874 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2875 $logtype = $suppress ?
'suppress' : 'delete';
2877 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2878 $logEntry->setPerformer( $user );
2879 $logEntry->setTarget( $logTitle );
2880 $logEntry->setComment( $reason );
2881 $logEntry->setTags( $tags );
2882 $logid = $logEntry->insert();
2884 $dbw->onTransactionPreCommitOrIdle(
2885 function () use ( $dbw, $logEntry, $logid ) {
2886 // T58776: avoid deadlocks (especially from FileDeleteForm)
2887 $logEntry->publish( $logid );
2892 $dbw->endAtomic( __METHOD__
);
2894 $this->doDeleteUpdates( $id, $content, $revision );
2896 Hooks
::run( 'ArticleDeleteComplete', [
2897 &$wikiPageBeforeDelete,
2903 $archivedRevisionCount
2905 $status->value
= $logid;
2907 // Show log excerpt on 404 pages rather than just a link
2908 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2909 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2910 $cache->set( $key, 1, $cache::TTL_DAY
);
2916 * Lock the page row for this title+id and return page_latest (or 0)
2918 * @return integer Returns 0 if no row was found with this title+id
2921 public function lockAndGetLatest() {
2922 return (int)wfGetDB( DB_MASTER
)->selectField(
2926 'page_id' => $this->getId(),
2927 // Typically page_id is enough, but some code might try to do
2928 // updates assuming the title is the same, so verify that
2929 'page_namespace' => $this->getTitle()->getNamespace(),
2930 'page_title' => $this->getTitle()->getDBkey()
2938 * Do some database updates after deletion
2940 * @param int $id The page_id value of the page being deleted
2941 * @param Content|null $content Optional page content to be used when determining
2942 * the required updates. This may be needed because $this->getContent()
2943 * may already return null when the page proper was deleted.
2944 * @param Revision|null $revision The latest page revision
2946 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2948 $countable = $this->isCountable();
2949 } catch ( Exception
$ex ) {
2950 // fallback for deleting broken pages for which we cannot load the content for
2951 // some reason. Note that doDeleteArticleReal() already logged this problem.
2955 // Update site status
2956 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2958 // Delete pagelinks, update secondary indexes, etc
2959 $updates = $this->getDeletionUpdates( $content );
2960 foreach ( $updates as $update ) {
2961 DeferredUpdates
::addUpdate( $update );
2964 // Reparse any pages transcluding this page
2965 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2967 // Reparse any pages including this image
2968 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2969 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2973 WikiPage
::onArticleDelete( $this->mTitle
);
2974 ResourceLoaderWikiModule
::invalidateModuleCache(
2975 $this->mTitle
, $revision, null, wfWikiID()
2978 // Reset this object and the Title object
2979 $this->loadFromRow( false, self
::READ_LATEST
);
2982 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2986 * Roll back the most recent consecutive set of edits to a page
2987 * from the same user; fails if there are no eligible edits to
2988 * roll back to, e.g. user is the sole contributor. This function
2989 * performs permissions checks on $user, then calls commitRollback()
2990 * to do the dirty work
2992 * @todo Separate the business/permission stuff out from backend code
2993 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2995 * @param string $fromP Name of the user whose edits to rollback.
2996 * @param string $summary Custom summary. Set to default summary if empty.
2997 * @param string $token Rollback token.
2998 * @param bool $bot If true, mark all reverted edits as bot.
3000 * @param array $resultDetails Array contains result-specific array of additional values
3001 * 'alreadyrolled' : 'current' (rev)
3002 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3004 * @param User $user The user performing the rollback
3005 * @param array|null $tags Change tags to apply to the rollback
3006 * Callers are responsible for permission checks
3007 * (with ChangeTags::canAddTagsAccompanyingChange)
3009 * @return array Array of errors, each error formatted as
3010 * array(messagekey, param1, param2, ...).
3011 * On success, the array is empty. This array can also be passed to
3012 * OutputPage::showPermissionsErrorPage().
3014 public function doRollback(
3015 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3017 $resultDetails = null;
3019 // Check permissions
3020 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3021 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3022 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3024 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3025 $errors[] = [ 'sessionfailure' ];
3028 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3029 $errors[] = [ 'actionthrottledtext' ];
3032 // If there were errors, bail out now
3033 if ( !empty( $errors ) ) {
3037 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3041 * Backend implementation of doRollback(), please refer there for parameter
3042 * and return value documentation
3044 * NOTE: This function does NOT check ANY permissions, it just commits the
3045 * rollback to the DB. Therefore, you should only call this function direct-
3046 * ly if you want to use custom permissions checks. If you don't, use
3047 * doRollback() instead.
3048 * @param string $fromP Name of the user whose edits to rollback.
3049 * @param string $summary Custom summary. Set to default summary if empty.
3050 * @param bool $bot If true, mark all reverted edits as bot.
3052 * @param array $resultDetails Contains result-specific array of additional values
3053 * @param User $guser The user performing the rollback
3054 * @param array|null $tags Change tags to apply to the rollback
3055 * Callers are responsible for permission checks
3056 * (with ChangeTags::canAddTagsAccompanyingChange)
3060 public function commitRollback( $fromP, $summary, $bot,
3061 &$resultDetails, User
$guser, $tags = null
3063 global $wgUseRCPatrol, $wgContLang;
3065 $dbw = wfGetDB( DB_MASTER
);
3067 if ( wfReadOnly() ) {
3068 return [ [ 'readonlytext' ] ];
3071 // Get the last editor
3072 $current = $this->getRevision();
3073 if ( is_null( $current ) ) {
3074 // Something wrong... no page?
3075 return [ [ 'notanarticle' ] ];
3078 $from = str_replace( '_', ' ', $fromP );
3079 // User name given should match up with the top revision.
3080 // If the user was deleted then $from should be empty.
3081 if ( $from != $current->getUserText() ) {
3082 $resultDetails = [ 'current' => $current ];
3083 return [ [ 'alreadyrolled',
3084 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3085 htmlspecialchars( $fromP ),
3086 htmlspecialchars( $current->getUserText() )
3090 // Get the last edit not by this person...
3091 // Note: these may not be public values
3092 $user = intval( $current->getUser( Revision
::RAW
) );
3093 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3094 $s = $dbw->selectRow( 'revision',
3095 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3096 [ 'rev_page' => $current->getPage(),
3097 "rev_user != {$user} OR rev_user_text != {$user_text}"
3099 [ 'USE INDEX' => 'page_timestamp',
3100 'ORDER BY' => 'rev_timestamp DESC' ]
3102 if ( $s === false ) {
3103 // No one else ever edited this page
3104 return [ [ 'cantrollback' ] ];
3105 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3106 ||
$s->rev_deleted
& Revision
::DELETED_USER
3108 // Only admins can see this text
3109 return [ [ 'notvisiblerev' ] ];
3112 // Generate the edit summary if necessary
3113 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3114 if ( empty( $summary ) ) {
3115 if ( $from == '' ) { // no public user name
3116 $summary = wfMessage( 'revertpage-nouser' );
3118 $summary = wfMessage( 'revertpage' );
3122 // Allow the custom summary to use the same args as the default message
3124 $target->getUserText(), $from, $s->rev_id
,
3125 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3126 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3128 if ( $summary instanceof Message
) {
3129 $summary = $summary->params( $args )->inContentLanguage()->text();
3131 $summary = wfMsgReplaceArgs( $summary, $args );
3134 // Trim spaces on user supplied text
3135 $summary = trim( $summary );
3137 // Truncate for whole multibyte characters.
3138 $summary = $wgContLang->truncate( $summary, 255 );
3141 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3143 if ( $guser->isAllowed( 'minoredit' ) ) {
3144 $flags |
= EDIT_MINOR
;
3147 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3148 $flags |
= EDIT_FORCE_BOT
;
3151 $targetContent = $target->getContent();
3152 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3154 // Actually store the edit
3155 $status = $this->doEditContent(
3165 // Set patrolling and bot flag on the edits, which gets rollbacked.
3166 // This is done even on edit failure to have patrolling in that case (T64157).
3168 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3169 // Mark all reverted edits as bot
3173 if ( $wgUseRCPatrol ) {
3174 // Mark all reverted edits as patrolled
3175 $set['rc_patrolled'] = 1;
3178 if ( count( $set ) ) {
3179 $dbw->update( 'recentchanges', $set,
3181 'rc_cur_id' => $current->getPage(),
3182 'rc_user_text' => $current->getUserText(),
3183 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3189 if ( !$status->isOK() ) {
3190 return $status->getErrorsArray();
3193 // raise error, when the edit is an edit without a new version
3194 $statusRev = isset( $status->value
['revision'] )
3195 ?
$status->value
['revision']
3197 if ( !( $statusRev instanceof Revision
) ) {
3198 $resultDetails = [ 'current' => $current ];
3199 return [ [ 'alreadyrolled',
3200 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3201 htmlspecialchars( $fromP ),
3202 htmlspecialchars( $current->getUserText() )
3206 if ( $changingContentModel ) {
3207 // If the content model changed during the rollback,
3208 // make sure it gets logged to Special:Log/contentmodel
3209 $log = new ManualLogEntry( 'contentmodel', 'change' );
3210 $log->setPerformer( $guser );
3211 $log->setTarget( $this->mTitle
);
3212 $log->setComment( $summary );
3213 $log->setParameters( [
3214 '4::oldmodel' => $current->getContentModel(),
3215 '5::newmodel' => $targetContent->getModel(),
3218 $logId = $log->insert( $dbw );
3219 $log->publish( $logId );
3222 $revId = $statusRev->getId();
3224 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3227 'summary' => $summary,
3228 'current' => $current,
3229 'target' => $target,
3237 * The onArticle*() functions are supposed to be a kind of hooks
3238 * which should be called whenever any of the specified actions
3241 * This is a good place to put code to clear caches, for instance.
3243 * This is called on page move and undelete, as well as edit
3245 * @param Title $title
3247 public static function onArticleCreate( Title
$title ) {
3248 // Update existence markers on article/talk tabs...
3249 $other = $title->getOtherPage();
3251 $other->purgeSquid();
3253 $title->touchLinks();
3254 $title->purgeSquid();
3255 $title->deleteTitleProtection();
3257 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3259 // Invalidate caches of articles which include this page
3260 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3262 if ( $title->getNamespace() == NS_CATEGORY
) {
3263 // Load the Category object, which will schedule a job to create
3264 // the category table row if necessary. Checking a replica DB is ok
3265 // here, in the worst case it'll run an unnecessary recount job on
3266 // a category that probably doesn't have many members.
3267 Category
::newFromTitle( $title )->getID();
3272 * Clears caches when article is deleted
3274 * @param Title $title
3276 public static function onArticleDelete( Title
$title ) {
3277 // Update existence markers on article/talk tabs...
3278 $other = $title->getOtherPage();
3280 $other->purgeSquid();
3282 $title->touchLinks();
3283 $title->purgeSquid();
3285 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3288 HTMLFileCache
::clearFileCache( $title );
3289 InfoAction
::invalidateCache( $title );
3292 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3293 MessageCache
::singleton()->updateMessageOverride( $title, null );
3297 if ( $title->getNamespace() == NS_FILE
) {
3298 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3302 if ( $title->getNamespace() == NS_USER_TALK
) {
3303 $user = User
::newFromName( $title->getText(), false );
3305 $user->setNewtalk( false );
3310 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3314 * Purge caches on page update etc
3316 * @param Title $title
3317 * @param Revision|null $revision Revision that was just saved, may be null
3319 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3320 // Invalidate caches of articles which include this page
3321 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3323 // Invalidate the caches of all pages which redirect here
3324 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3326 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3328 // Purge CDN for this page only
3329 $title->purgeSquid();
3330 // Clear file cache for this page only
3331 HTMLFileCache
::clearFileCache( $title );
3333 $revid = $revision ?
$revision->getId() : null;
3334 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3335 InfoAction
::invalidateCache( $title, $revid );
3342 * Returns a list of categories this page is a member of.
3343 * Results will include hidden categories
3345 * @return TitleArray
3347 public function getCategories() {
3348 $id = $this->getId();
3350 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3353 $dbr = wfGetDB( DB_REPLICA
);
3354 $res = $dbr->select( 'categorylinks',
3355 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3356 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3357 // as not being aliases, and NS_CATEGORY is numeric
3358 [ 'cl_from' => $id ],
3361 return TitleArray
::newFromResult( $res );
3365 * Returns a list of hidden categories this page is a member of.
3366 * Uses the page_props and categorylinks tables.
3368 * @return array Array of Title objects
3370 public function getHiddenCategories() {
3372 $id = $this->getId();
3378 $dbr = wfGetDB( DB_REPLICA
);
3379 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3381 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3382 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3385 if ( $res !== false ) {
3386 foreach ( $res as $row ) {
3387 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3395 * Auto-generates a deletion reason
3397 * @param bool &$hasHistory Whether the page has a history
3398 * @return string|bool String containing deletion reason or empty string, or boolean false
3399 * if no revision occurred
3401 public function getAutoDeleteReason( &$hasHistory ) {
3402 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3406 * Update all the appropriate counts in the category table, given that
3407 * we've added the categories $added and deleted the categories $deleted.
3409 * This should only be called from deferred updates or jobs to avoid contention.
3411 * @param array $added The names of categories that were added
3412 * @param array $deleted The names of categories that were deleted
3413 * @param integer $id Page ID (this should be the original deleted page ID)
3415 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3416 $id = $id ?
: $this->getId();
3417 $ns = $this->getTitle()->getNamespace();
3419 $addFields = [ 'cat_pages = cat_pages + 1' ];
3420 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3421 if ( $ns == NS_CATEGORY
) {
3422 $addFields[] = 'cat_subcats = cat_subcats + 1';
3423 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3424 } elseif ( $ns == NS_FILE
) {
3425 $addFields[] = 'cat_files = cat_files + 1';
3426 $removeFields[] = 'cat_files = cat_files - 1';
3429 $dbw = wfGetDB( DB_MASTER
);
3431 if ( count( $added ) ) {
3432 $existingAdded = $dbw->selectFieldValues(
3435 [ 'cat_title' => $added ],
3439 // For category rows that already exist, do a plain
3440 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3441 // to avoid creating gaps in the cat_id sequence.
3442 if ( count( $existingAdded ) ) {
3446 [ 'cat_title' => $existingAdded ],
3451 $missingAdded = array_diff( $added, $existingAdded );
3452 if ( count( $missingAdded ) ) {
3454 foreach ( $missingAdded as $cat ) {
3456 'cat_title' => $cat,
3458 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3459 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3472 if ( count( $deleted ) ) {
3476 [ 'cat_title' => $deleted ],
3481 foreach ( $added as $catName ) {
3482 $cat = Category
::newFromName( $catName );
3483 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3486 foreach ( $deleted as $catName ) {
3487 $cat = Category
::newFromName( $catName );
3488 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3491 // Refresh counts on categories that should be empty now, to
3492 // trigger possible deletion. Check master for the most
3493 // up-to-date cat_pages.
3494 if ( count( $deleted ) ) {
3495 $rows = $dbw->select(
3497 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3498 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3501 foreach ( $rows as $row ) {
3502 $cat = Category
::newFromRow( $row );
3503 // T166757: do the update after this DB commit
3504 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3505 $cat->refreshCounts();
3512 * Opportunistically enqueue link update jobs given fresh parser output if useful
3514 * @param ParserOutput $parserOutput Current version page output
3517 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3518 if ( wfReadOnly() ) {
3522 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3523 [ $this, $this->mTitle
, $parserOutput ]
3528 $config = RequestContext
::getMain()->getConfig();
3531 'isOpportunistic' => true,
3532 'rootJobTimestamp' => $parserOutput->getCacheTime()
3535 if ( $this->mTitle
->areRestrictionsCascading() ) {
3536 // If the page is cascade protecting, the links should really be up-to-date
3537 JobQueueGroup
::singleton()->lazyPush(
3538 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3540 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3541 // Assume the output contains "dynamic" time/random based magic words.
3542 // Only update pages that expired due to dynamic content and NOT due to edits
3543 // to referenced templates/files. When the cache expires due to dynamic content,
3544 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3545 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3546 // template/file edit already triggered recursive RefreshLinksJob jobs.
3547 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3548 // If a page is uncacheable, do not keep spamming a job for it.
3549 // Although it would be de-duplicated, it would still waste I/O.
3550 $cache = ObjectCache
::getLocalClusterInstance();
3551 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3552 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3553 if ( $cache->add( $key, time(), $ttl ) ) {
3554 JobQueueGroup
::singleton()->lazyPush(
3555 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3563 * Returns a list of updates to be performed when this page is deleted. The
3564 * updates should remove any information about this page from secondary data
3565 * stores such as links tables.
3567 * @param Content|null $content Optional Content object for determining the
3568 * necessary updates.
3569 * @return DeferrableUpdate[]
3571 public function getDeletionUpdates( Content
$content = null ) {
3573 // load content object, which may be used to determine the necessary updates.
3574 // XXX: the content may not be needed to determine the updates.
3576 $content = $this->getContent( Revision
::RAW
);
3577 } catch ( Exception
$ex ) {
3578 // If we can't load the content, something is wrong. Perhaps that's why
3579 // the user is trying to delete the page, so let's not fail in that case.
3580 // Note that doDeleteArticleReal() will already have logged an issue with
3581 // loading the content.
3588 $updates = $content->getDeletionUpdates( $this );
3591 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3596 * Whether this content displayed on this page
3597 * comes from the local database
3602 public function isLocal() {
3607 * The display name for the site this content
3608 * come from. If a subclass overrides isLocal(),
3609 * this could return something other than the
3615 public function getWikiDisplayName() {
3621 * Get the source URL for the content on this page,
3622 * typically the canonical URL, but may be a remote
3623 * link if the content comes from another site
3628 public function getSourceURL() {
3629 return $this->getTitle()->getCanonicalURL();
3633 * @param WANObjectCache $cache
3637 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3638 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3640 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );