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
218 public function getActionOverrides() {
219 return $this->getContentHandler()->getActionOverrides();
223 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
225 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
227 * @return ContentHandler
231 public function getContentHandler() {
232 return ContentHandler
::getForModelID( $this->getContentModel() );
236 * Get the title object of the article
237 * @return Title Title object of this page
239 public function getTitle() {
240 return $this->mTitle
;
247 public function clear() {
248 $this->mDataLoaded
= false;
249 $this->mDataLoadedFrom
= self
::READ_NONE
;
251 $this->clearCacheFields();
255 * Clear the object cache fields
258 protected function clearCacheFields() {
260 $this->mRedirectTarget
= null; // Title object if set
261 $this->mLastRevision
= null; // Latest revision
262 $this->mTouched
= '19700101000000';
263 $this->mLinksUpdated
= '19700101000000';
264 $this->mTimestamp
= '';
265 $this->mIsRedirect
= false;
266 $this->mLatest
= false;
267 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
268 // the requested rev ID and content against the cached one for equality. For most
269 // content types, the output should not change during the lifetime of this cache.
270 // Clearing it can cause extra parses on edit for no reason.
274 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
278 public function clearPreparedEdit() {
279 $this->mPreparedEdit
= false;
283 * Return the list of revision fields that should be selected to create
288 public static function selectFields() {
289 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
300 'page_links_updated',
305 if ( $wgContentHandlerUseDB ) {
306 $fields[] = 'page_content_model';
309 if ( $wgPageLanguageUseDB ) {
310 $fields[] = 'page_lang';
317 * Fetch a page record with the given conditions
318 * @param IDatabase $dbr
319 * @param array $conditions
320 * @param array $options
321 * @return object|bool Database result resource, or false on failure
323 protected function pageData( $dbr, $conditions, $options = [] ) {
324 $fields = self
::selectFields();
326 // Avoid PHP 7.1 warning of passing $this by reference
329 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
331 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
333 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
339 * Fetch a page record matching the Title object's namespace and title
340 * using a sanitized title string
342 * @param IDatabase $dbr
343 * @param Title $title
344 * @param array $options
345 * @return object|bool Database result resource, or false on failure
347 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
348 return $this->pageData( $dbr, [
349 'page_namespace' => $title->getNamespace(),
350 'page_title' => $title->getDBkey() ], $options );
354 * Fetch a page record matching the requested ID
356 * @param IDatabase $dbr
358 * @param array $options
359 * @return object|bool Database result resource, or false on failure
361 public function pageDataFromId( $dbr, $id, $options = [] ) {
362 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
366 * Load the object from a given source by title
368 * @param object|string|int $from One of the following:
369 * - A DB query result object.
370 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
371 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
372 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
373 * using SELECT FOR UPDATE.
377 public function loadPageData( $from = 'fromdb' ) {
378 $from = self
::convertSelectType( $from );
379 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
380 // We already have the data from the correct location, no need to load it twice.
384 if ( is_int( $from ) ) {
385 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
386 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
387 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
390 && $index == DB_REPLICA
391 && $loadBalancer->getServerCount() > 1
392 && $loadBalancer->hasOrMadeRecentMasterChanges()
394 $from = self
::READ_LATEST
;
395 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
396 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
399 // No idea from where the caller got this data, assume replica DB.
401 $from = self
::READ_NORMAL
;
404 $this->loadFromRow( $data, $from );
408 * Load the object from a database row
411 * @param object|bool $data DB row containing fields returned by selectFields() or false
412 * @param string|int $from One of the following:
413 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
414 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
415 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
416 * the master DB using SELECT FOR UPDATE
418 public function loadFromRow( $data, $from ) {
419 $lc = LinkCache
::singleton();
420 $lc->clearLink( $this->mTitle
);
423 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
425 $this->mTitle
->loadFromRow( $data );
427 // Old-fashioned restrictions
428 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
430 $this->mId
= intval( $data->page_id
);
431 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
432 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
433 $this->mIsRedirect
= intval( $data->page_is_redirect
);
434 $this->mLatest
= intval( $data->page_latest
);
435 // T39225: $latest may no longer match the cached latest Revision object.
436 // Double-check the ID of any cached latest Revision object for consistency.
437 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
438 $this->mLastRevision
= null;
439 $this->mTimestamp
= '';
442 $lc->addBadLinkObj( $this->mTitle
);
444 $this->mTitle
->loadFromRow( false );
446 $this->clearCacheFields();
451 $this->mDataLoaded
= true;
452 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
456 * @return int Page ID
458 public function getId() {
459 if ( !$this->mDataLoaded
) {
460 $this->loadPageData();
466 * @return bool Whether or not the page exists in the database
468 public function exists() {
469 if ( !$this->mDataLoaded
) {
470 $this->loadPageData();
472 return $this->mId
> 0;
476 * Check if this page is something we're going to be showing
477 * some sort of sensible content for. If we return false, page
478 * views (plain action=view) will return an HTTP 404 response,
479 * so spiders and robots can know they're following a bad link.
483 public function hasViewableContent() {
484 return $this->mTitle
->isKnown();
488 * Tests if the article content represents a redirect
492 public function isRedirect() {
493 if ( !$this->mDataLoaded
) {
494 $this->loadPageData();
497 return (bool)$this->mIsRedirect
;
501 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
503 * Will use the revisions actual content model if the page exists,
504 * and the page's default if the page doesn't exist yet.
510 public function getContentModel() {
511 if ( $this->exists() ) {
512 $cache = ObjectCache
::getMainWANInstance();
514 return $cache->getWithSetCallback(
515 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
518 $rev = $this->getRevision();
520 // Look at the revision's actual content model
521 return $rev->getContentModel();
523 $title = $this->mTitle
->getPrefixedDBkey();
524 wfWarn( "Page $title exists but has no (visible) revisions!" );
525 return $this->mTitle
->getContentModel();
531 // use the default model for this page
532 return $this->mTitle
->getContentModel();
536 * Loads page_touched and returns a value indicating if it should be used
537 * @return bool True if this page exists and is not a redirect
539 public function checkTouched() {
540 if ( !$this->mDataLoaded
) {
541 $this->loadPageData();
543 return ( $this->mId
&& !$this->mIsRedirect
);
547 * Get the page_touched field
548 * @return string Containing GMT timestamp
550 public function getTouched() {
551 if ( !$this->mDataLoaded
) {
552 $this->loadPageData();
554 return $this->mTouched
;
558 * Get the page_links_updated field
559 * @return string|null Containing GMT timestamp
561 public function getLinksTimestamp() {
562 if ( !$this->mDataLoaded
) {
563 $this->loadPageData();
565 return $this->mLinksUpdated
;
569 * Get the page_latest field
570 * @return int The rev_id of current revision
572 public function getLatest() {
573 if ( !$this->mDataLoaded
) {
574 $this->loadPageData();
576 return (int)$this->mLatest
;
580 * Get the Revision object of the oldest revision
581 * @return Revision|null
583 public function getOldestRevision() {
584 // Try using the replica DB first, then try the master
585 $rev = $this->mTitle
->getFirstRevision();
587 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
596 protected function loadLastEdit() {
597 if ( $this->mLastRevision
!== null ) {
598 return; // already loaded
601 $latest = $this->getLatest();
603 return; // page doesn't exist or is missing page_latest info
606 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
607 // T39225: if session S1 loads the page row FOR UPDATE, the result always
608 // includes the latest changes committed. This is true even within REPEATABLE-READ
609 // transactions, where S1 normally only sees changes committed before the first S1
610 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
611 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
612 // happened after the first S1 SELECT.
613 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
614 $flags = Revision
::READ_LOCKING
;
615 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
616 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
617 // Bug T93976: if page_latest was loaded from the master, fetch the
618 // revision from there as well, as it may not exist yet on a replica DB.
619 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
620 $flags = Revision
::READ_LATEST
;
621 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
623 $dbr = wfGetDB( DB_REPLICA
);
624 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
627 if ( $revision ) { // sanity
628 $this->setLastEdit( $revision );
633 * Set the latest revision
634 * @param Revision $revision
636 protected function setLastEdit( Revision
$revision ) {
637 $this->mLastRevision
= $revision;
638 $this->mTimestamp
= $revision->getTimestamp();
642 * Get the latest revision
643 * @return Revision|null
645 public function getRevision() {
646 $this->loadLastEdit();
647 if ( $this->mLastRevision
) {
648 return $this->mLastRevision
;
654 * Get the content of the current revision. No side-effects...
656 * @param int $audience One of:
657 * Revision::FOR_PUBLIC to be displayed to all users
658 * Revision::FOR_THIS_USER to be displayed to $wgUser
659 * Revision::RAW get the text regardless of permissions
660 * @param User $user User object to check for, only if FOR_THIS_USER is passed
661 * to the $audience parameter
662 * @return Content|null The content of the current revision
666 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
667 $this->loadLastEdit();
668 if ( $this->mLastRevision
) {
669 return $this->mLastRevision
->getContent( $audience, $user );
675 * @return string MW timestamp of last article revision
677 public function getTimestamp() {
678 // Check if the field has been filled by WikiPage::setTimestamp()
679 if ( !$this->mTimestamp
) {
680 $this->loadLastEdit();
683 return wfTimestamp( TS_MW
, $this->mTimestamp
);
687 * Set the page timestamp (use only to avoid DB queries)
688 * @param string $ts MW timestamp of last article revision
691 public function setTimestamp( $ts ) {
692 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
696 * @param int $audience One of:
697 * Revision::FOR_PUBLIC to be displayed to all users
698 * Revision::FOR_THIS_USER to be displayed to the given user
699 * Revision::RAW get the text regardless of permissions
700 * @param User $user User object to check for, only if FOR_THIS_USER is passed
701 * to the $audience parameter
702 * @return int User ID for the user that made the last article revision
704 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
705 $this->loadLastEdit();
706 if ( $this->mLastRevision
) {
707 return $this->mLastRevision
->getUser( $audience, $user );
714 * Get the User object of the user who created the page
715 * @param int $audience One of:
716 * Revision::FOR_PUBLIC to be displayed to all users
717 * Revision::FOR_THIS_USER to be displayed to the given user
718 * Revision::RAW get the text regardless of permissions
719 * @param User $user User object to check for, only if FOR_THIS_USER is passed
720 * to the $audience parameter
723 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
724 $revision = $this->getOldestRevision();
726 $userName = $revision->getUserText( $audience, $user );
727 return User
::newFromName( $userName, false );
734 * @param int $audience One of:
735 * Revision::FOR_PUBLIC to be displayed to all users
736 * Revision::FOR_THIS_USER to be displayed to the given user
737 * Revision::RAW get the text regardless of permissions
738 * @param User $user User object to check for, only if FOR_THIS_USER is passed
739 * to the $audience parameter
740 * @return string Username of the user that made the last article revision
742 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
743 $this->loadLastEdit();
744 if ( $this->mLastRevision
) {
745 return $this->mLastRevision
->getUserText( $audience, $user );
752 * @param int $audience One of:
753 * Revision::FOR_PUBLIC to be displayed to all users
754 * Revision::FOR_THIS_USER to be displayed to the given user
755 * Revision::RAW get the text regardless of permissions
756 * @param User $user User object to check for, only if FOR_THIS_USER is passed
757 * to the $audience parameter
758 * @return string Comment stored for the last article revision
760 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
761 $this->loadLastEdit();
762 if ( $this->mLastRevision
) {
763 return $this->mLastRevision
->getComment( $audience, $user );
770 * Returns true if last revision was marked as "minor edit"
772 * @return bool Minor edit indicator for the last article revision.
774 public function getMinorEdit() {
775 $this->loadLastEdit();
776 if ( $this->mLastRevision
) {
777 return $this->mLastRevision
->isMinor();
784 * Determine whether a page would be suitable for being counted as an
785 * article in the site_stats table based on the title & its content
787 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
788 * if false, the current database state will be used
791 public function isCountable( $editInfo = false ) {
792 global $wgArticleCountMethod;
794 if ( !$this->mTitle
->isContentPage() ) {
799 $content = $editInfo->pstContent
;
801 $content = $this->getContent();
804 if ( !$content ||
$content->isRedirect() ) {
810 if ( $wgArticleCountMethod === 'link' ) {
811 // nasty special case to avoid re-parsing to detect links
814 // ParserOutput::getLinks() is a 2D array of page links, so
815 // to be really correct we would need to recurse in the array
816 // but the main array should only have items in it if there are
818 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
820 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
821 [ 'pl_from' => $this->getId() ], __METHOD__
);
825 return $content->isCountable( $hasLinks );
829 * If this page is a redirect, get its target
831 * The target will be fetched from the redirect table if possible.
832 * If this page doesn't have an entry there, call insertRedirect()
833 * @return Title|null Title object, or null if this page is not a redirect
835 public function getRedirectTarget() {
836 if ( !$this->mTitle
->isRedirect() ) {
840 if ( $this->mRedirectTarget
!== null ) {
841 return $this->mRedirectTarget
;
844 // Query the redirect table
845 $dbr = wfGetDB( DB_REPLICA
);
846 $row = $dbr->selectRow( 'redirect',
847 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
848 [ 'rd_from' => $this->getId() ],
852 // rd_fragment and rd_interwiki were added later, populate them if empty
853 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
854 $this->mRedirectTarget
= Title
::makeTitle(
855 $row->rd_namespace
, $row->rd_title
,
856 $row->rd_fragment
, $row->rd_interwiki
858 return $this->mRedirectTarget
;
861 // This page doesn't have an entry in the redirect table
862 $this->mRedirectTarget
= $this->insertRedirect();
863 return $this->mRedirectTarget
;
867 * Insert an entry for this page into the redirect table if the content is a redirect
869 * The database update will be deferred via DeferredUpdates
871 * Don't call this function directly unless you know what you're doing.
872 * @return Title|null Title object or null if not a redirect
874 public function insertRedirect() {
875 $content = $this->getContent();
876 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
881 // Update the DB post-send if the page has not cached since now
882 $latest = $this->getLatest();
883 DeferredUpdates
::addCallableUpdate(
884 function () use ( $retval, $latest ) {
885 $this->insertRedirectEntry( $retval, $latest );
887 DeferredUpdates
::POSTSEND
,
895 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
896 * @param Title $rt Redirect target
897 * @param int|null $oldLatest Prior page_latest for check and set
899 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
900 $dbw = wfGetDB( DB_MASTER
);
901 $dbw->startAtomic( __METHOD__
);
903 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
907 'rd_from' => $this->getId(),
908 'rd_namespace' => $rt->getNamespace(),
909 'rd_title' => $rt->getDBkey(),
910 'rd_fragment' => $rt->getFragment(),
911 'rd_interwiki' => $rt->getInterwiki(),
915 'rd_namespace' => $rt->getNamespace(),
916 'rd_title' => $rt->getDBkey(),
917 'rd_fragment' => $rt->getFragment(),
918 'rd_interwiki' => $rt->getInterwiki(),
924 $dbw->endAtomic( __METHOD__
);
928 * Get the Title object or URL this page redirects to
930 * @return bool|Title|string False, Title of in-wiki target, or string with URL
932 public function followRedirect() {
933 return $this->getRedirectURL( $this->getRedirectTarget() );
937 * Get the Title object or URL to use for a redirect. We use Title
938 * objects for same-wiki, non-special redirects and URLs for everything
940 * @param Title $rt Redirect target
941 * @return bool|Title|string False, Title object of local target, or string with URL
943 public function getRedirectURL( $rt ) {
948 if ( $rt->isExternal() ) {
949 if ( $rt->isLocal() ) {
950 // Offsite wikis need an HTTP redirect.
951 // This can be hard to reverse and may produce loops,
952 // so they may be disabled in the site configuration.
953 $source = $this->mTitle
->getFullURL( 'redirect=no' );
954 return $rt->getFullURL( [ 'rdfrom' => $source ] );
956 // External pages without "local" bit set are not valid
962 if ( $rt->isSpecialPage() ) {
963 // Gotta handle redirects to special pages differently:
964 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
965 // Some pages are not valid targets.
966 if ( $rt->isValidRedirectTarget() ) {
967 return $rt->getFullURL();
977 * Get a list of users who have edited this article, not including the user who made
978 * the most recent revision, which you can get from $article->getUser() if you want it
979 * @return UserArrayFromResult
981 public function getContributors() {
982 // @todo FIXME: This is expensive; cache this info somewhere.
984 $dbr = wfGetDB( DB_REPLICA
);
986 if ( $dbr->implicitGroupby() ) {
987 $realNameField = 'user_real_name';
989 $realNameField = 'MIN(user_real_name) AS user_real_name';
992 $tables = [ 'revision', 'user' ];
995 'user_id' => 'rev_user',
996 'user_name' => 'rev_user_text',
998 'timestamp' => 'MAX(rev_timestamp)',
1001 $conds = [ 'rev_page' => $this->getId() ];
1003 // The user who made the top revision gets credited as "this page was last edited by
1004 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1005 $user = $this->getUser();
1007 $conds[] = "rev_user != $user";
1009 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1013 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1016 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1020 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1021 'ORDER BY' => 'timestamp DESC',
1024 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1025 return new UserArrayFromResult( $res );
1029 * Should the parser cache be used?
1031 * @param ParserOptions $parserOptions ParserOptions to check
1035 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1036 return $parserOptions->getStubThreshold() == 0
1038 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1039 && $this->getContentHandler()->isParserCacheSupported();
1043 * Get a ParserOutput for the given ParserOptions and revision ID.
1045 * The parser cache will be used if possible. Cache misses that result
1046 * in parser runs are debounced with PoolCounter.
1049 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1050 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1051 * get the current revision (default value)
1052 * @param bool $forceParse Force reindexing, regardless of cache settings
1053 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1055 public function getParserOutput(
1056 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1059 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1061 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1062 throw new InvalidArgumentException(
1063 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1067 wfDebug( __METHOD__
.
1068 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1069 if ( $parserOptions->getStubThreshold() ) {
1070 wfIncrStats( 'pcache.miss.stub' );
1073 if ( $useParserCache ) {
1074 $parserOutput = MediaWikiServices
::getInstance()->getParserCache()
1075 ->get( $this, $parserOptions );
1076 if ( $parserOutput !== false ) {
1077 return $parserOutput;
1081 if ( $oldid === null ||
$oldid === 0 ) {
1082 $oldid = $this->getLatest();
1085 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1088 return $pool->getParserOutput();
1092 * Do standard deferred updates after page view (existing or missing page)
1093 * @param User $user The relevant user
1094 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1096 public function doViewUpdates( User
$user, $oldid = 0 ) {
1097 if ( wfReadOnly() ) {
1101 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1102 // Update newtalk / watchlist notification status
1104 $user->clearNotification( $this->mTitle
, $oldid );
1105 } catch ( DBError
$e ) {
1106 // Avoid outage if the master is not reachable
1107 MWExceptionHandler
::logException( $e );
1112 * Perform the actions of a page purging
1114 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1115 * controlled how much purging was done.
1117 public function doPurge() {
1118 // Avoid PHP 7.1 warning of passing $this by reference
1121 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1125 $this->mTitle
->invalidateCache();
1128 HTMLFileCache
::clearFileCache( $this->getTitle() );
1129 // Send purge after above page_touched update was committed
1130 DeferredUpdates
::addUpdate(
1131 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1132 DeferredUpdates
::PRESEND
1135 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1136 $messageCache = MessageCache
::singleton();
1137 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1144 * Get the last time a user explicitly purged the page via action=purge
1146 * @return string|bool TS_MW timestamp or false
1148 * @deprecated since 1.29. It will always return false.
1150 public function getLastPurgeTimestamp() {
1151 wfDeprecated( __METHOD__
, '1.29' );
1156 * Insert a new empty page record for this article.
1157 * This *must* be followed up by creating a revision
1158 * and running $this->updateRevisionOn( ... );
1159 * or else the record will be left in a funky state.
1160 * Best if all done inside a transaction.
1162 * @param IDatabase $dbw
1163 * @param int|null $pageId Custom page ID that will be used for the insert statement
1165 * @return bool|int The newly created page_id key; false if the row was not
1166 * inserted, e.g. because the title already existed or because the specified
1167 * page ID is already in use.
1169 public function insertOn( $dbw, $pageId = null ) {
1170 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1174 'page_namespace' => $this->mTitle
->getNamespace(),
1175 'page_title' => $this->mTitle
->getDBkey(),
1176 'page_restrictions' => '',
1177 'page_is_redirect' => 0, // Will set this shortly...
1179 'page_random' => wfRandom(),
1180 'page_touched' => $dbw->timestamp(),
1181 'page_latest' => 0, // Fill this in shortly...
1182 'page_len' => 0, // Fill this in shortly...
1183 ] +
$pageIdForInsert,
1188 if ( $dbw->affectedRows() > 0 ) {
1189 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1190 $this->mId
= $newid;
1191 $this->mTitle
->resetArticleID( $newid );
1195 return false; // nothing changed
1200 * Update the page record to point to a newly saved revision.
1202 * @param IDatabase $dbw
1203 * @param Revision $revision For ID number, and text used to set
1204 * length and redirect status fields
1205 * @param int $lastRevision If given, will not overwrite the page field
1206 * when different from the currently set value.
1207 * Giving 0 indicates the new page flag should be set on.
1208 * @param bool $lastRevIsRedirect If given, will optimize adding and
1209 * removing rows in redirect table.
1210 * @return bool Success; false if the page row was missing or page_latest changed
1212 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1213 $lastRevIsRedirect = null
1215 global $wgContentHandlerUseDB;
1217 // Assertion to try to catch T92046
1218 if ( (int)$revision->getId() === 0 ) {
1219 throw new InvalidArgumentException(
1220 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1224 $content = $revision->getContent();
1225 $len = $content ?
$content->getSize() : 0;
1226 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1228 $conditions = [ 'page_id' => $this->getId() ];
1230 if ( !is_null( $lastRevision ) ) {
1231 // An extra check against threads stepping on each other
1232 $conditions['page_latest'] = $lastRevision;
1236 'page_latest' => $revision->getId(),
1237 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1238 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1239 'page_is_redirect' => $rt !== null ?
1 : 0,
1243 if ( $wgContentHandlerUseDB ) {
1244 $row['page_content_model'] = $revision->getContentModel();
1247 $dbw->update( 'page',
1252 $result = $dbw->affectedRows() > 0;
1254 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1255 $this->setLastEdit( $revision );
1256 $this->mLatest
= $revision->getId();
1257 $this->mIsRedirect
= (bool)$rt;
1258 // Update the LinkCache.
1259 LinkCache
::singleton()->addGoodLinkObj(
1265 $revision->getContentModel()
1273 * Add row to the redirect table if this is a redirect, remove otherwise.
1275 * @param IDatabase $dbw
1276 * @param Title $redirectTitle Title object pointing to the redirect target,
1277 * or NULL if this is not a redirect
1278 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1279 * removing rows in redirect table.
1280 * @return bool True on success, false on failure
1283 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1284 // Always update redirects (target link might have changed)
1285 // Update/Insert if we don't know if the last revision was a redirect or not
1286 // Delete if changing from redirect to non-redirect
1287 $isRedirect = !is_null( $redirectTitle );
1289 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1293 if ( $isRedirect ) {
1294 $this->insertRedirectEntry( $redirectTitle );
1296 // This is not a redirect, remove row from redirect table
1297 $where = [ 'rd_from' => $this->getId() ];
1298 $dbw->delete( 'redirect', $where, __METHOD__
);
1301 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1302 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1305 return ( $dbw->affectedRows() != 0 );
1309 * If the given revision is newer than the currently set page_latest,
1310 * update the page record. Otherwise, do nothing.
1312 * @deprecated since 1.24, use updateRevisionOn instead
1314 * @param IDatabase $dbw
1315 * @param Revision $revision
1318 public function updateIfNewerOn( $dbw, $revision ) {
1319 $row = $dbw->selectRow(
1320 [ 'revision', 'page' ],
1321 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1323 'page_id' => $this->getId(),
1324 'page_latest=rev_id' ],
1328 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1331 $prev = $row->rev_id
;
1332 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1334 // No or missing previous revision; mark the page as new
1336 $lastRevIsRedirect = null;
1339 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1345 * Get the content that needs to be saved in order to undo all revisions
1346 * between $undo and $undoafter. Revisions must belong to the same page,
1347 * must exist and must not be deleted
1348 * @param Revision $undo
1349 * @param Revision $undoafter Must be an earlier revision than $undo
1350 * @return Content|bool Content on success, false on failure
1352 * Before we had the Content object, this was done in getUndoText
1354 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1355 $handler = $undo->getContentHandler();
1356 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1360 * Returns true if this page's content model supports sections.
1364 * @todo The skin should check this and not offer section functionality if
1365 * sections are not supported.
1366 * @todo The EditPage should check this and not offer section functionality
1367 * if sections are not supported.
1369 public function supportsSections() {
1370 return $this->getContentHandler()->supportsSections();
1374 * @param string|int|null|bool $sectionId Section identifier as a number or string
1375 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1376 * or 'new' for a new section.
1377 * @param Content $sectionContent New content of the section.
1378 * @param string $sectionTitle New section's subject, only if $section is "new".
1379 * @param string $edittime Revision timestamp or null to use the current revision.
1381 * @throws MWException
1382 * @return Content|null New complete article content, or null if error.
1385 * @deprecated since 1.24, use replaceSectionAtRev instead
1387 public function replaceSectionContent(
1388 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1391 if ( $edittime && $sectionId !== 'new' ) {
1392 $dbr = wfGetDB( DB_REPLICA
);
1393 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1394 // Try the master if this thread may have just added it.
1395 // This could be abstracted into a Revision method, but we don't want
1396 // to encourage loading of revisions by timestamp.
1398 && wfGetLB()->getServerCount() > 1
1399 && wfGetLB()->hasOrMadeRecentMasterChanges()
1401 $dbw = wfGetDB( DB_MASTER
);
1402 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1405 $baseRevId = $rev->getId();
1409 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1413 * @param string|int|null|bool $sectionId Section identifier as a number or string
1414 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1415 * or 'new' for a new section.
1416 * @param Content $sectionContent New content of the section.
1417 * @param string $sectionTitle New section's subject, only if $section is "new".
1418 * @param int|null $baseRevId
1420 * @throws MWException
1421 * @return Content|null New complete article content, or null if error.
1425 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1426 $sectionTitle = '', $baseRevId = null
1428 if ( strval( $sectionId ) === '' ) {
1429 // Whole-page edit; let the whole text through
1430 $newContent = $sectionContent;
1432 if ( !$this->supportsSections() ) {
1433 throw new MWException( "sections not supported for content model " .
1434 $this->getContentHandler()->getModelID() );
1437 // T32711: always use current version when adding a new section
1438 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1439 $oldContent = $this->getContent();
1441 $rev = Revision
::newFromId( $baseRevId );
1443 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1444 $this->getId() . "; section: $sectionId)\n" );
1448 $oldContent = $rev->getContent();
1451 if ( !$oldContent ) {
1452 wfDebug( __METHOD__
. ": no page text\n" );
1456 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1463 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1465 * @return int Updated $flags
1467 public function checkFlags( $flags ) {
1468 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1469 if ( $this->exists() ) {
1470 $flags |
= EDIT_UPDATE
;
1480 * Change an existing article or create a new article. Updates RC and all necessary caches,
1481 * optionally via the deferred update array.
1483 * @param Content $content New content
1484 * @param string $summary Edit summary
1485 * @param int $flags Bitfield:
1487 * Article is known or assumed to be non-existent, create a new one
1489 * Article is known or assumed to be pre-existing, update it
1491 * Mark this edit minor, if the user is allowed to do so
1493 * Do not log the change in recentchanges
1495 * Mark the edit a "bot" edit regardless of user rights
1497 * Fill in blank summaries with generated text where possible
1499 * Signal that the page retrieve/save cycle happened entirely in this request.
1501 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1502 * article will be detected. If EDIT_UPDATE is specified and the article
1503 * doesn't exist, the function will return an edit-gone-missing error. If
1504 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1505 * error will be returned. These two conditions are also possible with
1506 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1508 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1509 * This is not the parent revision ID, rather the revision ID for older
1510 * content used as the source for a rollback, for example.
1511 * @param User $user The user doing the edit
1512 * @param string $serialFormat Format for storing the content in the
1514 * @param array|null $tags Change tags to apply to this edit
1515 * Callers are responsible for permission checks
1516 * (with ChangeTags::canAddTagsAccompanyingChange)
1517 * @param Int $undidRevId Id of revision that was undone or 0
1519 * @throws MWException
1520 * @return Status Possible errors:
1521 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1522 * set the fatal flag of $status.
1523 * edit-gone-missing: In update mode, but the article didn't exist.
1524 * edit-conflict: In update mode, the article changed unexpectedly.
1525 * edit-no-change: Warning that the text was the same as before.
1526 * edit-already-exists: In creation mode, but the article already exists.
1528 * Extensions may define additional errors.
1530 * $return->value will contain an associative array with members as follows:
1531 * new: Boolean indicating if the function attempted to create a new article.
1532 * revision: The revision object for the inserted revision, or null.
1535 * @throws MWException
1537 public function doEditContent(
1538 Content
$content, $summary, $flags = 0, $baseRevId = false,
1539 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1541 global $wgUser, $wgUseAutomaticEditSummaries;
1543 // Old default parameter for $tags was null
1544 if ( $tags === null ) {
1548 // Low-level sanity check
1549 if ( $this->mTitle
->getText() === '' ) {
1550 throw new MWException( 'Something is trying to edit an article with an empty title' );
1552 // Make sure the given content type is allowed for this page
1553 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1554 return Status
::newFatal( 'content-not-allowed-here',
1555 ContentHandler
::getLocalizedName( $content->getModel() ),
1556 $this->mTitle
->getPrefixedText()
1560 // Load the data from the master database if needed.
1561 // The caller may already loaded it from the master or even loaded it using
1562 // SELECT FOR UPDATE, so do not override that using clear().
1563 $this->loadPageData( 'fromdbmaster' );
1565 $user = $user ?
: $wgUser;
1566 $flags = $this->checkFlags( $flags );
1568 // Avoid PHP 7.1 warning of passing $this by reference
1571 // Trigger pre-save hook (using provided edit summary)
1572 $hookStatus = Status
::newGood( [] );
1573 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1574 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1575 // Check if the hook rejected the attempted save
1576 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1577 if ( $hookStatus->isOK() ) {
1578 // Hook returned false but didn't call fatal(); use generic message
1579 $hookStatus->fatal( 'edit-hook-aborted' );
1585 $old_revision = $this->getRevision(); // current revision
1586 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1588 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1589 $tags[] = 'mw-contentmodelchange';
1592 // Provide autosummaries if one is not provided and autosummaries are enabled
1593 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1594 $handler = $content->getContentHandler();
1595 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1598 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1599 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1605 // Get the pre-save transform content and final parser output
1606 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1607 $pstContent = $editInfo->pstContent
; // Content object
1609 'bot' => ( $flags & EDIT_FORCE_BOT
),
1610 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1611 'serialized' => $pstContent->serialize( $serialFormat ),
1612 'serialFormat' => $serialFormat,
1613 'baseRevId' => $baseRevId,
1614 'oldRevision' => $old_revision,
1615 'oldContent' => $old_content,
1616 'oldId' => $this->getLatest(),
1617 'oldIsRedirect' => $this->isRedirect(),
1618 'oldCountable' => $this->isCountable(),
1619 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1620 'undidRevId' => $undidRevId
1623 // Actually create the revision and create/update the page
1624 if ( $flags & EDIT_UPDATE
) {
1625 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1627 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1630 // Promote user to any groups they meet the criteria for
1631 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1632 $user->addAutopromoteOnceGroups( 'onEdit' );
1633 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1640 * @param Content $content Pre-save transform content
1643 * @param string $summary
1644 * @param array $meta
1646 * @throws DBUnexpectedError
1648 * @throws FatalError
1649 * @throws MWException
1651 private function doModify(
1652 Content
$content, $flags, User
$user, $summary, array $meta
1654 global $wgUseRCPatrol;
1656 // Update article, but only if changed.
1657 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1659 // Convenience variables
1660 $now = wfTimestampNow();
1661 $oldid = $meta['oldId'];
1662 /** @var Content|null $oldContent */
1663 $oldContent = $meta['oldContent'];
1664 $newsize = $content->getSize();
1667 // Article gone missing
1668 $status->fatal( 'edit-gone-missing' );
1671 } elseif ( !$oldContent ) {
1672 // Sanity check for T39225
1673 throw new MWException( "Could not find text for current revision {$oldid}." );
1676 // @TODO: pass content object?!
1677 $revision = new Revision( [
1678 'page' => $this->getId(),
1679 'title' => $this->mTitle
, // for determining the default content model
1680 'comment' => $summary,
1681 'minor_edit' => $meta['minor'],
1682 'text' => $meta['serialized'],
1684 'parent_id' => $oldid,
1685 'user' => $user->getId(),
1686 'user_text' => $user->getName(),
1687 'timestamp' => $now,
1688 'content_model' => $content->getModel(),
1689 'content_format' => $meta['serialFormat'],
1692 $changed = !$content->equals( $oldContent );
1694 $dbw = wfGetDB( DB_MASTER
);
1697 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1698 $status->merge( $prepStatus );
1699 if ( !$status->isOK() ) {
1703 $dbw->startAtomic( __METHOD__
);
1704 // Get the latest page_latest value while locking it.
1705 // Do a CAS style check to see if it's the same as when this method
1706 // started. If it changed then bail out before touching the DB.
1707 $latestNow = $this->lockAndGetLatest();
1708 if ( $latestNow != $oldid ) {
1709 $dbw->endAtomic( __METHOD__
);
1710 // Page updated or deleted in the mean time
1711 $status->fatal( 'edit-conflict' );
1716 // At this point we are now comitted to returning an OK
1717 // status unless some DB query error or other exception comes up.
1718 // This way callers don't have to call rollback() if $status is bad
1719 // unless they actually try to catch exceptions (which is rare).
1721 // Save the revision text
1722 $revisionId = $revision->insertOn( $dbw );
1723 // Update page_latest and friends to reflect the new revision
1724 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1725 throw new MWException( "Failed to update page row to use new revision." );
1728 Hooks
::run( 'NewRevisionFromEditComplete',
1729 [ $this, $revision, $meta['baseRevId'], $user ] );
1731 // Update recentchanges
1732 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1733 // Mark as patrolled if the user can do so
1734 $patrolled = $wgUseRCPatrol && !count(
1735 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1736 // Add RC row to the DB
1737 RecentChange
::notifyEdit(
1740 $revision->isMinor(),
1744 $this->getTimestamp(),
1747 $oldContent ?
$oldContent->getSize() : 0,
1755 $user->incEditCount();
1757 $dbw->endAtomic( __METHOD__
);
1758 $this->mTimestamp
= $now;
1760 // T34948: revision ID must be set to page {{REVISIONID}} and
1761 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1762 $revision->setId( $this->getLatest() );
1763 $revision->setUserIdAndName(
1764 $this->getUser( Revision
::RAW
),
1765 $this->getUserText( Revision
::RAW
)
1770 // Return the new revision to the caller
1771 $status->value
['revision'] = $revision;
1773 $status->warning( 'edit-no-change' );
1774 // Update page_touched as updateRevisionOn() was not called.
1775 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1776 $this->mTitle
->invalidateCache( $now );
1779 // Do secondary updates once the main changes have been committed...
1780 DeferredUpdates
::addUpdate(
1781 new AtomicSectionUpdate(
1785 $revision, &$user, $content, $summary, &$flags,
1786 $changed, $meta, &$status
1788 // Update links tables, site stats, etc.
1789 $this->doEditUpdates(
1793 'changed' => $changed,
1794 'oldcountable' => $meta['oldCountable'],
1795 'oldrevision' => $meta['oldRevision']
1798 // Avoid PHP 7.1 warning of passing $this by reference
1800 // Trigger post-save hook
1801 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1802 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1803 $meta['undidRevId'] ];
1804 Hooks
::run( 'PageContentSaveComplete', $params );
1807 DeferredUpdates
::PRESEND
1814 * @param Content $content Pre-save transform content
1817 * @param string $summary
1818 * @param array $meta
1820 * @throws DBUnexpectedError
1822 * @throws FatalError
1823 * @throws MWException
1825 private function doCreate(
1826 Content
$content, $flags, User
$user, $summary, array $meta
1828 global $wgUseRCPatrol, $wgUseNPPatrol;
1830 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1832 $now = wfTimestampNow();
1833 $newsize = $content->getSize();
1834 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1835 $status->merge( $prepStatus );
1836 if ( !$status->isOK() ) {
1840 $dbw = wfGetDB( DB_MASTER
);
1841 $dbw->startAtomic( __METHOD__
);
1843 // Add the page record unless one already exists for the title
1844 $newid = $this->insertOn( $dbw );
1845 if ( $newid === false ) {
1846 $dbw->endAtomic( __METHOD__
); // nothing inserted
1847 $status->fatal( 'edit-already-exists' );
1849 return $status; // nothing done
1852 // At this point we are now comitted to returning an OK
1853 // status unless some DB query error or other exception comes up.
1854 // This way callers don't have to call rollback() if $status is bad
1855 // unless they actually try to catch exceptions (which is rare).
1857 // @TODO: pass content object?!
1858 $revision = new Revision( [
1860 'title' => $this->mTitle
, // for determining the default content model
1861 'comment' => $summary,
1862 'minor_edit' => $meta['minor'],
1863 'text' => $meta['serialized'],
1865 'user' => $user->getId(),
1866 'user_text' => $user->getName(),
1867 'timestamp' => $now,
1868 'content_model' => $content->getModel(),
1869 'content_format' => $meta['serialFormat'],
1872 // Save the revision text...
1873 $revisionId = $revision->insertOn( $dbw );
1874 // Update the page record with revision data
1875 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1876 throw new MWException( "Failed to update page row to use new revision." );
1879 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1881 // Update recentchanges
1882 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1883 // Mark as patrolled if the user can do so
1884 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1885 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1886 // Add RC row to the DB
1887 RecentChange
::notifyNew(
1890 $revision->isMinor(),
1902 $user->incEditCount();
1904 $dbw->endAtomic( __METHOD__
);
1905 $this->mTimestamp
= $now;
1907 // Return the new revision to the caller
1908 $status->value
['revision'] = $revision;
1910 // Do secondary updates once the main changes have been committed...
1911 DeferredUpdates
::addUpdate(
1912 new AtomicSectionUpdate(
1916 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1918 // Update links, etc.
1919 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1920 // Avoid PHP 7.1 warning of passing $this by reference
1922 // Trigger post-create hook
1923 $params = [ &$wikiPage, &$user, $content, $summary,
1924 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1925 Hooks
::run( 'PageContentInsertComplete', $params );
1926 // Trigger post-save hook
1927 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1928 Hooks
::run( 'PageContentSaveComplete', $params );
1931 DeferredUpdates
::PRESEND
1938 * Get parser options suitable for rendering the primary article wikitext
1940 * @see ContentHandler::makeParserOptions
1942 * @param IContextSource|User|string $context One of the following:
1943 * - IContextSource: Use the User and the Language of the provided
1945 * - User: Use the provided User object and $wgLang for the language,
1946 * so use an IContextSource object if possible.
1947 * - 'canonical': Canonical options (anonymous user with default
1948 * preferences and content language).
1949 * @return ParserOptions
1951 public function makeParserOptions( $context ) {
1952 $options = $this->getContentHandler()->makeParserOptions( $context );
1954 if ( $this->getTitle()->isConversionTable() ) {
1955 // @todo ConversionTable should become a separate content model, so
1956 // we don't need special cases like this one.
1957 $options->disableContentConversion();
1964 * Prepare content which is about to be saved.
1966 * Prior to 1.30, this returned a stdClass object with the same class
1969 * @param Content $content
1970 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1971 * revision ID is also accepted, but this is deprecated.
1972 * @param User|null $user
1973 * @param string|null $serialFormat
1974 * @param bool $useCache Check shared prepared edit cache
1976 * @return PreparedEdit
1980 public function prepareContentForEdit(
1981 Content
$content, $revision = null, User
$user = null,
1982 $serialFormat = null, $useCache = true
1984 global $wgContLang, $wgUser, $wgAjaxEditStash;
1986 if ( is_object( $revision ) ) {
1987 $revid = $revision->getId();
1990 // This code path is deprecated, and nothing is known to
1991 // use it, so performance here shouldn't be a worry.
1992 if ( $revid !== null ) {
1993 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
1999 $user = is_null( $user ) ?
$wgUser : $user;
2000 // XXX: check $user->getId() here???
2002 // Use a sane default for $serialFormat, see T59026
2003 if ( $serialFormat === null ) {
2004 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2007 if ( $this->mPreparedEdit
2008 && isset( $this->mPreparedEdit
->newContent
)
2009 && $this->mPreparedEdit
->newContent
->equals( $content )
2010 && $this->mPreparedEdit
->revid
== $revid
2011 && $this->mPreparedEdit
->format
== $serialFormat
2012 // XXX: also check $user here?
2015 return $this->mPreparedEdit
;
2018 // The edit may have already been prepared via api.php?action=stashedit
2019 $cachedEdit = $useCache && $wgAjaxEditStash
2020 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2023 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2024 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2026 $edit = new PreparedEdit();
2027 if ( $cachedEdit ) {
2028 $edit->timestamp
= $cachedEdit->timestamp
;
2030 $edit->timestamp
= wfTimestampNow();
2032 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2033 $edit->revid
= $revid;
2035 if ( $cachedEdit ) {
2036 $edit->pstContent
= $cachedEdit->pstContent
;
2038 $edit->pstContent
= $content
2039 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2043 $edit->format
= $serialFormat;
2044 $edit->popts
= $this->makeParserOptions( 'canonical' );
2045 if ( $cachedEdit ) {
2046 $edit->output
= $cachedEdit->output
;
2049 // We get here if vary-revision is set. This means that this page references
2050 // itself (such as via self-transclusion). In this case, we need to make sure
2051 // that any such self-references refer to the newly-saved revision, and not
2052 // to the previous one, which could otherwise happen due to replica DB lag.
2053 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2054 $edit->popts
->setCurrentRevisionCallback(
2055 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2056 if ( $title->equals( $revision->getTitle() ) ) {
2059 return call_user_func( $oldCallback, $title, $parser );
2064 // Try to avoid a second parse if {{REVISIONID}} is used
2065 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2066 ? DB_MASTER
// use the best possible guess
2067 : DB_REPLICA
; // T154554
2069 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2070 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2078 $edit->output
= $edit->pstContent
2079 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2083 $edit->newContent
= $content;
2084 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2086 // NOTE: B/C for hooks! don't use these fields!
2087 $edit->newText
= $edit->newContent
2088 ? ContentHandler
::getContentText( $edit->newContent
)
2090 $edit->oldText
= $edit->oldContent
2091 ? ContentHandler
::getContentText( $edit->oldContent
)
2093 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2095 if ( $edit->output
) {
2096 $edit->output
->setCacheTime( wfTimestampNow() );
2099 // Process cache the result
2100 $this->mPreparedEdit
= $edit;
2106 * Do standard deferred updates after page edit.
2107 * Update links tables, site stats, search index and message cache.
2108 * Purges pages that include this page if the text was changed here.
2109 * Every 100th edit, prune the recent changes table.
2111 * @param Revision $revision
2112 * @param User $user User object that did the revision
2113 * @param array $options Array of options, following indexes are used:
2114 * - changed: bool, whether the revision changed the content (default true)
2115 * - created: bool, whether the revision created the page (default false)
2116 * - moved: bool, whether the page was moved (default false)
2117 * - restored: bool, whether the page was undeleted (default false)
2118 * - oldrevision: Revision object for the pre-update revision (default null)
2119 * - oldcountable: bool, null, or string 'no-change' (default null):
2120 * - bool: whether the page was counted as an article before that
2121 * revision, only used in changed is true and created is false
2122 * - null: if created is false, don't update the article count; if created
2123 * is true, do update the article count
2124 * - 'no-change': don't update the article count, ever
2126 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2127 global $wgRCWatchCategoryMembership;
2133 'restored' => false,
2134 'oldrevision' => null,
2135 'oldcountable' => null
2137 $content = $revision->getContent();
2139 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2141 // See if the parser output before $revision was inserted is still valid
2143 if ( !$this->mPreparedEdit
) {
2144 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2145 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2146 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2147 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2148 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2150 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2151 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2152 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2154 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2155 $editInfo = $this->mPreparedEdit
;
2159 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2160 // $text is usually already pre-save transformed once. Avoid using the edit stash
2161 // as any prepared content from there or in doEditContent() was already rejected.
2162 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2165 // Save it to the parser cache.
2166 // Make sure the cache time matches page_touched to avoid double parsing.
2167 MediaWikiServices
::getInstance()->getParserCache()->save(
2168 $editInfo->output
, $this, $editInfo->popts
,
2169 $revision->getTimestamp(), $editInfo->revid
2172 // Update the links tables and other secondary data
2174 $recursive = $options['changed']; // T52785
2175 $updates = $content->getSecondaryDataUpdates(
2176 $this->getTitle(), null, $recursive, $editInfo->output
2178 foreach ( $updates as $update ) {
2179 if ( $update instanceof LinksUpdate
) {
2180 $update->setRevision( $revision );
2181 $update->setTriggeringUser( $user );
2183 DeferredUpdates
::addUpdate( $update );
2185 if ( $wgRCWatchCategoryMembership
2186 && $this->getContentHandler()->supportsCategories() === true
2187 && ( $options['changed'] ||
$options['created'] )
2188 && !$options['restored']
2190 // Note: jobs are pushed after deferred updates, so the job should be able to see
2191 // the recent change entry (also done via deferred updates) and carry over any
2192 // bot/deletion/IP flags, ect.
2193 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2196 'pageId' => $this->getId(),
2197 'revTimestamp' => $revision->getTimestamp()
2203 // Avoid PHP 7.1 warning of passing $this by reference
2206 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2208 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2209 // Flush old entries from the `recentchanges` table
2210 if ( mt_rand( 0, 9 ) == 0 ) {
2211 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2215 if ( !$this->exists() ) {
2219 $id = $this->getId();
2220 $title = $this->mTitle
->getPrefixedDBkey();
2221 $shortTitle = $this->mTitle
->getDBkey();
2223 if ( $options['oldcountable'] === 'no-change' ||
2224 ( !$options['changed'] && !$options['moved'] )
2227 } elseif ( $options['created'] ) {
2228 $good = (int)$this->isCountable( $editInfo );
2229 } elseif ( $options['oldcountable'] !== null ) {
2230 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2234 $edits = $options['changed'] ?
1 : 0;
2235 $total = $options['created'] ?
1 : 0;
2237 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2238 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2240 // If this is another user's talk page, update newtalk.
2241 // Don't do this if $options['changed'] = false (null-edits) nor if
2242 // it's a minor edit and the user doesn't want notifications for those.
2243 if ( $options['changed']
2244 && $this->mTitle
->getNamespace() == NS_USER_TALK
2245 && $shortTitle != $user->getTitleKey()
2246 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2248 $recipient = User
::newFromName( $shortTitle, false );
2249 if ( !$recipient ) {
2250 wfDebug( __METHOD__
. ": invalid username\n" );
2252 // Avoid PHP 7.1 warning of passing $this by reference
2255 // Allow extensions to prevent user notification
2256 // when a new message is added to their talk page
2257 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2258 if ( User
::isIP( $shortTitle ) ) {
2259 // An anonymous user
2260 $recipient->setNewtalk( true, $revision );
2261 } elseif ( $recipient->isLoggedIn() ) {
2262 $recipient->setNewtalk( true, $revision );
2264 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2270 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2271 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2274 if ( $options['created'] ) {
2275 self
::onArticleCreate( $this->mTitle
);
2276 } elseif ( $options['changed'] ) { // T52785
2277 self
::onArticleEdit( $this->mTitle
, $revision );
2280 ResourceLoaderWikiModule
::invalidateModuleCache(
2281 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2286 * Update the article's restriction field, and leave a log entry.
2287 * This works for protection both existing and non-existing pages.
2289 * @param array $limit Set of restriction keys
2290 * @param array $expiry Per restriction type expiration
2291 * @param int &$cascade Set to false if cascading protection isn't allowed.
2292 * @param string $reason
2293 * @param User $user The user updating the restrictions
2294 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2295 * ($user should be able to add the specified tags before this is called)
2296 * @return Status Status object; if action is taken, $status->value is the log_id of the
2297 * protection log entry.
2299 public function doUpdateRestrictions( array $limit, array $expiry,
2300 &$cascade, $reason, User
$user, $tags = null
2302 global $wgCascadingRestrictionLevels;
2304 if ( wfReadOnly() ) {
2305 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2308 $this->loadPageData( 'fromdbmaster' );
2309 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2310 $id = $this->getId();
2316 // Take this opportunity to purge out expired restrictions
2317 Title
::purgeExpiredRestrictions();
2319 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2320 // we expect a single selection, but the schema allows otherwise.
2321 $isProtected = false;
2325 $dbw = wfGetDB( DB_MASTER
);
2327 foreach ( $restrictionTypes as $action ) {
2328 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2329 $expiry[$action] = 'infinity';
2331 if ( !isset( $limit[$action] ) ) {
2332 $limit[$action] = '';
2333 } elseif ( $limit[$action] != '' ) {
2337 // Get current restrictions on $action
2338 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2339 if ( $current != '' ) {
2340 $isProtected = true;
2343 if ( $limit[$action] != $current ) {
2345 } elseif ( $limit[$action] != '' ) {
2346 // Only check expiry change if the action is actually being
2347 // protected, since expiry does nothing on an not-protected
2349 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2355 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2359 // If nothing has changed, do nothing
2361 return Status
::newGood();
2364 if ( !$protect ) { // No protection at all means unprotection
2365 $revCommentMsg = 'unprotectedarticle-comment';
2366 $logAction = 'unprotect';
2367 } elseif ( $isProtected ) {
2368 $revCommentMsg = 'modifiedarticleprotection-comment';
2369 $logAction = 'modify';
2371 $revCommentMsg = 'protectedarticle-comment';
2372 $logAction = 'protect';
2375 $logRelationsValues = [];
2376 $logRelationsField = null;
2377 $logParamsDetails = [];
2379 // Null revision (used for change tag insertion)
2380 $nullRevision = null;
2382 if ( $id ) { // Protection of existing page
2383 // Avoid PHP 7.1 warning of passing $this by reference
2386 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2387 return Status
::newGood();
2390 // Only certain restrictions can cascade...
2391 $editrestriction = isset( $limit['edit'] )
2392 ?
[ $limit['edit'] ]
2393 : $this->mTitle
->getRestrictions( 'edit' );
2394 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2395 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2397 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2398 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2401 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2402 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2403 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2405 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2406 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2409 // The schema allows multiple restrictions
2410 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2414 // insert null revision to identify the page protection change as edit summary
2415 $latest = $this->getLatest();
2416 $nullRevision = $this->insertProtectNullRevision(
2425 if ( $nullRevision === null ) {
2426 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2429 $logRelationsField = 'pr_id';
2431 // Update restrictions table
2432 foreach ( $limit as $action => $restrictions ) {
2434 'page_restrictions',
2437 'pr_type' => $action
2441 if ( $restrictions != '' ) {
2442 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2444 'page_restrictions',
2447 'pr_type' => $action,
2448 'pr_level' => $restrictions,
2449 'pr_cascade' => $cascadeValue,
2450 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2454 $logRelationsValues[] = $dbw->insertId();
2455 $logParamsDetails[] = [
2457 'level' => $restrictions,
2458 'expiry' => $expiry[$action],
2459 'cascade' => (bool)$cascadeValue,
2464 // Clear out legacy restriction fields
2467 [ 'page_restrictions' => '' ],
2468 [ 'page_id' => $id ],
2472 // Avoid PHP 7.1 warning of passing $this by reference
2475 Hooks
::run( 'NewRevisionFromEditComplete',
2476 [ $this, $nullRevision, $latest, $user ] );
2477 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2478 } else { // Protection of non-existing page (also known as "title protection")
2479 // Cascade protection is meaningless in this case
2482 if ( $limit['create'] != '' ) {
2483 $commentFields = CommentStore
::newKey( 'pt_reason' )->insert( $dbw, $reason );
2484 $dbw->replace( 'protected_titles',
2485 [ [ 'pt_namespace', 'pt_title' ] ],
2487 'pt_namespace' => $this->mTitle
->getNamespace(),
2488 'pt_title' => $this->mTitle
->getDBkey(),
2489 'pt_create_perm' => $limit['create'],
2490 'pt_timestamp' => $dbw->timestamp(),
2491 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2492 'pt_user' => $user->getId(),
2493 ] +
$commentFields, __METHOD__
2495 $logParamsDetails[] = [
2497 'level' => $limit['create'],
2498 'expiry' => $expiry['create'],
2501 $dbw->delete( 'protected_titles',
2503 'pt_namespace' => $this->mTitle
->getNamespace(),
2504 'pt_title' => $this->mTitle
->getDBkey()
2510 $this->mTitle
->flushRestrictions();
2511 InfoAction
::invalidateCache( $this->mTitle
);
2513 if ( $logAction == 'unprotect' ) {
2516 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2518 '4::description' => $protectDescriptionLog, // parameter for IRC
2519 '5:bool:cascade' => $cascade,
2520 'details' => $logParamsDetails, // parameter for localize and api
2524 // Update the protection log
2525 $logEntry = new ManualLogEntry( 'protect', $logAction );
2526 $logEntry->setTarget( $this->mTitle
);
2527 $logEntry->setComment( $reason );
2528 $logEntry->setPerformer( $user );
2529 $logEntry->setParameters( $params );
2530 if ( !is_null( $nullRevision ) ) {
2531 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2533 $logEntry->setTags( $tags );
2534 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2535 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2537 $logId = $logEntry->insert();
2538 $logEntry->publish( $logId );
2540 return Status
::newGood( $logId );
2544 * Insert a new null revision for this page.
2546 * @param string $revCommentMsg Comment message key for the revision
2547 * @param array $limit Set of restriction keys
2548 * @param array $expiry Per restriction type expiration
2549 * @param int $cascade Set to false if cascading protection isn't allowed.
2550 * @param string $reason
2551 * @param User|null $user
2552 * @return Revision|null Null on error
2554 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2555 array $expiry, $cascade, $reason, $user = null
2557 $dbw = wfGetDB( DB_MASTER
);
2559 // Prepare a null revision to be added to the history
2560 $editComment = wfMessage(
2562 $this->mTitle
->getPrefixedText(),
2563 $user ?
$user->getName() : ''
2564 )->inContentLanguage()->text();
2566 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2568 $protectDescription = $this->protectDescription( $limit, $expiry );
2569 if ( $protectDescription ) {
2570 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2571 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2572 ->inContentLanguage()->text();
2575 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2576 $editComment .= wfMessage( 'brackets' )->params(
2577 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2578 )->inContentLanguage()->text();
2581 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2583 $nullRev->insertOn( $dbw );
2585 // Update page record and touch page
2586 $oldLatest = $nullRev->getParentId();
2587 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2594 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2597 protected function formatExpiry( $expiry ) {
2600 if ( $expiry != 'infinity' ) {
2603 $wgContLang->timeanddate( $expiry, false, false ),
2604 $wgContLang->date( $expiry, false, false ),
2605 $wgContLang->time( $expiry, false, false )
2606 )->inContentLanguage()->text();
2608 return wfMessage( 'protect-expiry-indefinite' )
2609 ->inContentLanguage()->text();
2614 * Builds the description to serve as comment for the edit.
2616 * @param array $limit Set of restriction keys
2617 * @param array $expiry Per restriction type expiration
2620 public function protectDescription( array $limit, array $expiry ) {
2621 $protectDescription = '';
2623 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2624 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2625 # All possible message keys are listed here for easier grepping:
2626 # * restriction-create
2627 # * restriction-edit
2628 # * restriction-move
2629 # * restriction-upload
2630 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2631 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2632 # with '' filtered out. All possible message keys are listed below:
2633 # * protect-level-autoconfirmed
2634 # * protect-level-sysop
2635 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2636 ->inContentLanguage()->text();
2638 $expiryText = $this->formatExpiry( $expiry[$action] );
2640 if ( $protectDescription !== '' ) {
2641 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2643 $protectDescription .= wfMessage( 'protect-summary-desc' )
2644 ->params( $actionText, $restrictionsText, $expiryText )
2645 ->inContentLanguage()->text();
2648 return $protectDescription;
2652 * Builds the description to serve as comment for the log entry.
2654 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2655 * protect description text. Keep them in old format to avoid breaking compatibility.
2656 * TODO: Fix protection log to store structured description and format it on-the-fly.
2658 * @param array $limit Set of restriction keys
2659 * @param array $expiry Per restriction type expiration
2662 public function protectDescriptionLog( array $limit, array $expiry ) {
2665 $protectDescriptionLog = '';
2667 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2668 $expiryText = $this->formatExpiry( $expiry[$action] );
2669 $protectDescriptionLog .= $wgContLang->getDirMark() .
2670 "[$action=$restrictions] ($expiryText)";
2673 return trim( $protectDescriptionLog );
2677 * Take an array of page restrictions and flatten it to a string
2678 * suitable for insertion into the page_restrictions field.
2680 * @param string[] $limit
2682 * @throws MWException
2685 protected static function flattenRestrictions( $limit ) {
2686 if ( !is_array( $limit ) ) {
2687 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2693 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2694 $bits[] = "$action=$restrictions";
2697 return implode( ':', $bits );
2701 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2702 * backwards compatibility, if you care about error reporting you should use
2703 * doDeleteArticleReal() instead.
2705 * Deletes the article with database consistency, writes logs, purges caches
2707 * @param string $reason Delete reason for deletion log
2708 * @param bool $suppress Suppress all revisions and log the deletion in
2709 * the suppression log instead of the deletion log
2710 * @param int $u1 Unused
2711 * @param bool $u2 Unused
2712 * @param array|string &$error Array of errors to append to
2713 * @param User $user The deleting user
2714 * @return bool True if successful
2716 public function doDeleteArticle(
2717 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2719 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2720 return $status->isGood();
2724 * Back-end article deletion
2725 * Deletes the article with database consistency, writes logs, purges caches
2729 * @param string $reason Delete reason for deletion log
2730 * @param bool $suppress Suppress all revisions and log the deletion in
2731 * the suppression log instead of the deletion log
2732 * @param int $u1 Unused
2733 * @param bool $u2 Unused
2734 * @param array|string &$error Array of errors to append to
2735 * @param User $user The deleting user
2736 * @param array $tags Tags to apply to the deletion action
2737 * @param string $logsubtype
2738 * @return Status Status object; if successful, $status->value is the log_id of the
2739 * deletion log entry. If the page couldn't be deleted because it wasn't
2740 * found, $status is a non-fatal 'cannotdelete' error
2742 public function doDeleteArticleReal(
2743 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2744 $tags = [], $logsubtype = 'delete'
2746 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2748 wfDebug( __METHOD__
. "\n" );
2750 $status = Status
::newGood();
2752 if ( $this->mTitle
->getDBkey() === '' ) {
2753 $status->error( 'cannotdelete',
2754 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2758 // Avoid PHP 7.1 warning of passing $this by reference
2761 $user = is_null( $user ) ?
$wgUser : $user;
2762 if ( !Hooks
::run( 'ArticleDelete',
2763 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2765 if ( $status->isOK() ) {
2766 // Hook aborted but didn't set a fatal status
2767 $status->fatal( 'delete-hook-aborted' );
2772 $dbw = wfGetDB( DB_MASTER
);
2773 $dbw->startAtomic( __METHOD__
);
2775 $this->loadPageData( self
::READ_LATEST
);
2776 $id = $this->getId();
2777 // T98706: lock the page from various other updates but avoid using
2778 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2779 // the revisions queries (which also JOIN on user). Only lock the page
2780 // row and CAS check on page_latest to see if the trx snapshot matches.
2781 $lockedLatest = $this->lockAndGetLatest();
2782 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2783 $dbw->endAtomic( __METHOD__
);
2784 // Page not there or trx snapshot is stale
2785 $status->error( 'cannotdelete',
2786 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2790 // Given the lock above, we can be confident in the title and page ID values
2791 $namespace = $this->getTitle()->getNamespace();
2792 $dbKey = $this->getTitle()->getDBkey();
2794 // At this point we are now comitted to returning an OK
2795 // status unless some DB query error or other exception comes up.
2796 // This way callers don't have to call rollback() if $status is bad
2797 // unless they actually try to catch exceptions (which is rare).
2799 // we need to remember the old content so we can use it to generate all deletion updates.
2800 $revision = $this->getRevision();
2802 $content = $this->getContent( Revision
::RAW
);
2803 } catch ( Exception
$ex ) {
2804 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2805 . $ex->getMessage() );
2810 $revCommentStore = new CommentStore( 'rev_comment' );
2811 $arCommentStore = new CommentStore( 'ar_comment' );
2813 $fields = Revision
::selectFields();
2816 // Bitfields to further suppress the content
2818 $bitfield = Revision
::SUPPRESSED_ALL
;
2819 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2822 // For now, shunt the revision data into the archive table.
2823 // Text is *not* removed from the text table; bulk storage
2824 // is left intact to avoid breaking block-compression or
2825 // immutable storage schemes.
2826 // In the future, we may keep revisions and mark them with
2827 // the rev_deleted field, which is reserved for this purpose.
2829 // Get all of the page revisions
2830 $commentQuery = $revCommentStore->getJoin();
2831 $res = $dbw->select(
2832 [ 'revision' ] +
$commentQuery['tables'],
2833 $fields +
$commentQuery['fields'],
2834 [ 'rev_page' => $id ],
2837 $commentQuery['joins']
2840 // Build their equivalent archive rows
2844 /** @var int[] Revision IDs of edits that were made by IPs */
2847 foreach ( $res as $row ) {
2848 $comment = $revCommentStore->getComment( $row );
2850 'ar_namespace' => $namespace,
2851 'ar_title' => $dbKey,
2852 'ar_user' => $row->rev_user
,
2853 'ar_user_text' => $row->rev_user_text
,
2854 'ar_timestamp' => $row->rev_timestamp
,
2855 'ar_minor_edit' => $row->rev_minor_edit
,
2856 'ar_rev_id' => $row->rev_id
,
2857 'ar_parent_id' => $row->rev_parent_id
,
2858 'ar_text_id' => $row->rev_text_id
,
2861 'ar_len' => $row->rev_len
,
2862 'ar_page_id' => $id,
2863 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2864 'ar_sha1' => $row->rev_sha1
,
2865 ] +
$arCommentStore->insert( $dbw, $comment );
2866 if ( $wgContentHandlerUseDB ) {
2867 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2868 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2870 $rowsInsert[] = $rowInsert;
2871 $revids[] = $row->rev_id
;
2873 // Keep track of IP edits, so that the corresponding rows can
2874 // be deleted in the ip_changes table.
2875 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2876 $ipRevIds[] = $row->rev_id
;
2879 // Copy them into the archive table
2880 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2881 // Save this so we can pass it to the ArticleDeleteComplete hook.
2882 $archivedRevisionCount = $dbw->affectedRows();
2884 // Clone the title and wikiPage, so we have the information we need when
2885 // we log and run the ArticleDeleteComplete hook.
2886 $logTitle = clone $this->mTitle
;
2887 $wikiPageBeforeDelete = clone $this;
2889 // Now that it's safely backed up, delete it
2890 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2891 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2892 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2893 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2896 // Also delete records from ip_changes as applicable.
2897 if ( count( $ipRevIds ) > 0 ) {
2898 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2901 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2902 $logtype = $suppress ?
'suppress' : 'delete';
2904 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2905 $logEntry->setPerformer( $user );
2906 $logEntry->setTarget( $logTitle );
2907 $logEntry->setComment( $reason );
2908 $logEntry->setTags( $tags );
2909 $logid = $logEntry->insert();
2911 $dbw->onTransactionPreCommitOrIdle(
2912 function () use ( $dbw, $logEntry, $logid ) {
2913 // T58776: avoid deadlocks (especially from FileDeleteForm)
2914 $logEntry->publish( $logid );
2919 $dbw->endAtomic( __METHOD__
);
2921 $this->doDeleteUpdates( $id, $content, $revision );
2923 Hooks
::run( 'ArticleDeleteComplete', [
2924 &$wikiPageBeforeDelete,
2930 $archivedRevisionCount
2932 $status->value
= $logid;
2934 // Show log excerpt on 404 pages rather than just a link
2935 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2936 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2937 $cache->set( $key, 1, $cache::TTL_DAY
);
2943 * Lock the page row for this title+id and return page_latest (or 0)
2945 * @return int Returns 0 if no row was found with this title+id
2948 public function lockAndGetLatest() {
2949 return (int)wfGetDB( DB_MASTER
)->selectField(
2953 'page_id' => $this->getId(),
2954 // Typically page_id is enough, but some code might try to do
2955 // updates assuming the title is the same, so verify that
2956 'page_namespace' => $this->getTitle()->getNamespace(),
2957 'page_title' => $this->getTitle()->getDBkey()
2965 * Do some database updates after deletion
2967 * @param int $id The page_id value of the page being deleted
2968 * @param Content|null $content Optional page content to be used when determining
2969 * the required updates. This may be needed because $this->getContent()
2970 * may already return null when the page proper was deleted.
2971 * @param Revision|null $revision The latest page revision
2973 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2975 $countable = $this->isCountable();
2976 } catch ( Exception
$ex ) {
2977 // fallback for deleting broken pages for which we cannot load the content for
2978 // some reason. Note that doDeleteArticleReal() already logged this problem.
2982 // Update site status
2983 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2985 // Delete pagelinks, update secondary indexes, etc
2986 $updates = $this->getDeletionUpdates( $content );
2987 foreach ( $updates as $update ) {
2988 DeferredUpdates
::addUpdate( $update );
2991 // Reparse any pages transcluding this page
2992 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2994 // Reparse any pages including this image
2995 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2996 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
3000 self
::onArticleDelete( $this->mTitle
);
3001 ResourceLoaderWikiModule
::invalidateModuleCache(
3002 $this->mTitle
, $revision, null, wfWikiID()
3005 // Reset this object and the Title object
3006 $this->loadFromRow( false, self
::READ_LATEST
);
3009 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3013 * Roll back the most recent consecutive set of edits to a page
3014 * from the same user; fails if there are no eligible edits to
3015 * roll back to, e.g. user is the sole contributor. This function
3016 * performs permissions checks on $user, then calls commitRollback()
3017 * to do the dirty work
3019 * @todo Separate the business/permission stuff out from backend code
3020 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3022 * @param string $fromP Name of the user whose edits to rollback.
3023 * @param string $summary Custom summary. Set to default summary if empty.
3024 * @param string $token Rollback token.
3025 * @param bool $bot If true, mark all reverted edits as bot.
3027 * @param array &$resultDetails Array contains result-specific array of additional values
3028 * 'alreadyrolled' : 'current' (rev)
3029 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3031 * @param User $user The user performing the rollback
3032 * @param array|null $tags Change tags to apply to the rollback
3033 * Callers are responsible for permission checks
3034 * (with ChangeTags::canAddTagsAccompanyingChange)
3036 * @return array Array of errors, each error formatted as
3037 * array(messagekey, param1, param2, ...).
3038 * On success, the array is empty. This array can also be passed to
3039 * OutputPage::showPermissionsErrorPage().
3041 public function doRollback(
3042 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3044 $resultDetails = null;
3046 // Check permissions
3047 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3048 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3049 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3051 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3052 $errors[] = [ 'sessionfailure' ];
3055 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3056 $errors[] = [ 'actionthrottledtext' ];
3059 // If there were errors, bail out now
3060 if ( !empty( $errors ) ) {
3064 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3068 * Backend implementation of doRollback(), please refer there for parameter
3069 * and return value documentation
3071 * NOTE: This function does NOT check ANY permissions, it just commits the
3072 * rollback to the DB. Therefore, you should only call this function direct-
3073 * ly if you want to use custom permissions checks. If you don't, use
3074 * doRollback() instead.
3075 * @param string $fromP Name of the user whose edits to rollback.
3076 * @param string $summary Custom summary. Set to default summary if empty.
3077 * @param bool $bot If true, mark all reverted edits as bot.
3079 * @param array &$resultDetails Contains result-specific array of additional values
3080 * @param User $guser The user performing the rollback
3081 * @param array|null $tags Change tags to apply to the rollback
3082 * Callers are responsible for permission checks
3083 * (with ChangeTags::canAddTagsAccompanyingChange)
3087 public function commitRollback( $fromP, $summary, $bot,
3088 &$resultDetails, User
$guser, $tags = null
3090 global $wgUseRCPatrol, $wgContLang;
3092 $dbw = wfGetDB( DB_MASTER
);
3094 if ( wfReadOnly() ) {
3095 return [ [ 'readonlytext' ] ];
3098 // Get the last editor
3099 $current = $this->getRevision();
3100 if ( is_null( $current ) ) {
3101 // Something wrong... no page?
3102 return [ [ 'notanarticle' ] ];
3105 $from = str_replace( '_', ' ', $fromP );
3106 // User name given should match up with the top revision.
3107 // If the user was deleted then $from should be empty.
3108 if ( $from != $current->getUserText() ) {
3109 $resultDetails = [ 'current' => $current ];
3110 return [ [ 'alreadyrolled',
3111 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3112 htmlspecialchars( $fromP ),
3113 htmlspecialchars( $current->getUserText() )
3117 // Get the last edit not by this person...
3118 // Note: these may not be public values
3119 $user = intval( $current->getUser( Revision
::RAW
) );
3120 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3121 $s = $dbw->selectRow( 'revision',
3122 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3123 [ 'rev_page' => $current->getPage(),
3124 "rev_user != {$user} OR rev_user_text != {$user_text}"
3126 [ 'USE INDEX' => 'page_timestamp',
3127 'ORDER BY' => 'rev_timestamp DESC' ]
3129 if ( $s === false ) {
3130 // No one else ever edited this page
3131 return [ [ 'cantrollback' ] ];
3132 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3133 ||
$s->rev_deleted
& Revision
::DELETED_USER
3135 // Only admins can see this text
3136 return [ [ 'notvisiblerev' ] ];
3139 // Generate the edit summary if necessary
3140 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3141 if ( empty( $summary ) ) {
3142 if ( $from == '' ) { // no public user name
3143 $summary = wfMessage( 'revertpage-nouser' );
3145 $summary = wfMessage( 'revertpage' );
3149 // Allow the custom summary to use the same args as the default message
3151 $target->getUserText(), $from, $s->rev_id
,
3152 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3153 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3155 if ( $summary instanceof Message
) {
3156 $summary = $summary->params( $args )->inContentLanguage()->text();
3158 $summary = wfMsgReplaceArgs( $summary, $args );
3161 // Trim spaces on user supplied text
3162 $summary = trim( $summary );
3165 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3167 if ( $guser->isAllowed( 'minoredit' ) ) {
3168 $flags |
= EDIT_MINOR
;
3171 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3172 $flags |
= EDIT_FORCE_BOT
;
3175 $targetContent = $target->getContent();
3176 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3178 // Actually store the edit
3179 $status = $this->doEditContent(
3189 // Set patrolling and bot flag on the edits, which gets rollbacked.
3190 // This is done even on edit failure to have patrolling in that case (T64157).
3192 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3193 // Mark all reverted edits as bot
3197 if ( $wgUseRCPatrol ) {
3198 // Mark all reverted edits as patrolled
3199 $set['rc_patrolled'] = 1;
3202 if ( count( $set ) ) {
3203 $dbw->update( 'recentchanges', $set,
3205 'rc_cur_id' => $current->getPage(),
3206 'rc_user_text' => $current->getUserText(),
3207 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3213 if ( !$status->isOK() ) {
3214 return $status->getErrorsArray();
3217 // raise error, when the edit is an edit without a new version
3218 $statusRev = isset( $status->value
['revision'] )
3219 ?
$status->value
['revision']
3221 if ( !( $statusRev instanceof Revision
) ) {
3222 $resultDetails = [ 'current' => $current ];
3223 return [ [ 'alreadyrolled',
3224 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3225 htmlspecialchars( $fromP ),
3226 htmlspecialchars( $current->getUserText() )
3230 if ( $changingContentModel ) {
3231 // If the content model changed during the rollback,
3232 // make sure it gets logged to Special:Log/contentmodel
3233 $log = new ManualLogEntry( 'contentmodel', 'change' );
3234 $log->setPerformer( $guser );
3235 $log->setTarget( $this->mTitle
);
3236 $log->setComment( $summary );
3237 $log->setParameters( [
3238 '4::oldmodel' => $current->getContentModel(),
3239 '5::newmodel' => $targetContent->getModel(),
3242 $logId = $log->insert( $dbw );
3243 $log->publish( $logId );
3246 $revId = $statusRev->getId();
3248 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3251 'summary' => $summary,
3252 'current' => $current,
3253 'target' => $target,
3261 * The onArticle*() functions are supposed to be a kind of hooks
3262 * which should be called whenever any of the specified actions
3265 * This is a good place to put code to clear caches, for instance.
3267 * This is called on page move and undelete, as well as edit
3269 * @param Title $title
3271 public static function onArticleCreate( Title
$title ) {
3272 // Update existence markers on article/talk tabs...
3273 $other = $title->getOtherPage();
3275 $other->purgeSquid();
3277 $title->touchLinks();
3278 $title->purgeSquid();
3279 $title->deleteTitleProtection();
3281 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3283 // Invalidate caches of articles which include this page
3284 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3286 if ( $title->getNamespace() == NS_CATEGORY
) {
3287 // Load the Category object, which will schedule a job to create
3288 // the category table row if necessary. Checking a replica DB is ok
3289 // here, in the worst case it'll run an unnecessary recount job on
3290 // a category that probably doesn't have many members.
3291 Category
::newFromTitle( $title )->getID();
3296 * Clears caches when article is deleted
3298 * @param Title $title
3300 public static function onArticleDelete( Title
$title ) {
3301 // Update existence markers on article/talk tabs...
3302 $other = $title->getOtherPage();
3304 $other->purgeSquid();
3306 $title->touchLinks();
3307 $title->purgeSquid();
3309 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3312 HTMLFileCache
::clearFileCache( $title );
3313 InfoAction
::invalidateCache( $title );
3316 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3317 MessageCache
::singleton()->updateMessageOverride( $title, null );
3321 if ( $title->getNamespace() == NS_FILE
) {
3322 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3326 if ( $title->getNamespace() == NS_USER_TALK
) {
3327 $user = User
::newFromName( $title->getText(), false );
3329 $user->setNewtalk( false );
3334 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3338 * Purge caches on page update etc
3340 * @param Title $title
3341 * @param Revision|null $revision Revision that was just saved, may be null
3343 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3344 // Invalidate caches of articles which include this page
3345 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3347 // Invalidate the caches of all pages which redirect here
3348 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3350 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3352 // Purge CDN for this page only
3353 $title->purgeSquid();
3354 // Clear file cache for this page only
3355 HTMLFileCache
::clearFileCache( $title );
3357 $revid = $revision ?
$revision->getId() : null;
3358 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3359 InfoAction
::invalidateCache( $title, $revid );
3366 * Returns a list of categories this page is a member of.
3367 * Results will include hidden categories
3369 * @return TitleArray
3371 public function getCategories() {
3372 $id = $this->getId();
3374 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3377 $dbr = wfGetDB( DB_REPLICA
);
3378 $res = $dbr->select( 'categorylinks',
3379 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3380 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3381 // as not being aliases, and NS_CATEGORY is numeric
3382 [ 'cl_from' => $id ],
3385 return TitleArray
::newFromResult( $res );
3389 * Returns a list of hidden categories this page is a member of.
3390 * Uses the page_props and categorylinks tables.
3392 * @return array Array of Title objects
3394 public function getHiddenCategories() {
3396 $id = $this->getId();
3402 $dbr = wfGetDB( DB_REPLICA
);
3403 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3405 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3406 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3409 if ( $res !== false ) {
3410 foreach ( $res as $row ) {
3411 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3419 * Auto-generates a deletion reason
3421 * @param bool &$hasHistory Whether the page has a history
3422 * @return string|bool String containing deletion reason or empty string, or boolean false
3423 * if no revision occurred
3425 public function getAutoDeleteReason( &$hasHistory ) {
3426 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3430 * Update all the appropriate counts in the category table, given that
3431 * we've added the categories $added and deleted the categories $deleted.
3433 * This should only be called from deferred updates or jobs to avoid contention.
3435 * @param array $added The names of categories that were added
3436 * @param array $deleted The names of categories that were deleted
3437 * @param int $id Page ID (this should be the original deleted page ID)
3439 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3440 $id = $id ?
: $this->getId();
3441 $ns = $this->getTitle()->getNamespace();
3443 $addFields = [ 'cat_pages = cat_pages + 1' ];
3444 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3445 if ( $ns == NS_CATEGORY
) {
3446 $addFields[] = 'cat_subcats = cat_subcats + 1';
3447 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3448 } elseif ( $ns == NS_FILE
) {
3449 $addFields[] = 'cat_files = cat_files + 1';
3450 $removeFields[] = 'cat_files = cat_files - 1';
3453 $dbw = wfGetDB( DB_MASTER
);
3455 if ( count( $added ) ) {
3456 $existingAdded = $dbw->selectFieldValues(
3459 [ 'cat_title' => $added ],
3463 // For category rows that already exist, do a plain
3464 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3465 // to avoid creating gaps in the cat_id sequence.
3466 if ( count( $existingAdded ) ) {
3470 [ 'cat_title' => $existingAdded ],
3475 $missingAdded = array_diff( $added, $existingAdded );
3476 if ( count( $missingAdded ) ) {
3478 foreach ( $missingAdded as $cat ) {
3480 'cat_title' => $cat,
3482 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3483 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3496 if ( count( $deleted ) ) {
3500 [ 'cat_title' => $deleted ],
3505 foreach ( $added as $catName ) {
3506 $cat = Category
::newFromName( $catName );
3507 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3510 foreach ( $deleted as $catName ) {
3511 $cat = Category
::newFromName( $catName );
3512 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3515 // Refresh counts on categories that should be empty now, to
3516 // trigger possible deletion. Check master for the most
3517 // up-to-date cat_pages.
3518 if ( count( $deleted ) ) {
3519 $rows = $dbw->select(
3521 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3522 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3525 foreach ( $rows as $row ) {
3526 $cat = Category
::newFromRow( $row );
3527 // T166757: do the update after this DB commit
3528 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3529 $cat->refreshCounts();
3536 * Opportunistically enqueue link update jobs given fresh parser output if useful
3538 * @param ParserOutput $parserOutput Current version page output
3541 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3542 if ( wfReadOnly() ) {
3546 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3547 [ $this, $this->mTitle
, $parserOutput ]
3552 $config = RequestContext
::getMain()->getConfig();
3555 'isOpportunistic' => true,
3556 'rootJobTimestamp' => $parserOutput->getCacheTime()
3559 if ( $this->mTitle
->areRestrictionsCascading() ) {
3560 // If the page is cascade protecting, the links should really be up-to-date
3561 JobQueueGroup
::singleton()->lazyPush(
3562 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3564 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3565 // Assume the output contains "dynamic" time/random based magic words.
3566 // Only update pages that expired due to dynamic content and NOT due to edits
3567 // to referenced templates/files. When the cache expires due to dynamic content,
3568 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3569 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3570 // template/file edit already triggered recursive RefreshLinksJob jobs.
3571 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3572 // If a page is uncacheable, do not keep spamming a job for it.
3573 // Although it would be de-duplicated, it would still waste I/O.
3574 $cache = ObjectCache
::getLocalClusterInstance();
3575 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3576 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3577 if ( $cache->add( $key, time(), $ttl ) ) {
3578 JobQueueGroup
::singleton()->lazyPush(
3579 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3587 * Returns a list of updates to be performed when this page is deleted. The
3588 * updates should remove any information about this page from secondary data
3589 * stores such as links tables.
3591 * @param Content|null $content Optional Content object for determining the
3592 * necessary updates.
3593 * @return DeferrableUpdate[]
3595 public function getDeletionUpdates( Content
$content = null ) {
3597 // load content object, which may be used to determine the necessary updates.
3598 // XXX: the content may not be needed to determine the updates.
3600 $content = $this->getContent( Revision
::RAW
);
3601 } catch ( Exception
$ex ) {
3602 // If we can't load the content, something is wrong. Perhaps that's why
3603 // the user is trying to delete the page, so let's not fail in that case.
3604 // Note that doDeleteArticleReal() will already have logged an issue with
3605 // loading the content.
3612 $updates = $content->getDeletionUpdates( $this );
3615 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3620 * Whether this content displayed on this page
3621 * comes from the local database
3626 public function isLocal() {
3631 * The display name for the site this content
3632 * come from. If a subclass overrides isLocal(),
3633 * this could return something other than the
3639 public function getWikiDisplayName() {
3645 * Get the source URL for the content on this page,
3646 * typically the canonical URL, but may be a remote
3647 * link if the content comes from another site
3652 public function getSourceURL() {
3653 return $this->getTitle()->getCanonicalURL();
3657 * @param WANObjectCache $cache
3661 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3662 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3664 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );