3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use \MediaWiki\Logger\LoggerFactory
;
25 use \MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\FakeResultWrapper
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\DBError
;
29 use Wikimedia\Rdbms\DBUnexpectedError
;
32 * Class representing a MediaWiki article and history.
34 * Some fields are public only for backwards-compatibility. Use accessors.
35 * In the past, this class was part of Article.php and everything was public.
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mLinksUpdated = '19700101000000';
91 /** @deprecated since 1.29. Added in 1.28 for partial purging, no longer used. */
92 const PURGE_CDN_CACHE
= 1;
93 const PURGE_CLUSTER_PCACHE
= 2;
94 const PURGE_GLOBAL_PCACHE
= 4;
98 * Constructor and clear the article
99 * @param Title $title Reference to a Title object.
101 public function __construct( Title
$title ) {
102 $this->mTitle
= $title;
106 * Makes sure that the mTitle object is cloned
107 * to the newly cloned WikiPage.
109 public function __clone() {
110 $this->mTitle
= clone $this->mTitle
;
114 * Create a WikiPage object of the appropriate class for the given title.
116 * @param Title $title
118 * @throws MWException
119 * @return WikiPage|WikiCategoryPage|WikiFilePage
121 public static function factory( Title
$title ) {
122 $ns = $title->getNamespace();
124 if ( $ns == NS_MEDIA
) {
125 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
126 } elseif ( $ns < 0 ) {
127 throw new MWException( "Invalid or virtual namespace $ns given." );
131 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
137 $page = new WikiFilePage( $title );
140 $page = new WikiCategoryPage( $title );
143 $page = new WikiPage( $title );
150 * Constructor from a page id
152 * @param int $id Article ID to load
153 * @param string|int $from One of the following values:
154 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
155 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
157 * @return WikiPage|null
159 public static function newFromID( $id, $from = 'fromdb' ) {
160 // page ids are never 0 or negative, see T63166
165 $from = self
::convertSelectType( $from );
166 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
167 $row = $db->selectRow(
168 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
172 return self
::newFromRow( $row, $from );
176 * Constructor from a database row
179 * @param object $row Database row containing at least fields returned by selectFields().
180 * @param string|int $from Source of $data:
181 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
182 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
183 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
186 public static function newFromRow( $row, $from = 'fromdb' ) {
187 $page = self
::factory( Title
::newFromRow( $row ) );
188 $page->loadFromRow( $row, $from );
193 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
195 * @param object|string|int $type
198 private static function convertSelectType( $type ) {
201 return self
::READ_NORMAL
;
203 return self
::READ_LATEST
;
205 return self
::READ_LOCKING
;
207 // It may already be an integer or whatever else
213 * @todo Move this UI stuff somewhere else
215 * @see ContentHandler::getActionOverrides
217 public function getActionOverrides() {
218 return $this->getContentHandler()->getActionOverrides();
222 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
224 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
226 * @return ContentHandler
230 public function getContentHandler() {
231 return ContentHandler
::getForModelID( $this->getContentModel() );
235 * Get the title object of the article
236 * @return Title Title object of this page
238 public function getTitle() {
239 return $this->mTitle
;
246 public function clear() {
247 $this->mDataLoaded
= false;
248 $this->mDataLoadedFrom
= self
::READ_NONE
;
250 $this->clearCacheFields();
254 * Clear the object cache fields
257 protected function clearCacheFields() {
259 $this->mRedirectTarget
= null; // Title object if set
260 $this->mLastRevision
= null; // Latest revision
261 $this->mTouched
= '19700101000000';
262 $this->mLinksUpdated
= '19700101000000';
263 $this->mTimestamp
= '';
264 $this->mIsRedirect
= false;
265 $this->mLatest
= false;
266 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
267 // the requested rev ID and content against the cached one for equality. For most
268 // content types, the output should not change during the lifetime of this cache.
269 // Clearing it can cause extra parses on edit for no reason.
273 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
277 public function clearPreparedEdit() {
278 $this->mPreparedEdit
= false;
282 * Return the list of revision fields that should be selected to create
287 public static function selectFields() {
288 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
299 'page_links_updated',
304 if ( $wgContentHandlerUseDB ) {
305 $fields[] = 'page_content_model';
308 if ( $wgPageLanguageUseDB ) {
309 $fields[] = 'page_lang';
316 * Fetch a page record with the given conditions
317 * @param IDatabase $dbr
318 * @param array $conditions
319 * @param array $options
320 * @return object|bool Database result resource, or false on failure
322 protected function pageData( $dbr, $conditions, $options = [] ) {
323 $fields = self
::selectFields();
325 // Avoid PHP 7.1 warning of passing $this by reference
328 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
330 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
332 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
338 * Fetch a page record matching the Title object's namespace and title
339 * using a sanitized title string
341 * @param IDatabase $dbr
342 * @param Title $title
343 * @param array $options
344 * @return object|bool Database result resource, or false on failure
346 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
347 return $this->pageData( $dbr, [
348 'page_namespace' => $title->getNamespace(),
349 'page_title' => $title->getDBkey() ], $options );
353 * Fetch a page record matching the requested ID
355 * @param IDatabase $dbr
357 * @param array $options
358 * @return object|bool Database result resource, or false on failure
360 public function pageDataFromId( $dbr, $id, $options = [] ) {
361 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
365 * Load the object from a given source by title
367 * @param object|string|int $from One of the following:
368 * - A DB query result object.
369 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
370 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
371 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
372 * using SELECT FOR UPDATE.
376 public function loadPageData( $from = 'fromdb' ) {
377 $from = self
::convertSelectType( $from );
378 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
379 // We already have the data from the correct location, no need to load it twice.
383 if ( is_int( $from ) ) {
384 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
385 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
386 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
389 && $index == DB_REPLICA
390 && $loadBalancer->getServerCount() > 1
391 && $loadBalancer->hasOrMadeRecentMasterChanges()
393 $from = self
::READ_LATEST
;
394 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
395 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
398 // No idea from where the caller got this data, assume replica DB.
400 $from = self
::READ_NORMAL
;
403 $this->loadFromRow( $data, $from );
407 * Load the object from a database row
410 * @param object|bool $data DB row containing fields returned by selectFields() or false
411 * @param string|int $from One of the following:
412 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
413 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
414 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
415 * the master DB using SELECT FOR UPDATE
417 public function loadFromRow( $data, $from ) {
418 $lc = LinkCache
::singleton();
419 $lc->clearLink( $this->mTitle
);
422 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
424 $this->mTitle
->loadFromRow( $data );
426 // Old-fashioned restrictions
427 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
429 $this->mId
= intval( $data->page_id
);
430 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
431 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
432 $this->mIsRedirect
= intval( $data->page_is_redirect
);
433 $this->mLatest
= intval( $data->page_latest
);
434 // T39225: $latest may no longer match the cached latest Revision object.
435 // Double-check the ID of any cached latest Revision object for consistency.
436 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
437 $this->mLastRevision
= null;
438 $this->mTimestamp
= '';
441 $lc->addBadLinkObj( $this->mTitle
);
443 $this->mTitle
->loadFromRow( false );
445 $this->clearCacheFields();
450 $this->mDataLoaded
= true;
451 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
455 * @return int Page ID
457 public function getId() {
458 if ( !$this->mDataLoaded
) {
459 $this->loadPageData();
465 * @return bool Whether or not the page exists in the database
467 public function exists() {
468 if ( !$this->mDataLoaded
) {
469 $this->loadPageData();
471 return $this->mId
> 0;
475 * Check if this page is something we're going to be showing
476 * some sort of sensible content for. If we return false, page
477 * views (plain action=view) will return an HTTP 404 response,
478 * so spiders and robots can know they're following a bad link.
482 public function hasViewableContent() {
483 return $this->mTitle
->isKnown();
487 * Tests if the article content represents a redirect
491 public function isRedirect() {
492 if ( !$this->mDataLoaded
) {
493 $this->loadPageData();
496 return (bool)$this->mIsRedirect
;
500 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
502 * Will use the revisions actual content model if the page exists,
503 * and the page's default if the page doesn't exist yet.
509 public function getContentModel() {
510 if ( $this->exists() ) {
511 $cache = ObjectCache
::getMainWANInstance();
513 return $cache->getWithSetCallback(
514 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
517 $rev = $this->getRevision();
519 // Look at the revision's actual content model
520 return $rev->getContentModel();
522 $title = $this->mTitle
->getPrefixedDBkey();
523 wfWarn( "Page $title exists but has no (visible) revisions!" );
524 return $this->mTitle
->getContentModel();
530 // use the default model for this page
531 return $this->mTitle
->getContentModel();
535 * Loads page_touched and returns a value indicating if it should be used
536 * @return bool True if this page exists and is not a redirect
538 public function checkTouched() {
539 if ( !$this->mDataLoaded
) {
540 $this->loadPageData();
542 return ( $this->mId
&& !$this->mIsRedirect
);
546 * Get the page_touched field
547 * @return string Containing GMT timestamp
549 public function getTouched() {
550 if ( !$this->mDataLoaded
) {
551 $this->loadPageData();
553 return $this->mTouched
;
557 * Get the page_links_updated field
558 * @return string|null Containing GMT timestamp
560 public function getLinksTimestamp() {
561 if ( !$this->mDataLoaded
) {
562 $this->loadPageData();
564 return $this->mLinksUpdated
;
568 * Get the page_latest field
569 * @return int The rev_id of current revision
571 public function getLatest() {
572 if ( !$this->mDataLoaded
) {
573 $this->loadPageData();
575 return (int)$this->mLatest
;
579 * Get the Revision object of the oldest revision
580 * @return Revision|null
582 public function getOldestRevision() {
583 // Try using the replica DB first, then try the master
584 $rev = $this->mTitle
->getFirstRevision();
586 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
592 * Loads everything except the text
593 * This isn't necessary for all uses, so it's only done if needed.
595 protected function loadLastEdit() {
596 if ( $this->mLastRevision
!== null ) {
597 return; // already loaded
600 $latest = $this->getLatest();
602 return; // page doesn't exist or is missing page_latest info
605 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
606 // T39225: if session S1 loads the page row FOR UPDATE, the result always
607 // includes the latest changes committed. This is true even within REPEATABLE-READ
608 // transactions, where S1 normally only sees changes committed before the first S1
609 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
610 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
611 // happened after the first S1 SELECT.
612 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
613 $flags = Revision
::READ_LOCKING
;
614 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
615 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
616 // Bug T93976: if page_latest was loaded from the master, fetch the
617 // revision from there as well, as it may not exist yet on a replica DB.
618 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
619 $flags = Revision
::READ_LATEST
;
620 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
622 $dbr = wfGetDB( DB_REPLICA
);
623 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
626 if ( $revision ) { // sanity
627 $this->setLastEdit( $revision );
632 * Set the latest revision
633 * @param Revision $revision
635 protected function setLastEdit( Revision
$revision ) {
636 $this->mLastRevision
= $revision;
637 $this->mTimestamp
= $revision->getTimestamp();
641 * Get the latest revision
642 * @return Revision|null
644 public function getRevision() {
645 $this->loadLastEdit();
646 if ( $this->mLastRevision
) {
647 return $this->mLastRevision
;
653 * Get the content of the current revision. No side-effects...
655 * @param int $audience One of:
656 * Revision::FOR_PUBLIC to be displayed to all users
657 * Revision::FOR_THIS_USER to be displayed to $wgUser
658 * Revision::RAW get the text regardless of permissions
659 * @param User $user User object to check for, only if FOR_THIS_USER is passed
660 * to the $audience parameter
661 * @return Content|null The content of the current revision
665 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
666 $this->loadLastEdit();
667 if ( $this->mLastRevision
) {
668 return $this->mLastRevision
->getContent( $audience, $user );
674 * @return string MW timestamp of last article revision
676 public function getTimestamp() {
677 // Check if the field has been filled by WikiPage::setTimestamp()
678 if ( !$this->mTimestamp
) {
679 $this->loadLastEdit();
682 return wfTimestamp( TS_MW
, $this->mTimestamp
);
686 * Set the page timestamp (use only to avoid DB queries)
687 * @param string $ts MW timestamp of last article revision
690 public function setTimestamp( $ts ) {
691 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
695 * @param int $audience One of:
696 * Revision::FOR_PUBLIC to be displayed to all users
697 * Revision::FOR_THIS_USER to be displayed to the given user
698 * Revision::RAW get the text regardless of permissions
699 * @param User $user User object to check for, only if FOR_THIS_USER is passed
700 * to the $audience parameter
701 * @return int User ID for the user that made the last article revision
703 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
704 $this->loadLastEdit();
705 if ( $this->mLastRevision
) {
706 return $this->mLastRevision
->getUser( $audience, $user );
713 * Get the User object of the user who created the page
714 * @param int $audience One of:
715 * Revision::FOR_PUBLIC to be displayed to all users
716 * Revision::FOR_THIS_USER to be displayed to the given user
717 * Revision::RAW get the text regardless of permissions
718 * @param User $user User object to check for, only if FOR_THIS_USER is passed
719 * to the $audience parameter
722 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
723 $revision = $this->getOldestRevision();
725 $userName = $revision->getUserText( $audience, $user );
726 return User
::newFromName( $userName, false );
733 * @param int $audience One of:
734 * Revision::FOR_PUBLIC to be displayed to all users
735 * Revision::FOR_THIS_USER to be displayed to the given user
736 * Revision::RAW get the text regardless of permissions
737 * @param User $user User object to check for, only if FOR_THIS_USER is passed
738 * to the $audience parameter
739 * @return string Username of the user that made the last article revision
741 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
742 $this->loadLastEdit();
743 if ( $this->mLastRevision
) {
744 return $this->mLastRevision
->getUserText( $audience, $user );
751 * @param int $audience One of:
752 * Revision::FOR_PUBLIC to be displayed to all users
753 * Revision::FOR_THIS_USER to be displayed to the given user
754 * Revision::RAW get the text regardless of permissions
755 * @param User $user User object to check for, only if FOR_THIS_USER is passed
756 * to the $audience parameter
757 * @return string Comment stored for the last article revision
759 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
760 $this->loadLastEdit();
761 if ( $this->mLastRevision
) {
762 return $this->mLastRevision
->getComment( $audience, $user );
769 * Returns true if last revision was marked as "minor edit"
771 * @return bool Minor edit indicator for the last article revision.
773 public function getMinorEdit() {
774 $this->loadLastEdit();
775 if ( $this->mLastRevision
) {
776 return $this->mLastRevision
->isMinor();
783 * Determine whether a page would be suitable for being counted as an
784 * article in the site_stats table based on the title & its content
786 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
787 * if false, the current database state will be used
790 public function isCountable( $editInfo = false ) {
791 global $wgArticleCountMethod;
793 if ( !$this->mTitle
->isContentPage() ) {
798 $content = $editInfo->pstContent
;
800 $content = $this->getContent();
803 if ( !$content ||
$content->isRedirect() ) {
809 if ( $wgArticleCountMethod === 'link' ) {
810 // nasty special case to avoid re-parsing to detect links
813 // ParserOutput::getLinks() is a 2D array of page links, so
814 // to be really correct we would need to recurse in the array
815 // but the main array should only have items in it if there are
817 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
819 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
820 [ 'pl_from' => $this->getId() ], __METHOD__
);
824 return $content->isCountable( $hasLinks );
828 * If this page is a redirect, get its target
830 * The target will be fetched from the redirect table if possible.
831 * If this page doesn't have an entry there, call insertRedirect()
832 * @return Title|null Title object, or null if this page is not a redirect
834 public function getRedirectTarget() {
835 if ( !$this->mTitle
->isRedirect() ) {
839 if ( $this->mRedirectTarget
!== null ) {
840 return $this->mRedirectTarget
;
843 // Query the redirect table
844 $dbr = wfGetDB( DB_REPLICA
);
845 $row = $dbr->selectRow( 'redirect',
846 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
847 [ 'rd_from' => $this->getId() ],
851 // rd_fragment and rd_interwiki were added later, populate them if empty
852 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
853 $this->mRedirectTarget
= Title
::makeTitle(
854 $row->rd_namespace
, $row->rd_title
,
855 $row->rd_fragment
, $row->rd_interwiki
857 return $this->mRedirectTarget
;
860 // This page doesn't have an entry in the redirect table
861 $this->mRedirectTarget
= $this->insertRedirect();
862 return $this->mRedirectTarget
;
866 * Insert an entry for this page into the redirect table if the content is a redirect
868 * The database update will be deferred via DeferredUpdates
870 * Don't call this function directly unless you know what you're doing.
871 * @return Title|null Title object or null if not a redirect
873 public function insertRedirect() {
874 $content = $this->getContent();
875 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
880 // Update the DB post-send if the page has not cached since now
881 $latest = $this->getLatest();
882 DeferredUpdates
::addCallableUpdate(
883 function () use ( $retval, $latest ) {
884 $this->insertRedirectEntry( $retval, $latest );
886 DeferredUpdates
::POSTSEND
,
894 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
895 * @param Title $rt Redirect target
896 * @param int|null $oldLatest Prior page_latest for check and set
898 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
899 $dbw = wfGetDB( DB_MASTER
);
900 $dbw->startAtomic( __METHOD__
);
902 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
906 'rd_from' => $this->getId(),
907 'rd_namespace' => $rt->getNamespace(),
908 'rd_title' => $rt->getDBkey(),
909 'rd_fragment' => $rt->getFragment(),
910 'rd_interwiki' => $rt->getInterwiki(),
914 'rd_namespace' => $rt->getNamespace(),
915 'rd_title' => $rt->getDBkey(),
916 'rd_fragment' => $rt->getFragment(),
917 'rd_interwiki' => $rt->getInterwiki(),
923 $dbw->endAtomic( __METHOD__
);
927 * Get the Title object or URL this page redirects to
929 * @return bool|Title|string False, Title of in-wiki target, or string with URL
931 public function followRedirect() {
932 return $this->getRedirectURL( $this->getRedirectTarget() );
936 * Get the Title object or URL to use for a redirect. We use Title
937 * objects for same-wiki, non-special redirects and URLs for everything
939 * @param Title $rt Redirect target
940 * @return bool|Title|string False, Title object of local target, or string with URL
942 public function getRedirectURL( $rt ) {
947 if ( $rt->isExternal() ) {
948 if ( $rt->isLocal() ) {
949 // Offsite wikis need an HTTP redirect.
950 // This can be hard to reverse and may produce loops,
951 // so they may be disabled in the site configuration.
952 $source = $this->mTitle
->getFullURL( 'redirect=no' );
953 return $rt->getFullURL( [ 'rdfrom' => $source ] );
955 // External pages without "local" bit set are not valid
961 if ( $rt->isSpecialPage() ) {
962 // Gotta handle redirects to special pages differently:
963 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
964 // Some pages are not valid targets.
965 if ( $rt->isValidRedirectTarget() ) {
966 return $rt->getFullURL();
976 * Get a list of users who have edited this article, not including the user who made
977 * the most recent revision, which you can get from $article->getUser() if you want it
978 * @return UserArrayFromResult
980 public function getContributors() {
981 // @todo FIXME: This is expensive; cache this info somewhere.
983 $dbr = wfGetDB( DB_REPLICA
);
985 $tables = [ 'revision', 'user' ];
988 'user_id' => 'rev_user',
989 'user_name' => 'rev_user_text',
990 'user_real_name' => 'MIN(user_real_name)',
991 'timestamp' => 'MAX(rev_timestamp)',
994 $conds = [ 'rev_page' => $this->getId() ];
996 // The user who made the top revision gets credited as "this page was last edited by
997 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
998 $user = $this->getUser();
1000 $conds[] = "rev_user != $user";
1002 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1006 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1009 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1013 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1014 'ORDER BY' => 'timestamp DESC',
1017 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1018 return new UserArrayFromResult( $res );
1022 * Should the parser cache be used?
1024 * @param ParserOptions $parserOptions ParserOptions to check
1028 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1029 return $parserOptions->getStubThreshold() == 0
1031 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1032 && $this->getContentHandler()->isParserCacheSupported();
1036 * Get a ParserOutput for the given ParserOptions and revision ID.
1038 * The parser cache will be used if possible. Cache misses that result
1039 * in parser runs are debounced with PoolCounter.
1042 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1043 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1044 * get the current revision (default value)
1045 * @param bool $forceParse Force reindexing, regardless of cache settings
1046 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1048 public function getParserOutput(
1049 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1052 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1054 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1055 throw new InvalidArgumentException(
1056 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1060 wfDebug( __METHOD__
.
1061 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1062 if ( $parserOptions->getStubThreshold() ) {
1063 wfIncrStats( 'pcache.miss.stub' );
1066 if ( $useParserCache ) {
1067 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1068 if ( $parserOutput !== false ) {
1069 return $parserOutput;
1073 if ( $oldid === null ||
$oldid === 0 ) {
1074 $oldid = $this->getLatest();
1077 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1080 return $pool->getParserOutput();
1084 * Do standard deferred updates after page view (existing or missing page)
1085 * @param User $user The relevant user
1086 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1088 public function doViewUpdates( User
$user, $oldid = 0 ) {
1089 if ( wfReadOnly() ) {
1093 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1094 // Update newtalk / watchlist notification status
1096 $user->clearNotification( $this->mTitle
, $oldid );
1097 } catch ( DBError
$e ) {
1098 // Avoid outage if the master is not reachable
1099 MWExceptionHandler
::logException( $e );
1104 * Perform the actions of a page purging
1106 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1107 * controlled how much purging was done.
1109 public function doPurge() {
1110 // Avoid PHP 7.1 warning of passing $this by reference
1113 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1117 $this->mTitle
->invalidateCache();
1120 HTMLFileCache
::clearFileCache( $this->getTitle() );
1121 // Send purge after above page_touched update was committed
1122 DeferredUpdates
::addUpdate(
1123 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1124 DeferredUpdates
::PRESEND
1127 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1128 $messageCache = MessageCache
::singleton();
1129 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1136 * Get the last time a user explicitly purged the page via action=purge
1138 * @return string|bool TS_MW timestamp or false
1140 * @deprecated since 1.29. It will always return false.
1142 public function getLastPurgeTimestamp() {
1143 wfDeprecated( __METHOD__
, '1.29' );
1148 * Insert a new empty page record for this article.
1149 * This *must* be followed up by creating a revision
1150 * and running $this->updateRevisionOn( ... );
1151 * or else the record will be left in a funky state.
1152 * Best if all done inside a transaction.
1154 * @param IDatabase $dbw
1155 * @param int|null $pageId Custom page ID that will be used for the insert statement
1157 * @return bool|int The newly created page_id key; false if the row was not
1158 * inserted, e.g. because the title already existed or because the specified
1159 * page ID is already in use.
1161 public function insertOn( $dbw, $pageId = null ) {
1162 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1166 'page_namespace' => $this->mTitle
->getNamespace(),
1167 'page_title' => $this->mTitle
->getDBkey(),
1168 'page_restrictions' => '',
1169 'page_is_redirect' => 0, // Will set this shortly...
1171 'page_random' => wfRandom(),
1172 'page_touched' => $dbw->timestamp(),
1173 'page_latest' => 0, // Fill this in shortly...
1174 'page_len' => 0, // Fill this in shortly...
1175 ] +
$pageIdForInsert,
1180 if ( $dbw->affectedRows() > 0 ) {
1181 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1182 $this->mId
= $newid;
1183 $this->mTitle
->resetArticleID( $newid );
1187 return false; // nothing changed
1192 * Update the page record to point to a newly saved revision.
1194 * @param IDatabase $dbw
1195 * @param Revision $revision For ID number, and text used to set
1196 * length and redirect status fields
1197 * @param int $lastRevision If given, will not overwrite the page field
1198 * when different from the currently set value.
1199 * Giving 0 indicates the new page flag should be set on.
1200 * @param bool $lastRevIsRedirect If given, will optimize adding and
1201 * removing rows in redirect table.
1202 * @return bool Success; false if the page row was missing or page_latest changed
1204 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1205 $lastRevIsRedirect = null
1207 global $wgContentHandlerUseDB;
1209 // Assertion to try to catch T92046
1210 if ( (int)$revision->getId() === 0 ) {
1211 throw new InvalidArgumentException(
1212 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1216 $content = $revision->getContent();
1217 $len = $content ?
$content->getSize() : 0;
1218 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1220 $conditions = [ 'page_id' => $this->getId() ];
1222 if ( !is_null( $lastRevision ) ) {
1223 // An extra check against threads stepping on each other
1224 $conditions['page_latest'] = $lastRevision;
1228 'page_latest' => $revision->getId(),
1229 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1230 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1231 'page_is_redirect' => $rt !== null ?
1 : 0,
1235 if ( $wgContentHandlerUseDB ) {
1236 $row['page_content_model'] = $revision->getContentModel();
1239 $dbw->update( 'page',
1244 $result = $dbw->affectedRows() > 0;
1246 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1247 $this->setLastEdit( $revision );
1248 $this->mLatest
= $revision->getId();
1249 $this->mIsRedirect
= (bool)$rt;
1250 // Update the LinkCache.
1251 LinkCache
::singleton()->addGoodLinkObj(
1257 $revision->getContentModel()
1265 * Add row to the redirect table if this is a redirect, remove otherwise.
1267 * @param IDatabase $dbw
1268 * @param Title $redirectTitle Title object pointing to the redirect target,
1269 * or NULL if this is not a redirect
1270 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1271 * removing rows in redirect table.
1272 * @return bool True on success, false on failure
1275 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1276 // Always update redirects (target link might have changed)
1277 // Update/Insert if we don't know if the last revision was a redirect or not
1278 // Delete if changing from redirect to non-redirect
1279 $isRedirect = !is_null( $redirectTitle );
1281 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1285 if ( $isRedirect ) {
1286 $this->insertRedirectEntry( $redirectTitle );
1288 // This is not a redirect, remove row from redirect table
1289 $where = [ 'rd_from' => $this->getId() ];
1290 $dbw->delete( 'redirect', $where, __METHOD__
);
1293 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1294 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1297 return ( $dbw->affectedRows() != 0 );
1301 * If the given revision is newer than the currently set page_latest,
1302 * update the page record. Otherwise, do nothing.
1304 * @deprecated since 1.24, use updateRevisionOn instead
1306 * @param IDatabase $dbw
1307 * @param Revision $revision
1310 public function updateIfNewerOn( $dbw, $revision ) {
1311 $row = $dbw->selectRow(
1312 [ 'revision', 'page' ],
1313 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1315 'page_id' => $this->getId(),
1316 'page_latest=rev_id' ],
1320 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1323 $prev = $row->rev_id
;
1324 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1326 // No or missing previous revision; mark the page as new
1328 $lastRevIsRedirect = null;
1331 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1337 * Get the content that needs to be saved in order to undo all revisions
1338 * between $undo and $undoafter. Revisions must belong to the same page,
1339 * must exist and must not be deleted
1340 * @param Revision $undo
1341 * @param Revision $undoafter Must be an earlier revision than $undo
1342 * @return Content|bool Content on success, false on failure
1344 * Before we had the Content object, this was done in getUndoText
1346 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1347 $handler = $undo->getContentHandler();
1348 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1352 * Returns true if this page's content model supports sections.
1356 * @todo The skin should check this and not offer section functionality if
1357 * sections are not supported.
1358 * @todo The EditPage should check this and not offer section functionality
1359 * if sections are not supported.
1361 public function supportsSections() {
1362 return $this->getContentHandler()->supportsSections();
1366 * @param string|int|null|bool $sectionId Section identifier as a number or string
1367 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1368 * or 'new' for a new section.
1369 * @param Content $sectionContent New content of the section.
1370 * @param string $sectionTitle New section's subject, only if $section is "new".
1371 * @param string $edittime Revision timestamp or null to use the current revision.
1373 * @throws MWException
1374 * @return Content|null New complete article content, or null if error.
1377 * @deprecated since 1.24, use replaceSectionAtRev instead
1379 public function replaceSectionContent(
1380 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1383 if ( $edittime && $sectionId !== 'new' ) {
1384 $dbr = wfGetDB( DB_REPLICA
);
1385 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1386 // Try the master if this thread may have just added it.
1387 // This could be abstracted into a Revision method, but we don't want
1388 // to encourage loading of revisions by timestamp.
1390 && wfGetLB()->getServerCount() > 1
1391 && wfGetLB()->hasOrMadeRecentMasterChanges()
1393 $dbw = wfGetDB( DB_MASTER
);
1394 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1397 $baseRevId = $rev->getId();
1401 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1405 * @param string|int|null|bool $sectionId Section identifier as a number or string
1406 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1407 * or 'new' for a new section.
1408 * @param Content $sectionContent New content of the section.
1409 * @param string $sectionTitle New section's subject, only if $section is "new".
1410 * @param int|null $baseRevId
1412 * @throws MWException
1413 * @return Content|null New complete article content, or null if error.
1417 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1418 $sectionTitle = '', $baseRevId = null
1420 if ( strval( $sectionId ) === '' ) {
1421 // Whole-page edit; let the whole text through
1422 $newContent = $sectionContent;
1424 if ( !$this->supportsSections() ) {
1425 throw new MWException( "sections not supported for content model " .
1426 $this->getContentHandler()->getModelID() );
1429 // T32711: always use current version when adding a new section
1430 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1431 $oldContent = $this->getContent();
1433 $rev = Revision
::newFromId( $baseRevId );
1435 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1436 $this->getId() . "; section: $sectionId)\n" );
1440 $oldContent = $rev->getContent();
1443 if ( !$oldContent ) {
1444 wfDebug( __METHOD__
. ": no page text\n" );
1448 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1455 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1457 * @return int Updated $flags
1459 public function checkFlags( $flags ) {
1460 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1461 if ( $this->exists() ) {
1462 $flags |
= EDIT_UPDATE
;
1472 * Change an existing article or create a new article. Updates RC and all necessary caches,
1473 * optionally via the deferred update array.
1475 * @param Content $content New content
1476 * @param string $summary Edit summary
1477 * @param int $flags Bitfield:
1479 * Article is known or assumed to be non-existent, create a new one
1481 * Article is known or assumed to be pre-existing, update it
1483 * Mark this edit minor, if the user is allowed to do so
1485 * Do not log the change in recentchanges
1487 * Mark the edit a "bot" edit regardless of user rights
1489 * Fill in blank summaries with generated text where possible
1491 * Signal that the page retrieve/save cycle happened entirely in this request.
1493 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1494 * article will be detected. If EDIT_UPDATE is specified and the article
1495 * doesn't exist, the function will return an edit-gone-missing error. If
1496 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1497 * error will be returned. These two conditions are also possible with
1498 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1500 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1501 * This is not the parent revision ID, rather the revision ID for older
1502 * content used as the source for a rollback, for example.
1503 * @param User $user The user doing the edit
1504 * @param string $serialFormat Format for storing the content in the
1506 * @param array|null $tags Change tags to apply to this edit
1507 * Callers are responsible for permission checks
1508 * (with ChangeTags::canAddTagsAccompanyingChange)
1509 * @param Int $undidRevId Id of revision that was undone or 0
1511 * @throws MWException
1512 * @return Status Possible errors:
1513 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1514 * set the fatal flag of $status.
1515 * edit-gone-missing: In update mode, but the article didn't exist.
1516 * edit-conflict: In update mode, the article changed unexpectedly.
1517 * edit-no-change: Warning that the text was the same as before.
1518 * edit-already-exists: In creation mode, but the article already exists.
1520 * Extensions may define additional errors.
1522 * $return->value will contain an associative array with members as follows:
1523 * new: Boolean indicating if the function attempted to create a new article.
1524 * revision: The revision object for the inserted revision, or null.
1527 * @throws MWException
1529 public function doEditContent(
1530 Content
$content, $summary, $flags = 0, $baseRevId = false,
1531 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1533 global $wgUser, $wgUseAutomaticEditSummaries;
1535 // Old default parameter for $tags was null
1536 if ( $tags === null ) {
1540 // Low-level sanity check
1541 if ( $this->mTitle
->getText() === '' ) {
1542 throw new MWException( 'Something is trying to edit an article with an empty title' );
1544 // Make sure the given content type is allowed for this page
1545 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1546 return Status
::newFatal( 'content-not-allowed-here',
1547 ContentHandler
::getLocalizedName( $content->getModel() ),
1548 $this->mTitle
->getPrefixedText()
1552 // Load the data from the master database if needed.
1553 // The caller may already loaded it from the master or even loaded it using
1554 // SELECT FOR UPDATE, so do not override that using clear().
1555 $this->loadPageData( 'fromdbmaster' );
1557 $user = $user ?
: $wgUser;
1558 $flags = $this->checkFlags( $flags );
1560 // Avoid PHP 7.1 warning of passing $this by reference
1563 // Trigger pre-save hook (using provided edit summary)
1564 $hookStatus = Status
::newGood( [] );
1565 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1566 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1567 // Check if the hook rejected the attempted save
1568 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1569 if ( $hookStatus->isOK() ) {
1570 // Hook returned false but didn't call fatal(); use generic message
1571 $hookStatus->fatal( 'edit-hook-aborted' );
1577 $old_revision = $this->getRevision(); // current revision
1578 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1580 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1581 $tags[] = 'mw-contentmodelchange';
1584 // Provide autosummaries if one is not provided and autosummaries are enabled
1585 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1586 $handler = $content->getContentHandler();
1587 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1590 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1591 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1597 // Get the pre-save transform content and final parser output
1598 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1599 $pstContent = $editInfo->pstContent
; // Content object
1601 'bot' => ( $flags & EDIT_FORCE_BOT
),
1602 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1603 'serialized' => $pstContent->serialize( $serialFormat ),
1604 'serialFormat' => $serialFormat,
1605 'baseRevId' => $baseRevId,
1606 'oldRevision' => $old_revision,
1607 'oldContent' => $old_content,
1608 'oldId' => $this->getLatest(),
1609 'oldIsRedirect' => $this->isRedirect(),
1610 'oldCountable' => $this->isCountable(),
1611 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1612 'undidRevId' => $undidRevId
1615 // Actually create the revision and create/update the page
1616 if ( $flags & EDIT_UPDATE
) {
1617 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1619 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1622 // Promote user to any groups they meet the criteria for
1623 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1624 $user->addAutopromoteOnceGroups( 'onEdit' );
1625 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1632 * @param Content $content Pre-save transform content
1635 * @param string $summary
1636 * @param array $meta
1638 * @throws DBUnexpectedError
1640 * @throws FatalError
1641 * @throws MWException
1643 private function doModify(
1644 Content
$content, $flags, User
$user, $summary, array $meta
1646 global $wgUseRCPatrol;
1648 // Update article, but only if changed.
1649 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1651 // Convenience variables
1652 $now = wfTimestampNow();
1653 $oldid = $meta['oldId'];
1654 /** @var Content|null $oldContent */
1655 $oldContent = $meta['oldContent'];
1656 $newsize = $content->getSize();
1659 // Article gone missing
1660 $status->fatal( 'edit-gone-missing' );
1663 } elseif ( !$oldContent ) {
1664 // Sanity check for T39225
1665 throw new MWException( "Could not find text for current revision {$oldid}." );
1668 // @TODO: pass content object?!
1669 $revision = new Revision( [
1670 'page' => $this->getId(),
1671 'title' => $this->mTitle
, // for determining the default content model
1672 'comment' => $summary,
1673 'minor_edit' => $meta['minor'],
1674 'text' => $meta['serialized'],
1676 'parent_id' => $oldid,
1677 'user' => $user->getId(),
1678 'user_text' => $user->getName(),
1679 'timestamp' => $now,
1680 'content_model' => $content->getModel(),
1681 'content_format' => $meta['serialFormat'],
1684 $changed = !$content->equals( $oldContent );
1686 $dbw = wfGetDB( DB_MASTER
);
1689 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1690 $status->merge( $prepStatus );
1691 if ( !$status->isOK() ) {
1695 $dbw->startAtomic( __METHOD__
);
1696 // Get the latest page_latest value while locking it.
1697 // Do a CAS style check to see if it's the same as when this method
1698 // started. If it changed then bail out before touching the DB.
1699 $latestNow = $this->lockAndGetLatest();
1700 if ( $latestNow != $oldid ) {
1701 $dbw->endAtomic( __METHOD__
);
1702 // Page updated or deleted in the mean time
1703 $status->fatal( 'edit-conflict' );
1708 // At this point we are now comitted to returning an OK
1709 // status unless some DB query error or other exception comes up.
1710 // This way callers don't have to call rollback() if $status is bad
1711 // unless they actually try to catch exceptions (which is rare).
1713 // Save the revision text
1714 $revisionId = $revision->insertOn( $dbw );
1715 // Update page_latest and friends to reflect the new revision
1716 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1717 throw new MWException( "Failed to update page row to use new revision." );
1720 Hooks
::run( 'NewRevisionFromEditComplete',
1721 [ $this, $revision, $meta['baseRevId'], $user ] );
1723 // Update recentchanges
1724 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1725 // Mark as patrolled if the user can do so
1726 $patrolled = $wgUseRCPatrol && !count(
1727 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1728 // Add RC row to the DB
1729 RecentChange
::notifyEdit(
1732 $revision->isMinor(),
1736 $this->getTimestamp(),
1739 $oldContent ?
$oldContent->getSize() : 0,
1747 $user->incEditCount();
1749 $dbw->endAtomic( __METHOD__
);
1750 $this->mTimestamp
= $now;
1752 // T34948: revision ID must be set to page {{REVISIONID}} and
1753 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1754 $revision->setId( $this->getLatest() );
1755 $revision->setUserIdAndName(
1756 $this->getUser( Revision
::RAW
),
1757 $this->getUserText( Revision
::RAW
)
1762 // Return the new revision to the caller
1763 $status->value
['revision'] = $revision;
1765 $status->warning( 'edit-no-change' );
1766 // Update page_touched as updateRevisionOn() was not called.
1767 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1768 $this->mTitle
->invalidateCache( $now );
1771 // Do secondary updates once the main changes have been committed...
1772 DeferredUpdates
::addUpdate(
1773 new AtomicSectionUpdate(
1777 $revision, &$user, $content, $summary, &$flags,
1778 $changed, $meta, &$status
1780 // Update links tables, site stats, etc.
1781 $this->doEditUpdates(
1785 'changed' => $changed,
1786 'oldcountable' => $meta['oldCountable'],
1787 'oldrevision' => $meta['oldRevision']
1790 // Avoid PHP 7.1 warning of passing $this by reference
1792 // Trigger post-save hook
1793 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1794 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1795 $meta['undidRevId'] ];
1796 Hooks
::run( 'PageContentSaveComplete', $params );
1799 DeferredUpdates
::PRESEND
1806 * @param Content $content Pre-save transform content
1809 * @param string $summary
1810 * @param array $meta
1812 * @throws DBUnexpectedError
1814 * @throws FatalError
1815 * @throws MWException
1817 private function doCreate(
1818 Content
$content, $flags, User
$user, $summary, array $meta
1820 global $wgUseRCPatrol, $wgUseNPPatrol;
1822 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1824 $now = wfTimestampNow();
1825 $newsize = $content->getSize();
1826 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1827 $status->merge( $prepStatus );
1828 if ( !$status->isOK() ) {
1832 $dbw = wfGetDB( DB_MASTER
);
1833 $dbw->startAtomic( __METHOD__
);
1835 // Add the page record unless one already exists for the title
1836 $newid = $this->insertOn( $dbw );
1837 if ( $newid === false ) {
1838 $dbw->endAtomic( __METHOD__
); // nothing inserted
1839 $status->fatal( 'edit-already-exists' );
1841 return $status; // nothing done
1844 // At this point we are now comitted to returning an OK
1845 // status unless some DB query error or other exception comes up.
1846 // This way callers don't have to call rollback() if $status is bad
1847 // unless they actually try to catch exceptions (which is rare).
1849 // @TODO: pass content object?!
1850 $revision = new Revision( [
1852 'title' => $this->mTitle
, // for determining the default content model
1853 'comment' => $summary,
1854 'minor_edit' => $meta['minor'],
1855 'text' => $meta['serialized'],
1857 'user' => $user->getId(),
1858 'user_text' => $user->getName(),
1859 'timestamp' => $now,
1860 'content_model' => $content->getModel(),
1861 'content_format' => $meta['serialFormat'],
1864 // Save the revision text...
1865 $revisionId = $revision->insertOn( $dbw );
1866 // Update the page record with revision data
1867 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1868 throw new MWException( "Failed to update page row to use new revision." );
1871 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1873 // Update recentchanges
1874 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1875 // Mark as patrolled if the user can do so
1876 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1877 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1878 // Add RC row to the DB
1879 RecentChange
::notifyNew(
1882 $revision->isMinor(),
1894 $user->incEditCount();
1896 $dbw->endAtomic( __METHOD__
);
1897 $this->mTimestamp
= $now;
1899 // Return the new revision to the caller
1900 $status->value
['revision'] = $revision;
1902 // Do secondary updates once the main changes have been committed...
1903 DeferredUpdates
::addUpdate(
1904 new AtomicSectionUpdate(
1908 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1910 // Update links, etc.
1911 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1912 // Avoid PHP 7.1 warning of passing $this by reference
1914 // Trigger post-create hook
1915 $params = [ &$wikiPage, &$user, $content, $summary,
1916 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1917 Hooks
::run( 'PageContentInsertComplete', $params );
1918 // Trigger post-save hook
1919 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1920 Hooks
::run( 'PageContentSaveComplete', $params );
1923 DeferredUpdates
::PRESEND
1930 * Get parser options suitable for rendering the primary article wikitext
1932 * @see ContentHandler::makeParserOptions
1934 * @param IContextSource|User|string $context One of the following:
1935 * - IContextSource: Use the User and the Language of the provided
1937 * - User: Use the provided User object and $wgLang for the language,
1938 * so use an IContextSource object if possible.
1939 * - 'canonical': Canonical options (anonymous user with default
1940 * preferences and content language).
1941 * @return ParserOptions
1943 public function makeParserOptions( $context ) {
1944 $options = $this->getContentHandler()->makeParserOptions( $context );
1946 if ( $this->getTitle()->isConversionTable() ) {
1947 // @todo ConversionTable should become a separate content model, so
1948 // we don't need special cases like this one.
1949 $options->disableContentConversion();
1956 * Prepare content which is about to be saved.
1958 * Prior to 1.30, this returned a stdClass object with the same class
1961 * @param Content $content
1962 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1963 * revision ID is also accepted, but this is deprecated.
1964 * @param User|null $user
1965 * @param string|null $serialFormat
1966 * @param bool $useCache Check shared prepared edit cache
1968 * @return PreparedEdit
1972 public function prepareContentForEdit(
1973 Content
$content, $revision = null, User
$user = null,
1974 $serialFormat = null, $useCache = true
1976 global $wgContLang, $wgUser, $wgAjaxEditStash;
1978 if ( is_object( $revision ) ) {
1979 $revid = $revision->getId();
1982 // This code path is deprecated, and nothing is known to
1983 // use it, so performance here shouldn't be a worry.
1984 if ( $revid !== null ) {
1985 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
1991 $user = is_null( $user ) ?
$wgUser : $user;
1992 // XXX: check $user->getId() here???
1994 // Use a sane default for $serialFormat, see T59026
1995 if ( $serialFormat === null ) {
1996 $serialFormat = $content->getContentHandler()->getDefaultFormat();
1999 if ( $this->mPreparedEdit
2000 && isset( $this->mPreparedEdit
->newContent
)
2001 && $this->mPreparedEdit
->newContent
->equals( $content )
2002 && $this->mPreparedEdit
->revid
== $revid
2003 && $this->mPreparedEdit
->format
== $serialFormat
2004 // XXX: also check $user here?
2007 return $this->mPreparedEdit
;
2010 // The edit may have already been prepared via api.php?action=stashedit
2011 $cachedEdit = $useCache && $wgAjaxEditStash
2012 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2015 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2016 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2018 $edit = new PreparedEdit();
2019 if ( $cachedEdit ) {
2020 $edit->timestamp
= $cachedEdit->timestamp
;
2022 $edit->timestamp
= wfTimestampNow();
2024 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2025 $edit->revid
= $revid;
2027 if ( $cachedEdit ) {
2028 $edit->pstContent
= $cachedEdit->pstContent
;
2030 $edit->pstContent
= $content
2031 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2035 $edit->format
= $serialFormat;
2036 $edit->popts
= $this->makeParserOptions( 'canonical' );
2037 if ( $cachedEdit ) {
2038 $edit->output
= $cachedEdit->output
;
2041 // We get here if vary-revision is set. This means that this page references
2042 // itself (such as via self-transclusion). In this case, we need to make sure
2043 // that any such self-references refer to the newly-saved revision, and not
2044 // to the previous one, which could otherwise happen due to replica DB lag.
2045 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2046 $edit->popts
->setCurrentRevisionCallback(
2047 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2048 if ( $title->equals( $revision->getTitle() ) ) {
2051 return call_user_func( $oldCallback, $title, $parser );
2056 // Try to avoid a second parse if {{REVISIONID}} is used
2057 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2058 ? DB_MASTER
// use the best possible guess
2059 : DB_REPLICA
; // T154554
2061 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2062 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2070 $edit->output
= $edit->pstContent
2071 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2075 $edit->newContent
= $content;
2076 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2078 // NOTE: B/C for hooks! don't use these fields!
2079 $edit->newText
= $edit->newContent
2080 ? ContentHandler
::getContentText( $edit->newContent
)
2082 $edit->oldText
= $edit->oldContent
2083 ? ContentHandler
::getContentText( $edit->oldContent
)
2085 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2087 if ( $edit->output
) {
2088 $edit->output
->setCacheTime( wfTimestampNow() );
2091 // Process cache the result
2092 $this->mPreparedEdit
= $edit;
2098 * Do standard deferred updates after page edit.
2099 * Update links tables, site stats, search index and message cache.
2100 * Purges pages that include this page if the text was changed here.
2101 * Every 100th edit, prune the recent changes table.
2103 * @param Revision $revision
2104 * @param User $user User object that did the revision
2105 * @param array $options Array of options, following indexes are used:
2106 * - changed: bool, whether the revision changed the content (default true)
2107 * - created: bool, whether the revision created the page (default false)
2108 * - moved: bool, whether the page was moved (default false)
2109 * - restored: bool, whether the page was undeleted (default false)
2110 * - oldrevision: Revision object for the pre-update revision (default null)
2111 * - oldcountable: bool, null, or string 'no-change' (default null):
2112 * - bool: whether the page was counted as an article before that
2113 * revision, only used in changed is true and created is false
2114 * - null: if created is false, don't update the article count; if created
2115 * is true, do update the article count
2116 * - 'no-change': don't update the article count, ever
2118 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2119 global $wgRCWatchCategoryMembership;
2125 'restored' => false,
2126 'oldrevision' => null,
2127 'oldcountable' => null
2129 $content = $revision->getContent();
2131 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2133 // See if the parser output before $revision was inserted is still valid
2135 if ( !$this->mPreparedEdit
) {
2136 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2137 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2138 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2139 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2140 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2142 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2143 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2144 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2146 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2147 $editInfo = $this->mPreparedEdit
;
2151 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2152 // $text is usually already pre-save transformed once. Avoid using the edit stash
2153 // as any prepared content from there or in doEditContent() was already rejected.
2154 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2157 // Save it to the parser cache.
2158 // Make sure the cache time matches page_touched to avoid double parsing.
2159 ParserCache
::singleton()->save(
2160 $editInfo->output
, $this, $editInfo->popts
,
2161 $revision->getTimestamp(), $editInfo->revid
2164 // Update the links tables and other secondary data
2166 $recursive = $options['changed']; // T52785
2167 $updates = $content->getSecondaryDataUpdates(
2168 $this->getTitle(), null, $recursive, $editInfo->output
2170 foreach ( $updates as $update ) {
2171 if ( $update instanceof LinksUpdate
) {
2172 $update->setRevision( $revision );
2173 $update->setTriggeringUser( $user );
2175 DeferredUpdates
::addUpdate( $update );
2177 if ( $wgRCWatchCategoryMembership
2178 && $this->getContentHandler()->supportsCategories() === true
2179 && ( $options['changed'] ||
$options['created'] )
2180 && !$options['restored']
2182 // Note: jobs are pushed after deferred updates, so the job should be able to see
2183 // the recent change entry (also done via deferred updates) and carry over any
2184 // bot/deletion/IP flags, ect.
2185 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2188 'pageId' => $this->getId(),
2189 'revTimestamp' => $revision->getTimestamp()
2195 // Avoid PHP 7.1 warning of passing $this by reference
2198 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2200 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2201 // Flush old entries from the `recentchanges` table
2202 if ( mt_rand( 0, 9 ) == 0 ) {
2203 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2207 if ( !$this->exists() ) {
2211 $id = $this->getId();
2212 $title = $this->mTitle
->getPrefixedDBkey();
2213 $shortTitle = $this->mTitle
->getDBkey();
2215 if ( $options['oldcountable'] === 'no-change' ||
2216 ( !$options['changed'] && !$options['moved'] )
2219 } elseif ( $options['created'] ) {
2220 $good = (int)$this->isCountable( $editInfo );
2221 } elseif ( $options['oldcountable'] !== null ) {
2222 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2226 $edits = $options['changed'] ?
1 : 0;
2227 $total = $options['created'] ?
1 : 0;
2229 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2230 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2232 // If this is another user's talk page, update newtalk.
2233 // Don't do this if $options['changed'] = false (null-edits) nor if
2234 // it's a minor edit and the user doesn't want notifications for those.
2235 if ( $options['changed']
2236 && $this->mTitle
->getNamespace() == NS_USER_TALK
2237 && $shortTitle != $user->getTitleKey()
2238 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2240 $recipient = User
::newFromName( $shortTitle, false );
2241 if ( !$recipient ) {
2242 wfDebug( __METHOD__
. ": invalid username\n" );
2244 // Avoid PHP 7.1 warning of passing $this by reference
2247 // Allow extensions to prevent user notification
2248 // when a new message is added to their talk page
2249 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2250 if ( User
::isIP( $shortTitle ) ) {
2251 // An anonymous user
2252 $recipient->setNewtalk( true, $revision );
2253 } elseif ( $recipient->isLoggedIn() ) {
2254 $recipient->setNewtalk( true, $revision );
2256 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2262 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2263 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2266 if ( $options['created'] ) {
2267 self
::onArticleCreate( $this->mTitle
);
2268 } elseif ( $options['changed'] ) { // T52785
2269 self
::onArticleEdit( $this->mTitle
, $revision );
2272 ResourceLoaderWikiModule
::invalidateModuleCache(
2273 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2278 * Update the article's restriction field, and leave a log entry.
2279 * This works for protection both existing and non-existing pages.
2281 * @param array $limit Set of restriction keys
2282 * @param array $expiry Per restriction type expiration
2283 * @param int &$cascade Set to false if cascading protection isn't allowed.
2284 * @param string $reason
2285 * @param User $user The user updating the restrictions
2286 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2287 * ($user should be able to add the specified tags before this is called)
2288 * @return Status Status object; if action is taken, $status->value is the log_id of the
2289 * protection log entry.
2291 public function doUpdateRestrictions( array $limit, array $expiry,
2292 &$cascade, $reason, User
$user, $tags = null
2294 global $wgCascadingRestrictionLevels;
2296 if ( wfReadOnly() ) {
2297 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2300 $this->loadPageData( 'fromdbmaster' );
2301 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2302 $id = $this->getId();
2308 // Take this opportunity to purge out expired restrictions
2309 Title
::purgeExpiredRestrictions();
2311 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2312 // we expect a single selection, but the schema allows otherwise.
2313 $isProtected = false;
2317 $dbw = wfGetDB( DB_MASTER
);
2319 foreach ( $restrictionTypes as $action ) {
2320 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2321 $expiry[$action] = 'infinity';
2323 if ( !isset( $limit[$action] ) ) {
2324 $limit[$action] = '';
2325 } elseif ( $limit[$action] != '' ) {
2329 // Get current restrictions on $action
2330 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2331 if ( $current != '' ) {
2332 $isProtected = true;
2335 if ( $limit[$action] != $current ) {
2337 } elseif ( $limit[$action] != '' ) {
2338 // Only check expiry change if the action is actually being
2339 // protected, since expiry does nothing on an not-protected
2341 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2347 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2351 // If nothing has changed, do nothing
2353 return Status
::newGood();
2356 if ( !$protect ) { // No protection at all means unprotection
2357 $revCommentMsg = 'unprotectedarticle-comment';
2358 $logAction = 'unprotect';
2359 } elseif ( $isProtected ) {
2360 $revCommentMsg = 'modifiedarticleprotection-comment';
2361 $logAction = 'modify';
2363 $revCommentMsg = 'protectedarticle-comment';
2364 $logAction = 'protect';
2367 $logRelationsValues = [];
2368 $logRelationsField = null;
2369 $logParamsDetails = [];
2371 // Null revision (used for change tag insertion)
2372 $nullRevision = null;
2374 if ( $id ) { // Protection of existing page
2375 // Avoid PHP 7.1 warning of passing $this by reference
2378 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2379 return Status
::newGood();
2382 // Only certain restrictions can cascade...
2383 $editrestriction = isset( $limit['edit'] )
2384 ?
[ $limit['edit'] ]
2385 : $this->mTitle
->getRestrictions( 'edit' );
2386 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2387 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2389 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2390 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2393 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2394 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2395 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2397 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2398 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2401 // The schema allows multiple restrictions
2402 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2406 // insert null revision to identify the page protection change as edit summary
2407 $latest = $this->getLatest();
2408 $nullRevision = $this->insertProtectNullRevision(
2417 if ( $nullRevision === null ) {
2418 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2421 $logRelationsField = 'pr_id';
2423 // Update restrictions table
2424 foreach ( $limit as $action => $restrictions ) {
2426 'page_restrictions',
2429 'pr_type' => $action
2433 if ( $restrictions != '' ) {
2434 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2436 'page_restrictions',
2439 'pr_type' => $action,
2440 'pr_level' => $restrictions,
2441 'pr_cascade' => $cascadeValue,
2442 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2446 $logRelationsValues[] = $dbw->insertId();
2447 $logParamsDetails[] = [
2449 'level' => $restrictions,
2450 'expiry' => $expiry[$action],
2451 'cascade' => (bool)$cascadeValue,
2456 // Clear out legacy restriction fields
2459 [ 'page_restrictions' => '' ],
2460 [ 'page_id' => $id ],
2464 // Avoid PHP 7.1 warning of passing $this by reference
2467 Hooks
::run( 'NewRevisionFromEditComplete',
2468 [ $this, $nullRevision, $latest, $user ] );
2469 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2470 } else { // Protection of non-existing page (also known as "title protection")
2471 // Cascade protection is meaningless in this case
2474 if ( $limit['create'] != '' ) {
2475 $commentFields = CommentStore
::newKey( 'pt_reason' )->insert( $dbw, $reason );
2476 $dbw->replace( 'protected_titles',
2477 [ [ 'pt_namespace', 'pt_title' ] ],
2479 'pt_namespace' => $this->mTitle
->getNamespace(),
2480 'pt_title' => $this->mTitle
->getDBkey(),
2481 'pt_create_perm' => $limit['create'],
2482 'pt_timestamp' => $dbw->timestamp(),
2483 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2484 'pt_user' => $user->getId(),
2485 ] +
$commentFields, __METHOD__
2487 $logParamsDetails[] = [
2489 'level' => $limit['create'],
2490 'expiry' => $expiry['create'],
2493 $dbw->delete( 'protected_titles',
2495 'pt_namespace' => $this->mTitle
->getNamespace(),
2496 'pt_title' => $this->mTitle
->getDBkey()
2502 $this->mTitle
->flushRestrictions();
2503 InfoAction
::invalidateCache( $this->mTitle
);
2505 if ( $logAction == 'unprotect' ) {
2508 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2510 '4::description' => $protectDescriptionLog, // parameter for IRC
2511 '5:bool:cascade' => $cascade,
2512 'details' => $logParamsDetails, // parameter for localize and api
2516 // Update the protection log
2517 $logEntry = new ManualLogEntry( 'protect', $logAction );
2518 $logEntry->setTarget( $this->mTitle
);
2519 $logEntry->setComment( $reason );
2520 $logEntry->setPerformer( $user );
2521 $logEntry->setParameters( $params );
2522 if ( !is_null( $nullRevision ) ) {
2523 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2525 $logEntry->setTags( $tags );
2526 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2527 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2529 $logId = $logEntry->insert();
2530 $logEntry->publish( $logId );
2532 return Status
::newGood( $logId );
2536 * Insert a new null revision for this page.
2538 * @param string $revCommentMsg Comment message key for the revision
2539 * @param array $limit Set of restriction keys
2540 * @param array $expiry Per restriction type expiration
2541 * @param int $cascade Set to false if cascading protection isn't allowed.
2542 * @param string $reason
2543 * @param User|null $user
2544 * @return Revision|null Null on error
2546 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2547 array $expiry, $cascade, $reason, $user = null
2549 $dbw = wfGetDB( DB_MASTER
);
2551 // Prepare a null revision to be added to the history
2552 $editComment = wfMessage(
2554 $this->mTitle
->getPrefixedText(),
2555 $user ?
$user->getName() : ''
2556 )->inContentLanguage()->text();
2558 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2560 $protectDescription = $this->protectDescription( $limit, $expiry );
2561 if ( $protectDescription ) {
2562 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2563 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2564 ->inContentLanguage()->text();
2567 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2568 $editComment .= wfMessage( 'brackets' )->params(
2569 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2570 )->inContentLanguage()->text();
2573 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2575 $nullRev->insertOn( $dbw );
2577 // Update page record and touch page
2578 $oldLatest = $nullRev->getParentId();
2579 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2586 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2589 protected function formatExpiry( $expiry ) {
2592 if ( $expiry != 'infinity' ) {
2595 $wgContLang->timeanddate( $expiry, false, false ),
2596 $wgContLang->date( $expiry, false, false ),
2597 $wgContLang->time( $expiry, false, false )
2598 )->inContentLanguage()->text();
2600 return wfMessage( 'protect-expiry-indefinite' )
2601 ->inContentLanguage()->text();
2606 * Builds the description to serve as comment for the edit.
2608 * @param array $limit Set of restriction keys
2609 * @param array $expiry Per restriction type expiration
2612 public function protectDescription( array $limit, array $expiry ) {
2613 $protectDescription = '';
2615 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2616 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2617 # All possible message keys are listed here for easier grepping:
2618 # * restriction-create
2619 # * restriction-edit
2620 # * restriction-move
2621 # * restriction-upload
2622 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2623 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2624 # with '' filtered out. All possible message keys are listed below:
2625 # * protect-level-autoconfirmed
2626 # * protect-level-sysop
2627 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2628 ->inContentLanguage()->text();
2630 $expiryText = $this->formatExpiry( $expiry[$action] );
2632 if ( $protectDescription !== '' ) {
2633 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2635 $protectDescription .= wfMessage( 'protect-summary-desc' )
2636 ->params( $actionText, $restrictionsText, $expiryText )
2637 ->inContentLanguage()->text();
2640 return $protectDescription;
2644 * Builds the description to serve as comment for the log entry.
2646 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2647 * protect description text. Keep them in old format to avoid breaking compatibility.
2648 * TODO: Fix protection log to store structured description and format it on-the-fly.
2650 * @param array $limit Set of restriction keys
2651 * @param array $expiry Per restriction type expiration
2654 public function protectDescriptionLog( array $limit, array $expiry ) {
2657 $protectDescriptionLog = '';
2659 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2660 $expiryText = $this->formatExpiry( $expiry[$action] );
2661 $protectDescriptionLog .= $wgContLang->getDirMark() .
2662 "[$action=$restrictions] ($expiryText)";
2665 return trim( $protectDescriptionLog );
2669 * Take an array of page restrictions and flatten it to a string
2670 * suitable for insertion into the page_restrictions field.
2672 * @param string[] $limit
2674 * @throws MWException
2677 protected static function flattenRestrictions( $limit ) {
2678 if ( !is_array( $limit ) ) {
2679 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2685 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2686 $bits[] = "$action=$restrictions";
2689 return implode( ':', $bits );
2693 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2694 * backwards compatibility, if you care about error reporting you should use
2695 * doDeleteArticleReal() instead.
2697 * Deletes the article with database consistency, writes logs, purges caches
2699 * @param string $reason Delete reason for deletion log
2700 * @param bool $suppress Suppress all revisions and log the deletion in
2701 * the suppression log instead of the deletion log
2702 * @param int $u1 Unused
2703 * @param bool $u2 Unused
2704 * @param array|string &$error Array of errors to append to
2705 * @param User $user The deleting user
2706 * @return bool True if successful
2708 public function doDeleteArticle(
2709 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2711 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2712 return $status->isGood();
2716 * Back-end article deletion
2717 * Deletes the article with database consistency, writes logs, purges caches
2721 * @param string $reason Delete reason for deletion log
2722 * @param bool $suppress Suppress all revisions and log the deletion in
2723 * the suppression log instead of the deletion log
2724 * @param int $u1 Unused
2725 * @param bool $u2 Unused
2726 * @param array|string &$error Array of errors to append to
2727 * @param User $user The deleting user
2728 * @param array $tags Tags to apply to the deletion action
2729 * @return Status Status object; if successful, $status->value is the log_id of the
2730 * deletion log entry. If the page couldn't be deleted because it wasn't
2731 * found, $status is a non-fatal 'cannotdelete' error
2733 public function doDeleteArticleReal(
2734 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2735 $tags = [], $logsubtype = 'delete'
2737 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2739 wfDebug( __METHOD__
. "\n" );
2741 $status = Status
::newGood();
2743 if ( $this->mTitle
->getDBkey() === '' ) {
2744 $status->error( 'cannotdelete',
2745 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2749 // Avoid PHP 7.1 warning of passing $this by reference
2752 $user = is_null( $user ) ?
$wgUser : $user;
2753 if ( !Hooks
::run( 'ArticleDelete',
2754 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2756 if ( $status->isOK() ) {
2757 // Hook aborted but didn't set a fatal status
2758 $status->fatal( 'delete-hook-aborted' );
2763 $dbw = wfGetDB( DB_MASTER
);
2764 $dbw->startAtomic( __METHOD__
);
2766 $this->loadPageData( self
::READ_LATEST
);
2767 $id = $this->getId();
2768 // T98706: lock the page from various other updates but avoid using
2769 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2770 // the revisions queries (which also JOIN on user). Only lock the page
2771 // row and CAS check on page_latest to see if the trx snapshot matches.
2772 $lockedLatest = $this->lockAndGetLatest();
2773 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2774 $dbw->endAtomic( __METHOD__
);
2775 // Page not there or trx snapshot is stale
2776 $status->error( 'cannotdelete',
2777 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2781 // Given the lock above, we can be confident in the title and page ID values
2782 $namespace = $this->getTitle()->getNamespace();
2783 $dbKey = $this->getTitle()->getDBkey();
2785 // At this point we are now comitted to returning an OK
2786 // status unless some DB query error or other exception comes up.
2787 // This way callers don't have to call rollback() if $status is bad
2788 // unless they actually try to catch exceptions (which is rare).
2790 // we need to remember the old content so we can use it to generate all deletion updates.
2791 $revision = $this->getRevision();
2793 $content = $this->getContent( Revision
::RAW
);
2794 } catch ( Exception
$ex ) {
2795 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2796 . $ex->getMessage() );
2801 $revCommentStore = new CommentStore( 'rev_comment' );
2802 $arCommentStore = new CommentStore( 'ar_comment' );
2804 $fields = Revision
::selectFields();
2807 // Bitfields to further suppress the content
2809 $bitfield = Revision
::SUPPRESSED_ALL
;
2810 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2813 // For now, shunt the revision data into the archive table.
2814 // Text is *not* removed from the text table; bulk storage
2815 // is left intact to avoid breaking block-compression or
2816 // immutable storage schemes.
2817 // In the future, we may keep revisions and mark them with
2818 // the rev_deleted field, which is reserved for this purpose.
2820 // Get all of the page revisions
2821 $commentQuery = $revCommentStore->getJoin();
2822 $res = $dbw->select(
2823 [ 'revision' ] +
$commentQuery['tables'],
2824 $fields +
$commentQuery['fields'],
2825 [ 'rev_page' => $id ],
2828 $commentQuery['joins']
2831 // Build their equivalent archive rows
2835 /** @var int[] Revision IDs of edits that were made by IPs */
2838 foreach ( $res as $row ) {
2839 $comment = $revCommentStore->getComment( $row );
2841 'ar_namespace' => $namespace,
2842 'ar_title' => $dbKey,
2843 'ar_user' => $row->rev_user
,
2844 'ar_user_text' => $row->rev_user_text
,
2845 'ar_timestamp' => $row->rev_timestamp
,
2846 'ar_minor_edit' => $row->rev_minor_edit
,
2847 'ar_rev_id' => $row->rev_id
,
2848 'ar_parent_id' => $row->rev_parent_id
,
2849 'ar_text_id' => $row->rev_text_id
,
2852 'ar_len' => $row->rev_len
,
2853 'ar_page_id' => $id,
2854 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2855 'ar_sha1' => $row->rev_sha1
,
2856 ] +
$arCommentStore->insert( $dbw, $comment );
2857 if ( $wgContentHandlerUseDB ) {
2858 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2859 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2861 $rowsInsert[] = $rowInsert;
2862 $revids[] = $row->rev_id
;
2864 // Keep track of IP edits, so that the corresponding rows can
2865 // be deleted in the ip_changes table.
2866 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2867 $ipRevIds[] = $row->rev_id
;
2870 // Copy them into the archive table
2871 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2872 // Save this so we can pass it to the ArticleDeleteComplete hook.
2873 $archivedRevisionCount = $dbw->affectedRows();
2875 // Clone the title and wikiPage, so we have the information we need when
2876 // we log and run the ArticleDeleteComplete hook.
2877 $logTitle = clone $this->mTitle
;
2878 $wikiPageBeforeDelete = clone $this;
2880 // Now that it's safely backed up, delete it
2881 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2882 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2883 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2884 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2887 // Also delete records from ip_changes as applicable.
2888 if ( count( $ipRevIds ) > 0 ) {
2889 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2892 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2893 $logtype = $suppress ?
'suppress' : 'delete';
2895 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2896 $logEntry->setPerformer( $user );
2897 $logEntry->setTarget( $logTitle );
2898 $logEntry->setComment( $reason );
2899 $logEntry->setTags( $tags );
2900 $logid = $logEntry->insert();
2902 $dbw->onTransactionPreCommitOrIdle(
2903 function () use ( $dbw, $logEntry, $logid ) {
2904 // T58776: avoid deadlocks (especially from FileDeleteForm)
2905 $logEntry->publish( $logid );
2910 $dbw->endAtomic( __METHOD__
);
2912 $this->doDeleteUpdates( $id, $content, $revision );
2914 Hooks
::run( 'ArticleDeleteComplete', [
2915 &$wikiPageBeforeDelete,
2921 $archivedRevisionCount
2923 $status->value
= $logid;
2925 // Show log excerpt on 404 pages rather than just a link
2926 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2927 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2928 $cache->set( $key, 1, $cache::TTL_DAY
);
2934 * Lock the page row for this title+id and return page_latest (or 0)
2936 * @return int Returns 0 if no row was found with this title+id
2939 public function lockAndGetLatest() {
2940 return (int)wfGetDB( DB_MASTER
)->selectField(
2944 'page_id' => $this->getId(),
2945 // Typically page_id is enough, but some code might try to do
2946 // updates assuming the title is the same, so verify that
2947 'page_namespace' => $this->getTitle()->getNamespace(),
2948 'page_title' => $this->getTitle()->getDBkey()
2956 * Do some database updates after deletion
2958 * @param int $id The page_id value of the page being deleted
2959 * @param Content|null $content Optional page content to be used when determining
2960 * the required updates. This may be needed because $this->getContent()
2961 * may already return null when the page proper was deleted.
2962 * @param Revision|null $revision The latest page revision
2964 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2966 $countable = $this->isCountable();
2967 } catch ( Exception
$ex ) {
2968 // fallback for deleting broken pages for which we cannot load the content for
2969 // some reason. Note that doDeleteArticleReal() already logged this problem.
2973 // Update site status
2974 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2976 // Delete pagelinks, update secondary indexes, etc
2977 $updates = $this->getDeletionUpdates( $content );
2978 foreach ( $updates as $update ) {
2979 DeferredUpdates
::addUpdate( $update );
2982 // Reparse any pages transcluding this page
2983 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2985 // Reparse any pages including this image
2986 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2987 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2991 self
::onArticleDelete( $this->mTitle
);
2992 ResourceLoaderWikiModule
::invalidateModuleCache(
2993 $this->mTitle
, $revision, null, wfWikiID()
2996 // Reset this object and the Title object
2997 $this->loadFromRow( false, self
::READ_LATEST
);
3000 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3004 * Roll back the most recent consecutive set of edits to a page
3005 * from the same user; fails if there are no eligible edits to
3006 * roll back to, e.g. user is the sole contributor. This function
3007 * performs permissions checks on $user, then calls commitRollback()
3008 * to do the dirty work
3010 * @todo Separate the business/permission stuff out from backend code
3011 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3013 * @param string $fromP Name of the user whose edits to rollback.
3014 * @param string $summary Custom summary. Set to default summary if empty.
3015 * @param string $token Rollback token.
3016 * @param bool $bot If true, mark all reverted edits as bot.
3018 * @param array &$resultDetails Array contains result-specific array of additional values
3019 * 'alreadyrolled' : 'current' (rev)
3020 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3022 * @param User $user The user performing the rollback
3023 * @param array|null $tags Change tags to apply to the rollback
3024 * Callers are responsible for permission checks
3025 * (with ChangeTags::canAddTagsAccompanyingChange)
3027 * @return array Array of errors, each error formatted as
3028 * array(messagekey, param1, param2, ...).
3029 * On success, the array is empty. This array can also be passed to
3030 * OutputPage::showPermissionsErrorPage().
3032 public function doRollback(
3033 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3035 $resultDetails = null;
3037 // Check permissions
3038 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3039 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3040 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3042 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3043 $errors[] = [ 'sessionfailure' ];
3046 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3047 $errors[] = [ 'actionthrottledtext' ];
3050 // If there were errors, bail out now
3051 if ( !empty( $errors ) ) {
3055 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3059 * Backend implementation of doRollback(), please refer there for parameter
3060 * and return value documentation
3062 * NOTE: This function does NOT check ANY permissions, it just commits the
3063 * rollback to the DB. Therefore, you should only call this function direct-
3064 * ly if you want to use custom permissions checks. If you don't, use
3065 * doRollback() instead.
3066 * @param string $fromP Name of the user whose edits to rollback.
3067 * @param string $summary Custom summary. Set to default summary if empty.
3068 * @param bool $bot If true, mark all reverted edits as bot.
3070 * @param array &$resultDetails Contains result-specific array of additional values
3071 * @param User $guser The user performing the rollback
3072 * @param array|null $tags Change tags to apply to the rollback
3073 * Callers are responsible for permission checks
3074 * (with ChangeTags::canAddTagsAccompanyingChange)
3078 public function commitRollback( $fromP, $summary, $bot,
3079 &$resultDetails, User
$guser, $tags = null
3081 global $wgUseRCPatrol, $wgContLang;
3083 $dbw = wfGetDB( DB_MASTER
);
3085 if ( wfReadOnly() ) {
3086 return [ [ 'readonlytext' ] ];
3089 // Get the last editor
3090 $current = $this->getRevision();
3091 if ( is_null( $current ) ) {
3092 // Something wrong... no page?
3093 return [ [ 'notanarticle' ] ];
3096 $from = str_replace( '_', ' ', $fromP );
3097 // User name given should match up with the top revision.
3098 // If the user was deleted then $from should be empty.
3099 if ( $from != $current->getUserText() ) {
3100 $resultDetails = [ 'current' => $current ];
3101 return [ [ 'alreadyrolled',
3102 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3103 htmlspecialchars( $fromP ),
3104 htmlspecialchars( $current->getUserText() )
3108 // Get the last edit not by this person...
3109 // Note: these may not be public values
3110 $user = intval( $current->getUser( Revision
::RAW
) );
3111 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3112 $s = $dbw->selectRow( 'revision',
3113 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3114 [ 'rev_page' => $current->getPage(),
3115 "rev_user != {$user} OR rev_user_text != {$user_text}"
3117 [ 'USE INDEX' => 'page_timestamp',
3118 'ORDER BY' => 'rev_timestamp DESC' ]
3120 if ( $s === false ) {
3121 // No one else ever edited this page
3122 return [ [ 'cantrollback' ] ];
3123 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3124 ||
$s->rev_deleted
& Revision
::DELETED_USER
3126 // Only admins can see this text
3127 return [ [ 'notvisiblerev' ] ];
3130 // Generate the edit summary if necessary
3131 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3132 if ( empty( $summary ) ) {
3133 if ( $from == '' ) { // no public user name
3134 $summary = wfMessage( 'revertpage-nouser' );
3136 $summary = wfMessage( 'revertpage' );
3140 // Allow the custom summary to use the same args as the default message
3142 $target->getUserText(), $from, $s->rev_id
,
3143 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3144 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3146 if ( $summary instanceof Message
) {
3147 $summary = $summary->params( $args )->inContentLanguage()->text();
3149 $summary = wfMsgReplaceArgs( $summary, $args );
3152 // Trim spaces on user supplied text
3153 $summary = trim( $summary );
3156 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3158 if ( $guser->isAllowed( 'minoredit' ) ) {
3159 $flags |
= EDIT_MINOR
;
3162 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3163 $flags |
= EDIT_FORCE_BOT
;
3166 $targetContent = $target->getContent();
3167 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3169 // Actually store the edit
3170 $status = $this->doEditContent(
3180 // Set patrolling and bot flag on the edits, which gets rollbacked.
3181 // This is done even on edit failure to have patrolling in that case (T64157).
3183 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3184 // Mark all reverted edits as bot
3188 if ( $wgUseRCPatrol ) {
3189 // Mark all reverted edits as patrolled
3190 $set['rc_patrolled'] = 1;
3193 if ( count( $set ) ) {
3194 $dbw->update( 'recentchanges', $set,
3196 'rc_cur_id' => $current->getPage(),
3197 'rc_user_text' => $current->getUserText(),
3198 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3204 if ( !$status->isOK() ) {
3205 return $status->getErrorsArray();
3208 // raise error, when the edit is an edit without a new version
3209 $statusRev = isset( $status->value
['revision'] )
3210 ?
$status->value
['revision']
3212 if ( !( $statusRev instanceof Revision
) ) {
3213 $resultDetails = [ 'current' => $current ];
3214 return [ [ 'alreadyrolled',
3215 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3216 htmlspecialchars( $fromP ),
3217 htmlspecialchars( $current->getUserText() )
3221 if ( $changingContentModel ) {
3222 // If the content model changed during the rollback,
3223 // make sure it gets logged to Special:Log/contentmodel
3224 $log = new ManualLogEntry( 'contentmodel', 'change' );
3225 $log->setPerformer( $guser );
3226 $log->setTarget( $this->mTitle
);
3227 $log->setComment( $summary );
3228 $log->setParameters( [
3229 '4::oldmodel' => $current->getContentModel(),
3230 '5::newmodel' => $targetContent->getModel(),
3233 $logId = $log->insert( $dbw );
3234 $log->publish( $logId );
3237 $revId = $statusRev->getId();
3239 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3242 'summary' => $summary,
3243 'current' => $current,
3244 'target' => $target,
3252 * The onArticle*() functions are supposed to be a kind of hooks
3253 * which should be called whenever any of the specified actions
3256 * This is a good place to put code to clear caches, for instance.
3258 * This is called on page move and undelete, as well as edit
3260 * @param Title $title
3262 public static function onArticleCreate( Title
$title ) {
3263 // Update existence markers on article/talk tabs...
3264 $other = $title->getOtherPage();
3266 $other->purgeSquid();
3268 $title->touchLinks();
3269 $title->purgeSquid();
3270 $title->deleteTitleProtection();
3272 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3274 // Invalidate caches of articles which include this page
3275 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3277 if ( $title->getNamespace() == NS_CATEGORY
) {
3278 // Load the Category object, which will schedule a job to create
3279 // the category table row if necessary. Checking a replica DB is ok
3280 // here, in the worst case it'll run an unnecessary recount job on
3281 // a category that probably doesn't have many members.
3282 Category
::newFromTitle( $title )->getID();
3287 * Clears caches when article is deleted
3289 * @param Title $title
3291 public static function onArticleDelete( Title
$title ) {
3292 // Update existence markers on article/talk tabs...
3293 $other = $title->getOtherPage();
3295 $other->purgeSquid();
3297 $title->touchLinks();
3298 $title->purgeSquid();
3300 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3303 HTMLFileCache
::clearFileCache( $title );
3304 InfoAction
::invalidateCache( $title );
3307 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3308 MessageCache
::singleton()->updateMessageOverride( $title, null );
3312 if ( $title->getNamespace() == NS_FILE
) {
3313 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3317 if ( $title->getNamespace() == NS_USER_TALK
) {
3318 $user = User
::newFromName( $title->getText(), false );
3320 $user->setNewtalk( false );
3325 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3329 * Purge caches on page update etc
3331 * @param Title $title
3332 * @param Revision|null $revision Revision that was just saved, may be null
3334 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3335 // Invalidate caches of articles which include this page
3336 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3338 // Invalidate the caches of all pages which redirect here
3339 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3341 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3343 // Purge CDN for this page only
3344 $title->purgeSquid();
3345 // Clear file cache for this page only
3346 HTMLFileCache
::clearFileCache( $title );
3348 $revid = $revision ?
$revision->getId() : null;
3349 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3350 InfoAction
::invalidateCache( $title, $revid );
3357 * Returns a list of categories this page is a member of.
3358 * Results will include hidden categories
3360 * @return TitleArray
3362 public function getCategories() {
3363 $id = $this->getId();
3365 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3368 $dbr = wfGetDB( DB_REPLICA
);
3369 $res = $dbr->select( 'categorylinks',
3370 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3371 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3372 // as not being aliases, and NS_CATEGORY is numeric
3373 [ 'cl_from' => $id ],
3376 return TitleArray
::newFromResult( $res );
3380 * Returns a list of hidden categories this page is a member of.
3381 * Uses the page_props and categorylinks tables.
3383 * @return array Array of Title objects
3385 public function getHiddenCategories() {
3387 $id = $this->getId();
3393 $dbr = wfGetDB( DB_REPLICA
);
3394 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3396 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3397 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3400 if ( $res !== false ) {
3401 foreach ( $res as $row ) {
3402 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3410 * Auto-generates a deletion reason
3412 * @param bool &$hasHistory Whether the page has a history
3413 * @return string|bool String containing deletion reason or empty string, or boolean false
3414 * if no revision occurred
3416 public function getAutoDeleteReason( &$hasHistory ) {
3417 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3421 * Update all the appropriate counts in the category table, given that
3422 * we've added the categories $added and deleted the categories $deleted.
3424 * This should only be called from deferred updates or jobs to avoid contention.
3426 * @param array $added The names of categories that were added
3427 * @param array $deleted The names of categories that were deleted
3428 * @param int $id Page ID (this should be the original deleted page ID)
3430 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3431 $id = $id ?
: $this->getId();
3432 $ns = $this->getTitle()->getNamespace();
3434 $addFields = [ 'cat_pages = cat_pages + 1' ];
3435 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3436 if ( $ns == NS_CATEGORY
) {
3437 $addFields[] = 'cat_subcats = cat_subcats + 1';
3438 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3439 } elseif ( $ns == NS_FILE
) {
3440 $addFields[] = 'cat_files = cat_files + 1';
3441 $removeFields[] = 'cat_files = cat_files - 1';
3444 $dbw = wfGetDB( DB_MASTER
);
3446 if ( count( $added ) ) {
3447 $existingAdded = $dbw->selectFieldValues(
3450 [ 'cat_title' => $added ],
3454 // For category rows that already exist, do a plain
3455 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3456 // to avoid creating gaps in the cat_id sequence.
3457 if ( count( $existingAdded ) ) {
3461 [ 'cat_title' => $existingAdded ],
3466 $missingAdded = array_diff( $added, $existingAdded );
3467 if ( count( $missingAdded ) ) {
3469 foreach ( $missingAdded as $cat ) {
3471 'cat_title' => $cat,
3473 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3474 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3487 if ( count( $deleted ) ) {
3491 [ 'cat_title' => $deleted ],
3496 foreach ( $added as $catName ) {
3497 $cat = Category
::newFromName( $catName );
3498 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3501 foreach ( $deleted as $catName ) {
3502 $cat = Category
::newFromName( $catName );
3503 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3506 // Refresh counts on categories that should be empty now, to
3507 // trigger possible deletion. Check master for the most
3508 // up-to-date cat_pages.
3509 if ( count( $deleted ) ) {
3510 $rows = $dbw->select(
3512 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3513 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3516 foreach ( $rows as $row ) {
3517 $cat = Category
::newFromRow( $row );
3518 // T166757: do the update after this DB commit
3519 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3520 $cat->refreshCounts();
3527 * Opportunistically enqueue link update jobs given fresh parser output if useful
3529 * @param ParserOutput $parserOutput Current version page output
3532 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3533 if ( wfReadOnly() ) {
3537 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3538 [ $this, $this->mTitle
, $parserOutput ]
3543 $config = RequestContext
::getMain()->getConfig();
3546 'isOpportunistic' => true,
3547 'rootJobTimestamp' => $parserOutput->getCacheTime()
3550 if ( $this->mTitle
->areRestrictionsCascading() ) {
3551 // If the page is cascade protecting, the links should really be up-to-date
3552 JobQueueGroup
::singleton()->lazyPush(
3553 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3555 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3556 // Assume the output contains "dynamic" time/random based magic words.
3557 // Only update pages that expired due to dynamic content and NOT due to edits
3558 // to referenced templates/files. When the cache expires due to dynamic content,
3559 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3560 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3561 // template/file edit already triggered recursive RefreshLinksJob jobs.
3562 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3563 // If a page is uncacheable, do not keep spamming a job for it.
3564 // Although it would be de-duplicated, it would still waste I/O.
3565 $cache = ObjectCache
::getLocalClusterInstance();
3566 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3567 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3568 if ( $cache->add( $key, time(), $ttl ) ) {
3569 JobQueueGroup
::singleton()->lazyPush(
3570 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3578 * Returns a list of updates to be performed when this page is deleted. The
3579 * updates should remove any information about this page from secondary data
3580 * stores such as links tables.
3582 * @param Content|null $content Optional Content object for determining the
3583 * necessary updates.
3584 * @return DeferrableUpdate[]
3586 public function getDeletionUpdates( Content
$content = null ) {
3588 // load content object, which may be used to determine the necessary updates.
3589 // XXX: the content may not be needed to determine the updates.
3591 $content = $this->getContent( Revision
::RAW
);
3592 } catch ( Exception
$ex ) {
3593 // If we can't load the content, something is wrong. Perhaps that's why
3594 // the user is trying to delete the page, so let's not fail in that case.
3595 // Note that doDeleteArticleReal() will already have logged an issue with
3596 // loading the content.
3603 $updates = $content->getDeletionUpdates( $this );
3606 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3611 * Whether this content displayed on this page
3612 * comes from the local database
3617 public function isLocal() {
3622 * The display name for the site this content
3623 * come from. If a subclass overrides isLocal(),
3624 * this could return something other than the
3630 public function getWikiDisplayName() {
3636 * Get the source URL for the content on this page,
3637 * typically the canonical URL, but may be a remote
3638 * link if the content comes from another site
3643 public function getSourceURL() {
3644 return $this->getTitle()->getCanonicalURL();
3648 * @param WANObjectCache $cache
3652 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3653 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3655 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );