3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use \MediaWiki\Logger\LoggerFactory
;
24 use \MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\FakeResultWrapper
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 class WikiPage
implements Page
, IDBAccessObject
{
35 // Constants for $mDataLoadedFrom and related
40 public $mTitle = null;
45 public $mDataLoaded = false; // !< Boolean
46 public $mIsRedirect = false; // !< Boolean
47 public $mLatest = false; // !< Integer (false means "not loaded")
50 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
51 public $mPreparedEdit = false;
56 protected $mId = null;
59 * @var int One of the READ_* constants
61 protected $mDataLoadedFrom = self
::READ_NONE
;
66 protected $mRedirectTarget = null;
71 protected $mLastRevision = null;
74 * @var string Timestamp of the current revision or empty string if not loaded
76 protected $mTimestamp = '';
81 protected $mTouched = '19700101000000';
86 protected $mLinksUpdated = '19700101000000';
88 /** @deprecated since 1.29. Added in 1.28 for partial purging, no longer used. */
89 const PURGE_CDN_CACHE
= 1;
90 const PURGE_CLUSTER_PCACHE
= 2;
91 const PURGE_GLOBAL_PCACHE
= 4;
95 * Constructor and clear the article
96 * @param Title $title Reference to a Title object.
98 public function __construct( Title
$title ) {
99 $this->mTitle
= $title;
103 * Makes sure that the mTitle object is cloned
104 * to the newly cloned WikiPage.
106 public function __clone() {
107 $this->mTitle
= clone $this->mTitle
;
111 * Create a WikiPage object of the appropriate class for the given title.
113 * @param Title $title
115 * @throws MWException
116 * @return WikiPage|WikiCategoryPage|WikiFilePage
118 public static function factory( Title
$title ) {
119 $ns = $title->getNamespace();
121 if ( $ns == NS_MEDIA
) {
122 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
123 } elseif ( $ns < 0 ) {
124 throw new MWException( "Invalid or virtual namespace $ns given." );
128 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
134 $page = new WikiFilePage( $title );
137 $page = new WikiCategoryPage( $title );
140 $page = new WikiPage( $title );
147 * Constructor from a page id
149 * @param int $id Article ID to load
150 * @param string|int $from One of the following values:
151 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
152 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
154 * @return WikiPage|null
156 public static function newFromID( $id, $from = 'fromdb' ) {
157 // page ids are never 0 or negative, see T63166
162 $from = self
::convertSelectType( $from );
163 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
164 $row = $db->selectRow(
165 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
169 return self
::newFromRow( $row, $from );
173 * Constructor from a database row
176 * @param object $row Database row containing at least fields returned by selectFields().
177 * @param string|int $from Source of $data:
178 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
179 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
180 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
183 public static function newFromRow( $row, $from = 'fromdb' ) {
184 $page = self
::factory( Title
::newFromRow( $row ) );
185 $page->loadFromRow( $row, $from );
190 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
192 * @param object|string|int $type
195 private static function convertSelectType( $type ) {
198 return self
::READ_NORMAL
;
200 return self
::READ_LATEST
;
202 return self
::READ_LOCKING
;
204 // It may already be an integer or whatever else
210 * @todo Move this UI stuff somewhere else
212 * @see ContentHandler::getActionOverrides
214 public function getActionOverrides() {
215 return $this->getContentHandler()->getActionOverrides();
219 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
221 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
223 * @return ContentHandler
227 public function getContentHandler() {
228 return ContentHandler
::getForModelID( $this->getContentModel() );
232 * Get the title object of the article
233 * @return Title Title object of this page
235 public function getTitle() {
236 return $this->mTitle
;
243 public function clear() {
244 $this->mDataLoaded
= false;
245 $this->mDataLoadedFrom
= self
::READ_NONE
;
247 $this->clearCacheFields();
251 * Clear the object cache fields
254 protected function clearCacheFields() {
256 $this->mRedirectTarget
= null; // Title object if set
257 $this->mLastRevision
= null; // Latest revision
258 $this->mTouched
= '19700101000000';
259 $this->mLinksUpdated
= '19700101000000';
260 $this->mTimestamp
= '';
261 $this->mIsRedirect
= false;
262 $this->mLatest
= false;
263 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
264 // the requested rev ID and content against the cached one for equality. For most
265 // content types, the output should not change during the lifetime of this cache.
266 // Clearing it can cause extra parses on edit for no reason.
270 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
274 public function clearPreparedEdit() {
275 $this->mPreparedEdit
= false;
279 * Return the list of revision fields that should be selected to create
284 public static function selectFields() {
285 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
296 'page_links_updated',
301 if ( $wgContentHandlerUseDB ) {
302 $fields[] = 'page_content_model';
305 if ( $wgPageLanguageUseDB ) {
306 $fields[] = 'page_lang';
313 * Fetch a page record with the given conditions
314 * @param IDatabase $dbr
315 * @param array $conditions
316 * @param array $options
317 * @return object|bool Database result resource, or false on failure
319 protected function pageData( $dbr, $conditions, $options = [] ) {
320 $fields = self
::selectFields();
322 // Avoid PHP 7.1 warning of passing $this by reference
325 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
327 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
329 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
335 * Fetch a page record matching the Title object's namespace and title
336 * using a sanitized title string
338 * @param IDatabase $dbr
339 * @param Title $title
340 * @param array $options
341 * @return object|bool Database result resource, or false on failure
343 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
344 return $this->pageData( $dbr, [
345 'page_namespace' => $title->getNamespace(),
346 'page_title' => $title->getDBkey() ], $options );
350 * Fetch a page record matching the requested ID
352 * @param IDatabase $dbr
354 * @param array $options
355 * @return object|bool Database result resource, or false on failure
357 public function pageDataFromId( $dbr, $id, $options = [] ) {
358 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
362 * Load the object from a given source by title
364 * @param object|string|int $from One of the following:
365 * - A DB query result object.
366 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
367 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
368 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
369 * using SELECT FOR UPDATE.
373 public function loadPageData( $from = 'fromdb' ) {
374 $from = self
::convertSelectType( $from );
375 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
376 // We already have the data from the correct location, no need to load it twice.
380 if ( is_int( $from ) ) {
381 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
382 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
385 && $index == DB_REPLICA
386 && wfGetLB()->getServerCount() > 1
387 && wfGetLB()->hasOrMadeRecentMasterChanges()
389 $from = self
::READ_LATEST
;
390 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
391 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
394 // No idea from where the caller got this data, assume replica DB.
396 $from = self
::READ_NORMAL
;
399 $this->loadFromRow( $data, $from );
403 * Load the object from a database row
406 * @param object|bool $data DB row containing fields returned by selectFields() or false
407 * @param string|int $from One of the following:
408 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
409 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
410 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
411 * the master DB using SELECT FOR UPDATE
413 public function loadFromRow( $data, $from ) {
414 $lc = LinkCache
::singleton();
415 $lc->clearLink( $this->mTitle
);
418 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
420 $this->mTitle
->loadFromRow( $data );
422 // Old-fashioned restrictions
423 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
425 $this->mId
= intval( $data->page_id
);
426 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
427 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
428 $this->mIsRedirect
= intval( $data->page_is_redirect
);
429 $this->mLatest
= intval( $data->page_latest
);
430 // T39225: $latest may no longer match the cached latest Revision object.
431 // Double-check the ID of any cached latest Revision object for consistency.
432 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
433 $this->mLastRevision
= null;
434 $this->mTimestamp
= '';
437 $lc->addBadLinkObj( $this->mTitle
);
439 $this->mTitle
->loadFromRow( false );
441 $this->clearCacheFields();
446 $this->mDataLoaded
= true;
447 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
451 * @return int Page ID
453 public function getId() {
454 if ( !$this->mDataLoaded
) {
455 $this->loadPageData();
461 * @return bool Whether or not the page exists in the database
463 public function exists() {
464 if ( !$this->mDataLoaded
) {
465 $this->loadPageData();
467 return $this->mId
> 0;
471 * Check if this page is something we're going to be showing
472 * some sort of sensible content for. If we return false, page
473 * views (plain action=view) will return an HTTP 404 response,
474 * so spiders and robots can know they're following a bad link.
478 public function hasViewableContent() {
479 return $this->mTitle
->isKnown();
483 * Tests if the article content represents a redirect
487 public function isRedirect() {
488 if ( !$this->mDataLoaded
) {
489 $this->loadPageData();
492 return (bool)$this->mIsRedirect
;
496 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
498 * Will use the revisions actual content model if the page exists,
499 * and the page's default if the page doesn't exist yet.
505 public function getContentModel() {
506 if ( $this->exists() ) {
507 $cache = ObjectCache
::getMainWANInstance();
509 return $cache->getWithSetCallback(
510 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
513 $rev = $this->getRevision();
515 // Look at the revision's actual content model
516 return $rev->getContentModel();
518 $title = $this->mTitle
->getPrefixedDBkey();
519 wfWarn( "Page $title exists but has no (visible) revisions!" );
520 return $this->mTitle
->getContentModel();
526 // use the default model for this page
527 return $this->mTitle
->getContentModel();
531 * Loads page_touched and returns a value indicating if it should be used
532 * @return bool True if this page exists and is not a redirect
534 public function checkTouched() {
535 if ( !$this->mDataLoaded
) {
536 $this->loadPageData();
538 return ( $this->mId
&& !$this->mIsRedirect
);
542 * Get the page_touched field
543 * @return string Containing GMT timestamp
545 public function getTouched() {
546 if ( !$this->mDataLoaded
) {
547 $this->loadPageData();
549 return $this->mTouched
;
553 * Get the page_links_updated field
554 * @return string|null Containing GMT timestamp
556 public function getLinksTimestamp() {
557 if ( !$this->mDataLoaded
) {
558 $this->loadPageData();
560 return $this->mLinksUpdated
;
564 * Get the page_latest field
565 * @return int The rev_id of current revision
567 public function getLatest() {
568 if ( !$this->mDataLoaded
) {
569 $this->loadPageData();
571 return (int)$this->mLatest
;
575 * Get the Revision object of the oldest revision
576 * @return Revision|null
578 public function getOldestRevision() {
580 // Try using the replica DB first, then try the master
582 $db = wfGetDB( DB_REPLICA
);
583 $revSelectFields = Revision
::selectFields();
586 while ( $continue ) {
587 $row = $db->selectRow(
591 'rev_page' => $this->getId()
595 'ORDER BY' => 'rev_timestamp ASC',
596 'IGNORE INDEX' => 'rev_timestamp'
603 $db = wfGetDB( DB_MASTER
);
608 return $row ? Revision
::newFromRow( $row ) : null;
612 * Loads everything except the text
613 * This isn't necessary for all uses, so it's only done if needed.
615 protected function loadLastEdit() {
616 if ( $this->mLastRevision
!== null ) {
617 return; // already loaded
620 $latest = $this->getLatest();
622 return; // page doesn't exist or is missing page_latest info
625 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
626 // T39225: if session S1 loads the page row FOR UPDATE, the result always
627 // includes the latest changes committed. This is true even within REPEATABLE-READ
628 // transactions, where S1 normally only sees changes committed before the first S1
629 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
630 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
631 // happened after the first S1 SELECT.
632 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
633 $flags = Revision
::READ_LOCKING
;
634 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
635 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
636 // Bug T93976: if page_latest was loaded from the master, fetch the
637 // revision from there as well, as it may not exist yet on a replica DB.
638 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
639 $flags = Revision
::READ_LATEST
;
640 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
642 $dbr = wfGetDB( DB_REPLICA
);
643 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
646 if ( $revision ) { // sanity
647 $this->setLastEdit( $revision );
652 * Set the latest revision
653 * @param Revision $revision
655 protected function setLastEdit( Revision
$revision ) {
656 $this->mLastRevision
= $revision;
657 $this->mTimestamp
= $revision->getTimestamp();
661 * Get the latest revision
662 * @return Revision|null
664 public function getRevision() {
665 $this->loadLastEdit();
666 if ( $this->mLastRevision
) {
667 return $this->mLastRevision
;
673 * Get the content of the current revision. No side-effects...
675 * @param int $audience One of:
676 * Revision::FOR_PUBLIC to be displayed to all users
677 * Revision::FOR_THIS_USER to be displayed to $wgUser
678 * Revision::RAW get the text regardless of permissions
679 * @param User $user User object to check for, only if FOR_THIS_USER is passed
680 * to the $audience parameter
681 * @return Content|null The content of the current revision
685 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
686 $this->loadLastEdit();
687 if ( $this->mLastRevision
) {
688 return $this->mLastRevision
->getContent( $audience, $user );
694 * @return string MW timestamp of last article revision
696 public function getTimestamp() {
697 // Check if the field has been filled by WikiPage::setTimestamp()
698 if ( !$this->mTimestamp
) {
699 $this->loadLastEdit();
702 return wfTimestamp( TS_MW
, $this->mTimestamp
);
706 * Set the page timestamp (use only to avoid DB queries)
707 * @param string $ts MW timestamp of last article revision
710 public function setTimestamp( $ts ) {
711 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
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
721 * @return int User ID for the user that made the last article revision
723 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
724 $this->loadLastEdit();
725 if ( $this->mLastRevision
) {
726 return $this->mLastRevision
->getUser( $audience, $user );
733 * Get the User object of the user who created the page
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
742 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
743 $revision = $this->getOldestRevision();
745 $userName = $revision->getUserText( $audience, $user );
746 return User
::newFromName( $userName, false );
753 * @param int $audience One of:
754 * Revision::FOR_PUBLIC to be displayed to all users
755 * Revision::FOR_THIS_USER to be displayed to the given user
756 * Revision::RAW get the text regardless of permissions
757 * @param User $user User object to check for, only if FOR_THIS_USER is passed
758 * to the $audience parameter
759 * @return string Username of the user that made the last article revision
761 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
762 $this->loadLastEdit();
763 if ( $this->mLastRevision
) {
764 return $this->mLastRevision
->getUserText( $audience, $user );
771 * @param int $audience One of:
772 * Revision::FOR_PUBLIC to be displayed to all users
773 * Revision::FOR_THIS_USER to be displayed to the given user
774 * Revision::RAW get the text regardless of permissions
775 * @param User $user User object to check for, only if FOR_THIS_USER is passed
776 * to the $audience parameter
777 * @return string Comment stored for the last article revision
779 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
780 $this->loadLastEdit();
781 if ( $this->mLastRevision
) {
782 return $this->mLastRevision
->getComment( $audience, $user );
789 * Returns true if last revision was marked as "minor edit"
791 * @return bool Minor edit indicator for the last article revision.
793 public function getMinorEdit() {
794 $this->loadLastEdit();
795 if ( $this->mLastRevision
) {
796 return $this->mLastRevision
->isMinor();
803 * Determine whether a page would be suitable for being counted as an
804 * article in the site_stats table based on the title & its content
806 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
807 * if false, the current database state will be used
810 public function isCountable( $editInfo = false ) {
811 global $wgArticleCountMethod;
813 if ( !$this->mTitle
->isContentPage() ) {
818 $content = $editInfo->pstContent
;
820 $content = $this->getContent();
823 if ( !$content ||
$content->isRedirect() ) {
829 if ( $wgArticleCountMethod === 'link' ) {
830 // nasty special case to avoid re-parsing to detect links
833 // ParserOutput::getLinks() is a 2D array of page links, so
834 // to be really correct we would need to recurse in the array
835 // but the main array should only have items in it if there are
837 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
839 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
840 [ 'pl_from' => $this->getId() ], __METHOD__
);
844 return $content->isCountable( $hasLinks );
848 * If this page is a redirect, get its target
850 * The target will be fetched from the redirect table if possible.
851 * If this page doesn't have an entry there, call insertRedirect()
852 * @return Title|null Title object, or null if this page is not a redirect
854 public function getRedirectTarget() {
855 if ( !$this->mTitle
->isRedirect() ) {
859 if ( $this->mRedirectTarget
!== null ) {
860 return $this->mRedirectTarget
;
863 // Query the redirect table
864 $dbr = wfGetDB( DB_REPLICA
);
865 $row = $dbr->selectRow( 'redirect',
866 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
867 [ 'rd_from' => $this->getId() ],
871 // rd_fragment and rd_interwiki were added later, populate them if empty
872 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
873 $this->mRedirectTarget
= Title
::makeTitle(
874 $row->rd_namespace
, $row->rd_title
,
875 $row->rd_fragment
, $row->rd_interwiki
877 return $this->mRedirectTarget
;
880 // This page doesn't have an entry in the redirect table
881 $this->mRedirectTarget
= $this->insertRedirect();
882 return $this->mRedirectTarget
;
886 * Insert an entry for this page into the redirect table if the content is a redirect
888 * The database update will be deferred via DeferredUpdates
890 * Don't call this function directly unless you know what you're doing.
891 * @return Title|null Title object or null if not a redirect
893 public function insertRedirect() {
894 $content = $this->getContent();
895 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
900 // Update the DB post-send if the page has not cached since now
902 $latest = $this->getLatest();
903 DeferredUpdates
::addCallableUpdate(
904 function () use ( $that, $retval, $latest ) {
905 $that->insertRedirectEntry( $retval, $latest );
907 DeferredUpdates
::POSTSEND
,
915 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
916 * @param Title $rt Redirect target
917 * @param int|null $oldLatest Prior page_latest for check and set
919 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
920 $dbw = wfGetDB( DB_MASTER
);
921 $dbw->startAtomic( __METHOD__
);
923 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
927 'rd_from' => $this->getId(),
928 'rd_namespace' => $rt->getNamespace(),
929 'rd_title' => $rt->getDBkey(),
930 'rd_fragment' => $rt->getFragment(),
931 'rd_interwiki' => $rt->getInterwiki(),
935 'rd_namespace' => $rt->getNamespace(),
936 'rd_title' => $rt->getDBkey(),
937 'rd_fragment' => $rt->getFragment(),
938 'rd_interwiki' => $rt->getInterwiki(),
944 $dbw->endAtomic( __METHOD__
);
948 * Get the Title object or URL this page redirects to
950 * @return bool|Title|string False, Title of in-wiki target, or string with URL
952 public function followRedirect() {
953 return $this->getRedirectURL( $this->getRedirectTarget() );
957 * Get the Title object or URL to use for a redirect. We use Title
958 * objects for same-wiki, non-special redirects and URLs for everything
960 * @param Title $rt Redirect target
961 * @return bool|Title|string False, Title object of local target, or string with URL
963 public function getRedirectURL( $rt ) {
968 if ( $rt->isExternal() ) {
969 if ( $rt->isLocal() ) {
970 // Offsite wikis need an HTTP redirect.
971 // This can be hard to reverse and may produce loops,
972 // so they may be disabled in the site configuration.
973 $source = $this->mTitle
->getFullURL( 'redirect=no' );
974 return $rt->getFullURL( [ 'rdfrom' => $source ] );
976 // External pages without "local" bit set are not valid
982 if ( $rt->isSpecialPage() ) {
983 // Gotta handle redirects to special pages differently:
984 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
985 // Some pages are not valid targets.
986 if ( $rt->isValidRedirectTarget() ) {
987 return $rt->getFullURL();
997 * Get a list of users who have edited this article, not including the user who made
998 * the most recent revision, which you can get from $article->getUser() if you want it
999 * @return UserArrayFromResult
1001 public function getContributors() {
1002 // @todo FIXME: This is expensive; cache this info somewhere.
1004 $dbr = wfGetDB( DB_REPLICA
);
1006 if ( $dbr->implicitGroupby() ) {
1007 $realNameField = 'user_real_name';
1009 $realNameField = 'MIN(user_real_name) AS user_real_name';
1012 $tables = [ 'revision', 'user' ];
1015 'user_id' => 'rev_user',
1016 'user_name' => 'rev_user_text',
1018 'timestamp' => 'MAX(rev_timestamp)',
1021 $conds = [ 'rev_page' => $this->getId() ];
1023 // The user who made the top revision gets credited as "this page was last edited by
1024 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1025 $user = $this->getUser();
1027 $conds[] = "rev_user != $user";
1029 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1033 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1036 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1040 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1041 'ORDER BY' => 'timestamp DESC',
1044 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1045 return new UserArrayFromResult( $res );
1049 * Should the parser cache be used?
1051 * @param ParserOptions $parserOptions ParserOptions to check
1055 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1056 return $parserOptions->getStubThreshold() == 0
1058 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1059 && $this->getContentHandler()->isParserCacheSupported();
1063 * Get a ParserOutput for the given ParserOptions and revision ID.
1065 * The parser cache will be used if possible. Cache misses that result
1066 * in parser runs are debounced with PoolCounter.
1069 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1070 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1071 * get the current revision (default value)
1072 * @param bool $forceParse Force reindexing, regardless of cache settings
1073 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1075 public function getParserOutput(
1076 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1079 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1080 wfDebug( __METHOD__
.
1081 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1082 if ( $parserOptions->getStubThreshold() ) {
1083 wfIncrStats( 'pcache.miss.stub' );
1086 if ( $useParserCache ) {
1087 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1088 if ( $parserOutput !== false ) {
1089 return $parserOutput;
1093 if ( $oldid === null ||
$oldid === 0 ) {
1094 $oldid = $this->getLatest();
1097 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1100 return $pool->getParserOutput();
1104 * Do standard deferred updates after page view (existing or missing page)
1105 * @param User $user The relevant user
1106 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1108 public function doViewUpdates( User
$user, $oldid = 0 ) {
1109 if ( wfReadOnly() ) {
1113 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1114 // Update newtalk / watchlist notification status
1116 $user->clearNotification( $this->mTitle
, $oldid );
1117 } catch ( DBError
$e ) {
1118 // Avoid outage if the master is not reachable
1119 MWExceptionHandler
::logException( $e );
1124 * Perform the actions of a page purging
1126 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1127 * controlled how much purging was done.
1129 public function doPurge() {
1130 // Avoid PHP 7.1 warning of passing $this by reference
1133 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1137 $this->mTitle
->invalidateCache();
1140 HTMLFileCache
::clearFileCache( $this->getTitle() );
1141 // Send purge after above page_touched update was committed
1142 DeferredUpdates
::addUpdate(
1143 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1144 DeferredUpdates
::PRESEND
1147 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1148 $messageCache = MessageCache
::singleton();
1149 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1156 * Get the last time a user explicitly purged the page via action=purge
1158 * @return string|bool TS_MW timestamp or false
1160 * @deprecated since 1.29. It will always return false.
1162 public function getLastPurgeTimestamp() {
1163 wfDeprecated( __METHOD__
, '1.29' );
1168 * Insert a new empty page record for this article.
1169 * This *must* be followed up by creating a revision
1170 * and running $this->updateRevisionOn( ... );
1171 * or else the record will be left in a funky state.
1172 * Best if all done inside a transaction.
1174 * @param IDatabase $dbw
1175 * @param int|null $pageId Custom page ID that will be used for the insert statement
1177 * @return bool|int The newly created page_id key; false if the row was not
1178 * inserted, e.g. because the title already existed or because the specified
1179 * page ID is already in use.
1181 public function insertOn( $dbw, $pageId = null ) {
1182 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1186 'page_id' => $pageIdForInsert,
1187 'page_namespace' => $this->mTitle
->getNamespace(),
1188 'page_title' => $this->mTitle
->getDBkey(),
1189 'page_restrictions' => '',
1190 'page_is_redirect' => 0, // Will set this shortly...
1192 'page_random' => wfRandom(),
1193 'page_touched' => $dbw->timestamp(),
1194 'page_latest' => 0, // Fill this in shortly...
1195 'page_len' => 0, // Fill this in shortly...
1201 if ( $dbw->affectedRows() > 0 ) {
1202 $newid = $pageId ?
: $dbw->insertId();
1203 $this->mId
= $newid;
1204 $this->mTitle
->resetArticleID( $newid );
1208 return false; // nothing changed
1213 * Update the page record to point to a newly saved revision.
1215 * @param IDatabase $dbw
1216 * @param Revision $revision For ID number, and text used to set
1217 * length and redirect status fields
1218 * @param int $lastRevision If given, will not overwrite the page field
1219 * when different from the currently set value.
1220 * Giving 0 indicates the new page flag should be set on.
1221 * @param bool $lastRevIsRedirect If given, will optimize adding and
1222 * removing rows in redirect table.
1223 * @return bool Success; false if the page row was missing or page_latest changed
1225 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1226 $lastRevIsRedirect = null
1228 global $wgContentHandlerUseDB;
1230 // Assertion to try to catch T92046
1231 if ( (int)$revision->getId() === 0 ) {
1232 throw new InvalidArgumentException(
1233 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1237 $content = $revision->getContent();
1238 $len = $content ?
$content->getSize() : 0;
1239 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1241 $conditions = [ 'page_id' => $this->getId() ];
1243 if ( !is_null( $lastRevision ) ) {
1244 // An extra check against threads stepping on each other
1245 $conditions['page_latest'] = $lastRevision;
1249 'page_latest' => $revision->getId(),
1250 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1251 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1252 'page_is_redirect' => $rt !== null ?
1 : 0,
1256 if ( $wgContentHandlerUseDB ) {
1257 $row['page_content_model'] = $revision->getContentModel();
1260 $dbw->update( 'page',
1265 $result = $dbw->affectedRows() > 0;
1267 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1268 $this->setLastEdit( $revision );
1269 $this->mLatest
= $revision->getId();
1270 $this->mIsRedirect
= (bool)$rt;
1271 // Update the LinkCache.
1272 LinkCache
::singleton()->addGoodLinkObj(
1278 $revision->getContentModel()
1286 * Add row to the redirect table if this is a redirect, remove otherwise.
1288 * @param IDatabase $dbw
1289 * @param Title $redirectTitle Title object pointing to the redirect target,
1290 * or NULL if this is not a redirect
1291 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1292 * removing rows in redirect table.
1293 * @return bool True on success, false on failure
1296 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1297 // Always update redirects (target link might have changed)
1298 // Update/Insert if we don't know if the last revision was a redirect or not
1299 // Delete if changing from redirect to non-redirect
1300 $isRedirect = !is_null( $redirectTitle );
1302 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1306 if ( $isRedirect ) {
1307 $this->insertRedirectEntry( $redirectTitle );
1309 // This is not a redirect, remove row from redirect table
1310 $where = [ 'rd_from' => $this->getId() ];
1311 $dbw->delete( 'redirect', $where, __METHOD__
);
1314 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1315 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1318 return ( $dbw->affectedRows() != 0 );
1322 * If the given revision is newer than the currently set page_latest,
1323 * update the page record. Otherwise, do nothing.
1325 * @deprecated since 1.24, use updateRevisionOn instead
1327 * @param IDatabase $dbw
1328 * @param Revision $revision
1331 public function updateIfNewerOn( $dbw, $revision ) {
1333 $row = $dbw->selectRow(
1334 [ 'revision', 'page' ],
1335 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1337 'page_id' => $this->getId(),
1338 'page_latest=rev_id' ],
1342 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1345 $prev = $row->rev_id
;
1346 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1348 // No or missing previous revision; mark the page as new
1350 $lastRevIsRedirect = null;
1353 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1359 * Get the content that needs to be saved in order to undo all revisions
1360 * between $undo and $undoafter. Revisions must belong to the same page,
1361 * must exist and must not be deleted
1362 * @param Revision $undo
1363 * @param Revision $undoafter Must be an earlier revision than $undo
1364 * @return Content|bool Content on success, false on failure
1366 * Before we had the Content object, this was done in getUndoText
1368 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1369 $handler = $undo->getContentHandler();
1370 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1374 * Returns true if this page's content model supports sections.
1378 * @todo The skin should check this and not offer section functionality if
1379 * sections are not supported.
1380 * @todo The EditPage should check this and not offer section functionality
1381 * if sections are not supported.
1383 public function supportsSections() {
1384 return $this->getContentHandler()->supportsSections();
1388 * @param string|int|null|bool $sectionId Section identifier as a number or string
1389 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1390 * or 'new' for a new section.
1391 * @param Content $sectionContent New content of the section.
1392 * @param string $sectionTitle New section's subject, only if $section is "new".
1393 * @param string $edittime Revision timestamp or null to use the current revision.
1395 * @throws MWException
1396 * @return Content|null New complete article content, or null if error.
1399 * @deprecated since 1.24, use replaceSectionAtRev instead
1401 public function replaceSectionContent(
1402 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1406 if ( $edittime && $sectionId !== 'new' ) {
1407 $dbr = wfGetDB( DB_REPLICA
);
1408 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1409 // Try the master if this thread may have just added it.
1410 // This could be abstracted into a Revision method, but we don't want
1411 // to encourage loading of revisions by timestamp.
1413 && wfGetLB()->getServerCount() > 1
1414 && wfGetLB()->hasOrMadeRecentMasterChanges()
1416 $dbw = wfGetDB( DB_MASTER
);
1417 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1420 $baseRevId = $rev->getId();
1424 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1428 * @param string|int|null|bool $sectionId Section identifier as a number or string
1429 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1430 * or 'new' for a new section.
1431 * @param Content $sectionContent New content of the section.
1432 * @param string $sectionTitle New section's subject, only if $section is "new".
1433 * @param int|null $baseRevId
1435 * @throws MWException
1436 * @return Content|null New complete article content, or null if error.
1440 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1441 $sectionTitle = '', $baseRevId = null
1444 if ( strval( $sectionId ) === '' ) {
1445 // Whole-page edit; let the whole text through
1446 $newContent = $sectionContent;
1448 if ( !$this->supportsSections() ) {
1449 throw new MWException( "sections not supported for content model " .
1450 $this->getContentHandler()->getModelID() );
1453 // T32711: always use current version when adding a new section
1454 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1455 $oldContent = $this->getContent();
1457 $rev = Revision
::newFromId( $baseRevId );
1459 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1460 $this->getId() . "; section: $sectionId)\n" );
1464 $oldContent = $rev->getContent();
1467 if ( !$oldContent ) {
1468 wfDebug( __METHOD__
. ": no page text\n" );
1472 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1479 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1481 * @return int Updated $flags
1483 public function checkFlags( $flags ) {
1484 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1485 if ( $this->exists() ) {
1486 $flags |
= EDIT_UPDATE
;
1496 * Change an existing article or create a new article. Updates RC and all necessary caches,
1497 * optionally via the deferred update array.
1499 * @param Content $content New content
1500 * @param string $summary Edit summary
1501 * @param int $flags Bitfield:
1503 * Article is known or assumed to be non-existent, create a new one
1505 * Article is known or assumed to be pre-existing, update it
1507 * Mark this edit minor, if the user is allowed to do so
1509 * Do not log the change in recentchanges
1511 * Mark the edit a "bot" edit regardless of user rights
1513 * Fill in blank summaries with generated text where possible
1515 * Signal that the page retrieve/save cycle happened entirely in this request.
1517 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1518 * article will be detected. If EDIT_UPDATE is specified and the article
1519 * doesn't exist, the function will return an edit-gone-missing error. If
1520 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1521 * error will be returned. These two conditions are also possible with
1522 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1524 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1525 * This is not the parent revision ID, rather the revision ID for older
1526 * content used as the source for a rollback, for example.
1527 * @param User $user The user doing the edit
1528 * @param string $serialFormat Format for storing the content in the
1530 * @param array|null $tags Change tags to apply to this edit
1531 * Callers are responsible for permission checks
1532 * (with ChangeTags::canAddTagsAccompanyingChange)
1533 * @param Int $undidRevId Id of revision that was undone or 0
1535 * @throws MWException
1536 * @return Status Possible errors:
1537 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1538 * set the fatal flag of $status.
1539 * edit-gone-missing: In update mode, but the article didn't exist.
1540 * edit-conflict: In update mode, the article changed unexpectedly.
1541 * edit-no-change: Warning that the text was the same as before.
1542 * edit-already-exists: In creation mode, but the article already exists.
1544 * Extensions may define additional errors.
1546 * $return->value will contain an associative array with members as follows:
1547 * new: Boolean indicating if the function attempted to create a new article.
1548 * revision: The revision object for the inserted revision, or null.
1551 * @throws MWException
1553 public function doEditContent(
1554 Content
$content, $summary, $flags = 0, $baseRevId = false,
1555 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1557 global $wgUser, $wgUseAutomaticEditSummaries;
1559 // Old default parameter for $tags was null
1560 if ( $tags === null ) {
1564 // Low-level sanity check
1565 if ( $this->mTitle
->getText() === '' ) {
1566 throw new MWException( 'Something is trying to edit an article with an empty title' );
1568 // Make sure the given content type is allowed for this page
1569 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1570 return Status
::newFatal( 'content-not-allowed-here',
1571 ContentHandler
::getLocalizedName( $content->getModel() ),
1572 $this->mTitle
->getPrefixedText()
1576 // Load the data from the master database if needed.
1577 // The caller may already loaded it from the master or even loaded it using
1578 // SELECT FOR UPDATE, so do not override that using clear().
1579 $this->loadPageData( 'fromdbmaster' );
1581 $user = $user ?
: $wgUser;
1582 $flags = $this->checkFlags( $flags );
1584 // Avoid PHP 7.1 warning of passing $this by reference
1587 // Trigger pre-save hook (using provided edit summary)
1588 $hookStatus = Status
::newGood( [] );
1589 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1590 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1591 // Check if the hook rejected the attempted save
1592 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1593 if ( $hookStatus->isOK() ) {
1594 // Hook returned false but didn't call fatal(); use generic message
1595 $hookStatus->fatal( 'edit-hook-aborted' );
1601 $old_revision = $this->getRevision(); // current revision
1602 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1604 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1605 $tags[] = 'mw-contentmodelchange';
1608 // Provide autosummaries if one is not provided and autosummaries are enabled
1609 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1610 $handler = $content->getContentHandler();
1611 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1614 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1615 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1621 // Get the pre-save transform content and final parser output
1622 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1623 $pstContent = $editInfo->pstContent
; // Content object
1625 'bot' => ( $flags & EDIT_FORCE_BOT
),
1626 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1627 'serialized' => $editInfo->pst
,
1628 'serialFormat' => $serialFormat,
1629 'baseRevId' => $baseRevId,
1630 'oldRevision' => $old_revision,
1631 'oldContent' => $old_content,
1632 'oldId' => $this->getLatest(),
1633 'oldIsRedirect' => $this->isRedirect(),
1634 'oldCountable' => $this->isCountable(),
1635 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1636 'undidRevId' => $undidRevId
1639 // Actually create the revision and create/update the page
1640 if ( $flags & EDIT_UPDATE
) {
1641 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1643 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1646 // Promote user to any groups they meet the criteria for
1647 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1648 $user->addAutopromoteOnceGroups( 'onEdit' );
1649 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1656 * @param Content $content Pre-save transform content
1657 * @param integer $flags
1659 * @param string $summary
1660 * @param array $meta
1662 * @throws DBUnexpectedError
1664 * @throws FatalError
1665 * @throws MWException
1667 private function doModify(
1668 Content
$content, $flags, User
$user, $summary, array $meta
1670 global $wgUseRCPatrol;
1672 // Update article, but only if changed.
1673 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1675 // Convenience variables
1676 $now = wfTimestampNow();
1677 $oldid = $meta['oldId'];
1678 /** @var $oldContent Content|null */
1679 $oldContent = $meta['oldContent'];
1680 $newsize = $content->getSize();
1683 // Article gone missing
1684 $status->fatal( 'edit-gone-missing' );
1687 } elseif ( !$oldContent ) {
1688 // Sanity check for T39225
1689 throw new MWException( "Could not find text for current revision {$oldid}." );
1692 // @TODO: pass content object?!
1693 $revision = new Revision( [
1694 'page' => $this->getId(),
1695 'title' => $this->mTitle
, // for determining the default content model
1696 'comment' => $summary,
1697 'minor_edit' => $meta['minor'],
1698 'text' => $meta['serialized'],
1700 'parent_id' => $oldid,
1701 'user' => $user->getId(),
1702 'user_text' => $user->getName(),
1703 'timestamp' => $now,
1704 'content_model' => $content->getModel(),
1705 'content_format' => $meta['serialFormat'],
1708 $changed = !$content->equals( $oldContent );
1710 $dbw = wfGetDB( DB_MASTER
);
1713 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1714 $status->merge( $prepStatus );
1715 if ( !$status->isOK() ) {
1719 $dbw->startAtomic( __METHOD__
);
1720 // Get the latest page_latest value while locking it.
1721 // Do a CAS style check to see if it's the same as when this method
1722 // started. If it changed then bail out before touching the DB.
1723 $latestNow = $this->lockAndGetLatest();
1724 if ( $latestNow != $oldid ) {
1725 $dbw->endAtomic( __METHOD__
);
1726 // Page updated or deleted in the mean time
1727 $status->fatal( 'edit-conflict' );
1732 // At this point we are now comitted to returning an OK
1733 // status unless some DB query error or other exception comes up.
1734 // This way callers don't have to call rollback() if $status is bad
1735 // unless they actually try to catch exceptions (which is rare).
1737 // Save the revision text
1738 $revisionId = $revision->insertOn( $dbw );
1739 // Update page_latest and friends to reflect the new revision
1740 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1741 throw new MWException( "Failed to update page row to use new revision." );
1744 Hooks
::run( 'NewRevisionFromEditComplete',
1745 [ $this, $revision, $meta['baseRevId'], $user ] );
1747 // Update recentchanges
1748 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1749 // Mark as patrolled if the user can do so
1750 $patrolled = $wgUseRCPatrol && !count(
1751 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1752 // Add RC row to the DB
1753 RecentChange
::notifyEdit(
1756 $revision->isMinor(),
1760 $this->getTimestamp(),
1763 $oldContent ?
$oldContent->getSize() : 0,
1771 $user->incEditCount();
1773 $dbw->endAtomic( __METHOD__
);
1774 $this->mTimestamp
= $now;
1776 // T34948: revision ID must be set to page {{REVISIONID}} and
1777 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1778 $revision->setId( $this->getLatest() );
1779 $revision->setUserIdAndName(
1780 $this->getUser( Revision
::RAW
),
1781 $this->getUserText( Revision
::RAW
)
1786 // Return the new revision to the caller
1787 $status->value
['revision'] = $revision;
1789 $status->warning( 'edit-no-change' );
1790 // Update page_touched as updateRevisionOn() was not called.
1791 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1792 $this->mTitle
->invalidateCache( $now );
1795 // Do secondary updates once the main changes have been committed...
1796 DeferredUpdates
::addUpdate(
1797 new AtomicSectionUpdate(
1801 $revision, &$user, $content, $summary, &$flags,
1802 $changed, $meta, &$status
1804 // Update links tables, site stats, etc.
1805 $this->doEditUpdates(
1809 'changed' => $changed,
1810 'oldcountable' => $meta['oldCountable'],
1811 'oldrevision' => $meta['oldRevision']
1814 // Avoid PHP 7.1 warning of passing $this by reference
1816 // Trigger post-save hook
1817 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1818 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1819 $meta['undidRevId'] ];
1820 Hooks
::run( 'PageContentSaveComplete', $params );
1823 DeferredUpdates
::PRESEND
1830 * @param Content $content Pre-save transform content
1831 * @param integer $flags
1833 * @param string $summary
1834 * @param array $meta
1836 * @throws DBUnexpectedError
1838 * @throws FatalError
1839 * @throws MWException
1841 private function doCreate(
1842 Content
$content, $flags, User
$user, $summary, array $meta
1844 global $wgUseRCPatrol, $wgUseNPPatrol;
1846 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1848 $now = wfTimestampNow();
1849 $newsize = $content->getSize();
1850 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1851 $status->merge( $prepStatus );
1852 if ( !$status->isOK() ) {
1856 $dbw = wfGetDB( DB_MASTER
);
1857 $dbw->startAtomic( __METHOD__
);
1859 // Add the page record unless one already exists for the title
1860 $newid = $this->insertOn( $dbw );
1861 if ( $newid === false ) {
1862 $dbw->endAtomic( __METHOD__
); // nothing inserted
1863 $status->fatal( 'edit-already-exists' );
1865 return $status; // nothing done
1868 // At this point we are now comitted to returning an OK
1869 // status unless some DB query error or other exception comes up.
1870 // This way callers don't have to call rollback() if $status is bad
1871 // unless they actually try to catch exceptions (which is rare).
1873 // @TODO: pass content object?!
1874 $revision = new Revision( [
1876 'title' => $this->mTitle
, // for determining the default content model
1877 'comment' => $summary,
1878 'minor_edit' => $meta['minor'],
1879 'text' => $meta['serialized'],
1881 'user' => $user->getId(),
1882 'user_text' => $user->getName(),
1883 'timestamp' => $now,
1884 'content_model' => $content->getModel(),
1885 'content_format' => $meta['serialFormat'],
1888 // Save the revision text...
1889 $revisionId = $revision->insertOn( $dbw );
1890 // Update the page record with revision data
1891 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1892 throw new MWException( "Failed to update page row to use new revision." );
1895 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1897 // Update recentchanges
1898 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1899 // Mark as patrolled if the user can do so
1900 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1901 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1902 // Add RC row to the DB
1903 RecentChange
::notifyNew(
1906 $revision->isMinor(),
1918 $user->incEditCount();
1920 $dbw->endAtomic( __METHOD__
);
1921 $this->mTimestamp
= $now;
1923 // Return the new revision to the caller
1924 $status->value
['revision'] = $revision;
1926 // Do secondary updates once the main changes have been committed...
1927 DeferredUpdates
::addUpdate(
1928 new AtomicSectionUpdate(
1932 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1934 // Update links, etc.
1935 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1936 // Avoid PHP 7.1 warning of passing $this by reference
1938 // Trigger post-create hook
1939 $params = [ &$wikiPage, &$user, $content, $summary,
1940 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1941 Hooks
::run( 'PageContentInsertComplete', $params );
1942 // Trigger post-save hook
1943 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1944 Hooks
::run( 'PageContentSaveComplete', $params );
1947 DeferredUpdates
::PRESEND
1954 * Get parser options suitable for rendering the primary article wikitext
1956 * @see ContentHandler::makeParserOptions
1958 * @param IContextSource|User|string $context One of the following:
1959 * - IContextSource: Use the User and the Language of the provided
1961 * - User: Use the provided User object and $wgLang for the language,
1962 * so use an IContextSource object if possible.
1963 * - 'canonical': Canonical options (anonymous user with default
1964 * preferences and content language).
1965 * @return ParserOptions
1967 public function makeParserOptions( $context ) {
1968 $options = $this->getContentHandler()->makeParserOptions( $context );
1970 if ( $this->getTitle()->isConversionTable() ) {
1971 // @todo ConversionTable should become a separate content model, so
1972 // we don't need special cases like this one.
1973 $options->disableContentConversion();
1980 * Prepare content which is about to be saved.
1981 * Returns a stdClass with source, pst and output members
1983 * @param Content $content
1984 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1985 * revision ID is also accepted, but this is deprecated.
1986 * @param User|null $user
1987 * @param string|null $serialFormat
1988 * @param bool $useCache Check shared prepared edit cache
1994 public function prepareContentForEdit(
1995 Content
$content, $revision = null, User
$user = null,
1996 $serialFormat = null, $useCache = true
1998 global $wgContLang, $wgUser, $wgAjaxEditStash;
2000 if ( is_object( $revision ) ) {
2001 $revid = $revision->getId();
2004 // This code path is deprecated, and nothing is known to
2005 // use it, so performance here shouldn't be a worry.
2006 if ( $revid !== null ) {
2007 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2013 $user = is_null( $user ) ?
$wgUser : $user;
2014 // XXX: check $user->getId() here???
2016 // Use a sane default for $serialFormat, see T59026
2017 if ( $serialFormat === null ) {
2018 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2021 if ( $this->mPreparedEdit
2022 && isset( $this->mPreparedEdit
->newContent
)
2023 && $this->mPreparedEdit
->newContent
->equals( $content )
2024 && $this->mPreparedEdit
->revid
== $revid
2025 && $this->mPreparedEdit
->format
== $serialFormat
2026 // XXX: also check $user here?
2029 return $this->mPreparedEdit
;
2032 // The edit may have already been prepared via api.php?action=stashedit
2033 $cachedEdit = $useCache && $wgAjaxEditStash
2034 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2037 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2038 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2041 if ( $cachedEdit ) {
2042 $edit->timestamp
= $cachedEdit->timestamp
;
2044 $edit->timestamp
= wfTimestampNow();
2046 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2047 $edit->revid
= $revid;
2049 if ( $cachedEdit ) {
2050 $edit->pstContent
= $cachedEdit->pstContent
;
2052 $edit->pstContent
= $content
2053 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2057 $edit->format
= $serialFormat;
2058 $edit->popts
= $this->makeParserOptions( 'canonical' );
2059 if ( $cachedEdit ) {
2060 $edit->output
= $cachedEdit->output
;
2063 // We get here if vary-revision is set. This means that this page references
2064 // itself (such as via self-transclusion). In this case, we need to make sure
2065 // that any such self-references refer to the newly-saved revision, and not
2066 // to the previous one, which could otherwise happen due to replica DB lag.
2067 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2068 $edit->popts
->setCurrentRevisionCallback(
2069 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2070 if ( $title->equals( $revision->getTitle() ) ) {
2073 return call_user_func( $oldCallback, $title, $parser );
2078 // Try to avoid a second parse if {{REVISIONID}} is used
2079 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2080 ? DB_MASTER
// use the best possible guess
2081 : DB_REPLICA
; // T154554
2083 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2084 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2092 $edit->output
= $edit->pstContent
2093 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2097 $edit->newContent
= $content;
2098 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2100 // NOTE: B/C for hooks! don't use these fields!
2101 $edit->newText
= $edit->newContent
2102 ? ContentHandler
::getContentText( $edit->newContent
)
2104 $edit->oldText
= $edit->oldContent
2105 ? ContentHandler
::getContentText( $edit->oldContent
)
2107 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2109 if ( $edit->output
) {
2110 $edit->output
->setCacheTime( wfTimestampNow() );
2113 // Process cache the result
2114 $this->mPreparedEdit
= $edit;
2120 * Do standard deferred updates after page edit.
2121 * Update links tables, site stats, search index and message cache.
2122 * Purges pages that include this page if the text was changed here.
2123 * Every 100th edit, prune the recent changes table.
2125 * @param Revision $revision
2126 * @param User $user User object that did the revision
2127 * @param array $options Array of options, following indexes are used:
2128 * - changed: boolean, whether the revision changed the content (default true)
2129 * - created: boolean, whether the revision created the page (default false)
2130 * - moved: boolean, whether the page was moved (default false)
2131 * - restored: boolean, whether the page was undeleted (default false)
2132 * - oldrevision: Revision object for the pre-update revision (default null)
2133 * - oldcountable: boolean, null, or string 'no-change' (default null):
2134 * - boolean: whether the page was counted as an article before that
2135 * revision, only used in changed is true and created is false
2136 * - null: if created is false, don't update the article count; if created
2137 * is true, do update the article count
2138 * - 'no-change': don't update the article count, ever
2140 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2141 global $wgRCWatchCategoryMembership;
2147 'restored' => false,
2148 'oldrevision' => null,
2149 'oldcountable' => null
2151 $content = $revision->getContent();
2153 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2155 // See if the parser output before $revision was inserted is still valid
2157 if ( !$this->mPreparedEdit
) {
2158 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2159 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2160 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2161 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2162 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2164 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2165 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2166 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2168 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2169 $editInfo = $this->mPreparedEdit
;
2173 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2174 // $text is usually already pre-save transformed once. Avoid using the edit stash
2175 // as any prepared content from there or in doEditContent() was already rejected.
2176 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2179 // Save it to the parser cache.
2180 // Make sure the cache time matches page_touched to avoid double parsing.
2181 ParserCache
::singleton()->save(
2182 $editInfo->output
, $this, $editInfo->popts
,
2183 $revision->getTimestamp(), $editInfo->revid
2186 // Update the links tables and other secondary data
2188 $recursive = $options['changed']; // T52785
2189 $updates = $content->getSecondaryDataUpdates(
2190 $this->getTitle(), null, $recursive, $editInfo->output
2192 foreach ( $updates as $update ) {
2193 if ( $update instanceof LinksUpdate
) {
2194 $update->setRevision( $revision );
2195 $update->setTriggeringUser( $user );
2197 DeferredUpdates
::addUpdate( $update );
2199 if ( $wgRCWatchCategoryMembership
2200 && $this->getContentHandler()->supportsCategories() === true
2201 && ( $options['changed'] ||
$options['created'] )
2202 && !$options['restored']
2204 // Note: jobs are pushed after deferred updates, so the job should be able to see
2205 // the recent change entry (also done via deferred updates) and carry over any
2206 // bot/deletion/IP flags, ect.
2207 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2210 'pageId' => $this->getId(),
2211 'revTimestamp' => $revision->getTimestamp()
2217 // Avoid PHP 7.1 warning of passing $this by reference
2220 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2222 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2223 // Flush old entries from the `recentchanges` table
2224 if ( mt_rand( 0, 9 ) == 0 ) {
2225 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2229 if ( !$this->exists() ) {
2233 $id = $this->getId();
2234 $title = $this->mTitle
->getPrefixedDBkey();
2235 $shortTitle = $this->mTitle
->getDBkey();
2237 if ( $options['oldcountable'] === 'no-change' ||
2238 ( !$options['changed'] && !$options['moved'] )
2241 } elseif ( $options['created'] ) {
2242 $good = (int)$this->isCountable( $editInfo );
2243 } elseif ( $options['oldcountable'] !== null ) {
2244 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2248 $edits = $options['changed'] ?
1 : 0;
2249 $total = $options['created'] ?
1 : 0;
2251 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2252 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2254 // If this is another user's talk page, update newtalk.
2255 // Don't do this if $options['changed'] = false (null-edits) nor if
2256 // it's a minor edit and the user doesn't want notifications for those.
2257 if ( $options['changed']
2258 && $this->mTitle
->getNamespace() == NS_USER_TALK
2259 && $shortTitle != $user->getTitleKey()
2260 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2262 $recipient = User
::newFromName( $shortTitle, false );
2263 if ( !$recipient ) {
2264 wfDebug( __METHOD__
. ": invalid username\n" );
2266 // Avoid PHP 7.1 warning of passing $this by reference
2269 // Allow extensions to prevent user notification
2270 // when a new message is added to their talk page
2271 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2272 if ( User
::isIP( $shortTitle ) ) {
2273 // An anonymous user
2274 $recipient->setNewtalk( true, $revision );
2275 } elseif ( $recipient->isLoggedIn() ) {
2276 $recipient->setNewtalk( true, $revision );
2278 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2284 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2285 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2288 if ( $options['created'] ) {
2289 self
::onArticleCreate( $this->mTitle
);
2290 } elseif ( $options['changed'] ) { // T52785
2291 self
::onArticleEdit( $this->mTitle
, $revision );
2294 ResourceLoaderWikiModule
::invalidateModuleCache(
2295 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2300 * Update the article's restriction field, and leave a log entry.
2301 * This works for protection both existing and non-existing pages.
2303 * @param array $limit Set of restriction keys
2304 * @param array $expiry Per restriction type expiration
2305 * @param int &$cascade Set to false if cascading protection isn't allowed.
2306 * @param string $reason
2307 * @param User $user The user updating the restrictions
2308 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2309 * ($user should be able to add the specified tags before this is called)
2310 * @return Status Status object; if action is taken, $status->value is the log_id of the
2311 * protection log entry.
2313 public function doUpdateRestrictions( array $limit, array $expiry,
2314 &$cascade, $reason, User
$user, $tags = null
2316 global $wgCascadingRestrictionLevels, $wgContLang;
2318 if ( wfReadOnly() ) {
2319 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2322 $this->loadPageData( 'fromdbmaster' );
2323 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2324 $id = $this->getId();
2330 // Take this opportunity to purge out expired restrictions
2331 Title
::purgeExpiredRestrictions();
2333 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2334 // we expect a single selection, but the schema allows otherwise.
2335 $isProtected = false;
2339 $dbw = wfGetDB( DB_MASTER
);
2341 foreach ( $restrictionTypes as $action ) {
2342 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2343 $expiry[$action] = 'infinity';
2345 if ( !isset( $limit[$action] ) ) {
2346 $limit[$action] = '';
2347 } elseif ( $limit[$action] != '' ) {
2351 // Get current restrictions on $action
2352 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2353 if ( $current != '' ) {
2354 $isProtected = true;
2357 if ( $limit[$action] != $current ) {
2359 } elseif ( $limit[$action] != '' ) {
2360 // Only check expiry change if the action is actually being
2361 // protected, since expiry does nothing on an not-protected
2363 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2369 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2373 // If nothing has changed, do nothing
2375 return Status
::newGood();
2378 if ( !$protect ) { // No protection at all means unprotection
2379 $revCommentMsg = 'unprotectedarticle-comment';
2380 $logAction = 'unprotect';
2381 } elseif ( $isProtected ) {
2382 $revCommentMsg = 'modifiedarticleprotection-comment';
2383 $logAction = 'modify';
2385 $revCommentMsg = 'protectedarticle-comment';
2386 $logAction = 'protect';
2389 // Truncate for whole multibyte characters
2390 $reason = $wgContLang->truncate( $reason, 255 );
2392 $logRelationsValues = [];
2393 $logRelationsField = null;
2394 $logParamsDetails = [];
2396 // Null revision (used for change tag insertion)
2397 $nullRevision = null;
2399 if ( $id ) { // Protection of existing page
2400 // Avoid PHP 7.1 warning of passing $this by reference
2403 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2404 return Status
::newGood();
2407 // Only certain restrictions can cascade...
2408 $editrestriction = isset( $limit['edit'] )
2409 ?
[ $limit['edit'] ]
2410 : $this->mTitle
->getRestrictions( 'edit' );
2411 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2412 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2414 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2415 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2418 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2419 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2420 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2422 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2423 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2426 // The schema allows multiple restrictions
2427 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2431 // insert null revision to identify the page protection change as edit summary
2432 $latest = $this->getLatest();
2433 $nullRevision = $this->insertProtectNullRevision(
2442 if ( $nullRevision === null ) {
2443 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2446 $logRelationsField = 'pr_id';
2448 // Update restrictions table
2449 foreach ( $limit as $action => $restrictions ) {
2451 'page_restrictions',
2454 'pr_type' => $action
2458 if ( $restrictions != '' ) {
2459 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2461 'page_restrictions',
2463 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2465 'pr_type' => $action,
2466 'pr_level' => $restrictions,
2467 'pr_cascade' => $cascadeValue,
2468 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2472 $logRelationsValues[] = $dbw->insertId();
2473 $logParamsDetails[] = [
2475 'level' => $restrictions,
2476 'expiry' => $expiry[$action],
2477 'cascade' => (bool)$cascadeValue,
2482 // Clear out legacy restriction fields
2485 [ 'page_restrictions' => '' ],
2486 [ 'page_id' => $id ],
2490 // Avoid PHP 7.1 warning of passing $this by reference
2493 Hooks
::run( 'NewRevisionFromEditComplete',
2494 [ $this, $nullRevision, $latest, $user ] );
2495 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2496 } else { // Protection of non-existing page (also known as "title protection")
2497 // Cascade protection is meaningless in this case
2500 if ( $limit['create'] != '' ) {
2501 $dbw->replace( 'protected_titles',
2502 [ [ 'pt_namespace', 'pt_title' ] ],
2504 'pt_namespace' => $this->mTitle
->getNamespace(),
2505 'pt_title' => $this->mTitle
->getDBkey(),
2506 'pt_create_perm' => $limit['create'],
2507 'pt_timestamp' => $dbw->timestamp(),
2508 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2509 'pt_user' => $user->getId(),
2510 'pt_reason' => $reason,
2513 $logParamsDetails[] = [
2515 'level' => $limit['create'],
2516 'expiry' => $expiry['create'],
2519 $dbw->delete( 'protected_titles',
2521 'pt_namespace' => $this->mTitle
->getNamespace(),
2522 'pt_title' => $this->mTitle
->getDBkey()
2528 $this->mTitle
->flushRestrictions();
2529 InfoAction
::invalidateCache( $this->mTitle
);
2531 if ( $logAction == 'unprotect' ) {
2534 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2536 '4::description' => $protectDescriptionLog, // parameter for IRC
2537 '5:bool:cascade' => $cascade,
2538 'details' => $logParamsDetails, // parameter for localize and api
2542 // Update the protection log
2543 $logEntry = new ManualLogEntry( 'protect', $logAction );
2544 $logEntry->setTarget( $this->mTitle
);
2545 $logEntry->setComment( $reason );
2546 $logEntry->setPerformer( $user );
2547 $logEntry->setParameters( $params );
2548 if ( !is_null( $nullRevision ) ) {
2549 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2551 $logEntry->setTags( $tags );
2552 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2553 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2555 $logId = $logEntry->insert();
2556 $logEntry->publish( $logId );
2558 return Status
::newGood( $logId );
2562 * Insert a new null revision for this page.
2564 * @param string $revCommentMsg Comment message key for the revision
2565 * @param array $limit Set of restriction keys
2566 * @param array $expiry Per restriction type expiration
2567 * @param int $cascade Set to false if cascading protection isn't allowed.
2568 * @param string $reason
2569 * @param User|null $user
2570 * @return Revision|null Null on error
2572 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2573 array $expiry, $cascade, $reason, $user = null
2575 $dbw = wfGetDB( DB_MASTER
);
2577 // Prepare a null revision to be added to the history
2578 $editComment = wfMessage(
2580 $this->mTitle
->getPrefixedText(),
2581 $user ?
$user->getName() : ''
2582 )->inContentLanguage()->text();
2584 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2586 $protectDescription = $this->protectDescription( $limit, $expiry );
2587 if ( $protectDescription ) {
2588 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2589 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2590 ->inContentLanguage()->text();
2593 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2594 $editComment .= wfMessage( 'brackets' )->params(
2595 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2596 )->inContentLanguage()->text();
2599 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2601 $nullRev->insertOn( $dbw );
2603 // Update page record and touch page
2604 $oldLatest = $nullRev->getParentId();
2605 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2612 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2615 protected function formatExpiry( $expiry ) {
2618 if ( $expiry != 'infinity' ) {
2621 $wgContLang->timeanddate( $expiry, false, false ),
2622 $wgContLang->date( $expiry, false, false ),
2623 $wgContLang->time( $expiry, false, false )
2624 )->inContentLanguage()->text();
2626 return wfMessage( 'protect-expiry-indefinite' )
2627 ->inContentLanguage()->text();
2632 * Builds the description to serve as comment for the edit.
2634 * @param array $limit Set of restriction keys
2635 * @param array $expiry Per restriction type expiration
2638 public function protectDescription( array $limit, array $expiry ) {
2639 $protectDescription = '';
2641 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2642 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2643 # All possible message keys are listed here for easier grepping:
2644 # * restriction-create
2645 # * restriction-edit
2646 # * restriction-move
2647 # * restriction-upload
2648 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2649 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2650 # with '' filtered out. All possible message keys are listed below:
2651 # * protect-level-autoconfirmed
2652 # * protect-level-sysop
2653 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2654 ->inContentLanguage()->text();
2656 $expiryText = $this->formatExpiry( $expiry[$action] );
2658 if ( $protectDescription !== '' ) {
2659 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2661 $protectDescription .= wfMessage( 'protect-summary-desc' )
2662 ->params( $actionText, $restrictionsText, $expiryText )
2663 ->inContentLanguage()->text();
2666 return $protectDescription;
2670 * Builds the description to serve as comment for the log entry.
2672 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2673 * protect description text. Keep them in old format to avoid breaking compatibility.
2674 * TODO: Fix protection log to store structured description and format it on-the-fly.
2676 * @param array $limit Set of restriction keys
2677 * @param array $expiry Per restriction type expiration
2680 public function protectDescriptionLog( array $limit, array $expiry ) {
2683 $protectDescriptionLog = '';
2685 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2686 $expiryText = $this->formatExpiry( $expiry[$action] );
2687 $protectDescriptionLog .= $wgContLang->getDirMark() .
2688 "[$action=$restrictions] ($expiryText)";
2691 return trim( $protectDescriptionLog );
2695 * Take an array of page restrictions and flatten it to a string
2696 * suitable for insertion into the page_restrictions field.
2698 * @param string[] $limit
2700 * @throws MWException
2703 protected static function flattenRestrictions( $limit ) {
2704 if ( !is_array( $limit ) ) {
2705 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2711 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2712 $bits[] = "$action=$restrictions";
2715 return implode( ':', $bits );
2719 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2720 * backwards compatibility, if you care about error reporting you should use
2721 * doDeleteArticleReal() instead.
2723 * Deletes the article with database consistency, writes logs, purges caches
2725 * @param string $reason Delete reason for deletion log
2726 * @param bool $suppress Suppress all revisions and log the deletion in
2727 * the suppression log instead of the deletion log
2728 * @param int $u1 Unused
2729 * @param bool $u2 Unused
2730 * @param array|string &$error Array of errors to append to
2731 * @param User $user The deleting user
2732 * @return bool True if successful
2734 public function doDeleteArticle(
2735 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2737 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2738 return $status->isGood();
2742 * Back-end article deletion
2743 * Deletes the article with database consistency, writes logs, purges caches
2747 * @param string $reason Delete reason for deletion log
2748 * @param bool $suppress Suppress all revisions and log the deletion in
2749 * the suppression log instead of the deletion log
2750 * @param int $u1 Unused
2751 * @param bool $u2 Unused
2752 * @param array|string &$error Array of errors to append to
2753 * @param User $user The deleting user
2754 * @param array $tags Tags to apply to the deletion action
2755 * @return Status Status object; if successful, $status->value is the log_id of the
2756 * deletion log entry. If the page couldn't be deleted because it wasn't
2757 * found, $status is a non-fatal 'cannotdelete' error
2759 public function doDeleteArticleReal(
2760 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2761 $tags = [], $logsubtype = 'delete'
2763 global $wgUser, $wgContentHandlerUseDB;
2765 wfDebug( __METHOD__
. "\n" );
2767 $status = Status
::newGood();
2769 if ( $this->mTitle
->getDBkey() === '' ) {
2770 $status->error( 'cannotdelete',
2771 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2775 // Avoid PHP 7.1 warning of passing $this by reference
2778 $user = is_null( $user ) ?
$wgUser : $user;
2779 if ( !Hooks
::run( 'ArticleDelete',
2780 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2782 if ( $status->isOK() ) {
2783 // Hook aborted but didn't set a fatal status
2784 $status->fatal( 'delete-hook-aborted' );
2789 $dbw = wfGetDB( DB_MASTER
);
2790 $dbw->startAtomic( __METHOD__
);
2792 $this->loadPageData( self
::READ_LATEST
);
2793 $id = $this->getId();
2794 // T98706: lock the page from various other updates but avoid using
2795 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2796 // the revisions queries (which also JOIN on user). Only lock the page
2797 // row and CAS check on page_latest to see if the trx snapshot matches.
2798 $lockedLatest = $this->lockAndGetLatest();
2799 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2800 $dbw->endAtomic( __METHOD__
);
2801 // Page not there or trx snapshot is stale
2802 $status->error( 'cannotdelete',
2803 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2807 // Given the lock above, we can be confident in the title and page ID values
2808 $namespace = $this->getTitle()->getNamespace();
2809 $dbKey = $this->getTitle()->getDBkey();
2811 // At this point we are now comitted to returning an OK
2812 // status unless some DB query error or other exception comes up.
2813 // This way callers don't have to call rollback() if $status is bad
2814 // unless they actually try to catch exceptions (which is rare).
2816 // we need to remember the old content so we can use it to generate all deletion updates.
2817 $revision = $this->getRevision();
2819 $content = $this->getContent( Revision
::RAW
);
2820 } catch ( Exception
$ex ) {
2821 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2822 . $ex->getMessage() );
2827 $fields = Revision
::selectFields();
2830 // Bitfields to further suppress the content
2832 $bitfield = Revision
::SUPPRESSED_ALL
;
2833 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2836 // For now, shunt the revision data into the archive table.
2837 // Text is *not* removed from the text table; bulk storage
2838 // is left intact to avoid breaking block-compression or
2839 // immutable storage schemes.
2840 // In the future, we may keep revisions and mark them with
2841 // the rev_deleted field, which is reserved for this purpose.
2843 // Get all of the page revisions
2844 $res = $dbw->select(
2847 [ 'rev_page' => $id ],
2851 // Build their equivalent archive rows
2853 foreach ( $res as $row ) {
2855 'ar_namespace' => $namespace,
2856 'ar_title' => $dbKey,
2857 'ar_comment' => $row->rev_comment
,
2858 'ar_user' => $row->rev_user
,
2859 'ar_user_text' => $row->rev_user_text
,
2860 'ar_timestamp' => $row->rev_timestamp
,
2861 'ar_minor_edit' => $row->rev_minor_edit
,
2862 'ar_rev_id' => $row->rev_id
,
2863 'ar_parent_id' => $row->rev_parent_id
,
2864 'ar_text_id' => $row->rev_text_id
,
2867 'ar_len' => $row->rev_len
,
2868 'ar_page_id' => $id,
2869 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2870 'ar_sha1' => $row->rev_sha1
,
2872 if ( $wgContentHandlerUseDB ) {
2873 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2874 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2876 $rowsInsert[] = $rowInsert;
2878 // Copy them into the archive table
2879 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2880 // Save this so we can pass it to the ArticleDeleteComplete hook.
2881 $archivedRevisionCount = $dbw->affectedRows();
2883 // Clone the title and wikiPage, so we have the information we need when
2884 // we log and run the ArticleDeleteComplete hook.
2885 $logTitle = clone $this->mTitle
;
2886 $wikiPageBeforeDelete = clone $this;
2888 // Now that it's safely backed up, delete it
2889 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2890 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2892 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2893 $logtype = $suppress ?
'suppress' : 'delete';
2895 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2896 $logEntry->setPerformer( $user );
2897 $logEntry->setTarget( $logTitle );
2898 $logEntry->setComment( $reason );
2899 $logEntry->setTags( $tags );
2900 $logid = $logEntry->insert();
2902 $dbw->onTransactionPreCommitOrIdle(
2903 function () use ( $dbw, $logEntry, $logid ) {
2904 // T58776: avoid deadlocks (especially from FileDeleteForm)
2905 $logEntry->publish( $logid );
2910 $dbw->endAtomic( __METHOD__
);
2912 $this->doDeleteUpdates( $id, $content, $revision );
2914 Hooks
::run( 'ArticleDeleteComplete', [
2915 &$wikiPageBeforeDelete,
2921 $archivedRevisionCount
2923 $status->value
= $logid;
2925 // Show log excerpt on 404 pages rather than just a link
2926 $cache = ObjectCache
::getMainStashInstance();
2927 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2928 $cache->set( $key, 1, $cache::TTL_DAY
);
2934 * Lock the page row for this title+id and return page_latest (or 0)
2936 * @return integer Returns 0 if no row was found with this title+id
2939 public function lockAndGetLatest() {
2940 return (int)wfGetDB( DB_MASTER
)->selectField(
2944 'page_id' => $this->getId(),
2945 // Typically page_id is enough, but some code might try to do
2946 // updates assuming the title is the same, so verify that
2947 'page_namespace' => $this->getTitle()->getNamespace(),
2948 'page_title' => $this->getTitle()->getDBkey()
2956 * Do some database updates after deletion
2958 * @param int $id The page_id value of the page being deleted
2959 * @param Content|null $content Optional page content to be used when determining
2960 * the required updates. This may be needed because $this->getContent()
2961 * may already return null when the page proper was deleted.
2962 * @param Revision|null $revision The latest page revision
2964 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2966 $countable = $this->isCountable();
2967 } catch ( Exception
$ex ) {
2968 // fallback for deleting broken pages for which we cannot load the content for
2969 // some reason. Note that doDeleteArticleReal() already logged this problem.
2973 // Update site status
2974 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2976 // Delete pagelinks, update secondary indexes, etc
2977 $updates = $this->getDeletionUpdates( $content );
2978 foreach ( $updates as $update ) {
2979 DeferredUpdates
::addUpdate( $update );
2982 // Reparse any pages transcluding this page
2983 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2985 // Reparse any pages including this image
2986 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2987 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2991 WikiPage
::onArticleDelete( $this->mTitle
);
2992 ResourceLoaderWikiModule
::invalidateModuleCache(
2993 $this->mTitle
, $revision, null, wfWikiID()
2996 // Reset this object and the Title object
2997 $this->loadFromRow( false, self
::READ_LATEST
);
3000 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3004 * Roll back the most recent consecutive set of edits to a page
3005 * from the same user; fails if there are no eligible edits to
3006 * roll back to, e.g. user is the sole contributor. This function
3007 * performs permissions checks on $user, then calls commitRollback()
3008 * to do the dirty work
3010 * @todo Separate the business/permission stuff out from backend code
3011 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3013 * @param string $fromP Name of the user whose edits to rollback.
3014 * @param string $summary Custom summary. Set to default summary if empty.
3015 * @param string $token Rollback token.
3016 * @param bool $bot If true, mark all reverted edits as bot.
3018 * @param array $resultDetails Array contains result-specific array of additional values
3019 * 'alreadyrolled' : 'current' (rev)
3020 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3022 * @param User $user The user performing the rollback
3023 * @param array|null $tags Change tags to apply to the rollback
3024 * Callers are responsible for permission checks
3025 * (with ChangeTags::canAddTagsAccompanyingChange)
3027 * @return array Array of errors, each error formatted as
3028 * array(messagekey, param1, param2, ...).
3029 * On success, the array is empty. This array can also be passed to
3030 * OutputPage::showPermissionsErrorPage().
3032 public function doRollback(
3033 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3035 $resultDetails = null;
3037 // Check permissions
3038 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3039 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3040 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3042 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3043 $errors[] = [ 'sessionfailure' ];
3046 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3047 $errors[] = [ 'actionthrottledtext' ];
3050 // If there were errors, bail out now
3051 if ( !empty( $errors ) ) {
3055 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3059 * Backend implementation of doRollback(), please refer there for parameter
3060 * and return value documentation
3062 * NOTE: This function does NOT check ANY permissions, it just commits the
3063 * rollback to the DB. Therefore, you should only call this function direct-
3064 * ly if you want to use custom permissions checks. If you don't, use
3065 * doRollback() instead.
3066 * @param string $fromP Name of the user whose edits to rollback.
3067 * @param string $summary Custom summary. Set to default summary if empty.
3068 * @param bool $bot If true, mark all reverted edits as bot.
3070 * @param array $resultDetails Contains result-specific array of additional values
3071 * @param User $guser The user performing the rollback
3072 * @param array|null $tags Change tags to apply to the rollback
3073 * Callers are responsible for permission checks
3074 * (with ChangeTags::canAddTagsAccompanyingChange)
3078 public function commitRollback( $fromP, $summary, $bot,
3079 &$resultDetails, User
$guser, $tags = null
3081 global $wgUseRCPatrol, $wgContLang;
3083 $dbw = wfGetDB( DB_MASTER
);
3085 if ( wfReadOnly() ) {
3086 return [ [ 'readonlytext' ] ];
3089 // Get the last editor
3090 $current = $this->getRevision();
3091 if ( is_null( $current ) ) {
3092 // Something wrong... no page?
3093 return [ [ 'notanarticle' ] ];
3096 $from = str_replace( '_', ' ', $fromP );
3097 // User name given should match up with the top revision.
3098 // If the user was deleted then $from should be empty.
3099 if ( $from != $current->getUserText() ) {
3100 $resultDetails = [ 'current' => $current ];
3101 return [ [ 'alreadyrolled',
3102 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3103 htmlspecialchars( $fromP ),
3104 htmlspecialchars( $current->getUserText() )
3108 // Get the last edit not by this person...
3109 // Note: these may not be public values
3110 $user = intval( $current->getUser( Revision
::RAW
) );
3111 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3112 $s = $dbw->selectRow( 'revision',
3113 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3114 [ 'rev_page' => $current->getPage(),
3115 "rev_user != {$user} OR rev_user_text != {$user_text}"
3117 [ 'USE INDEX' => 'page_timestamp',
3118 'ORDER BY' => 'rev_timestamp DESC' ]
3120 if ( $s === false ) {
3121 // No one else ever edited this page
3122 return [ [ 'cantrollback' ] ];
3123 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3124 ||
$s->rev_deleted
& Revision
::DELETED_USER
3126 // Only admins can see this text
3127 return [ [ 'notvisiblerev' ] ];
3130 // Generate the edit summary if necessary
3131 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3132 if ( empty( $summary ) ) {
3133 if ( $from == '' ) { // no public user name
3134 $summary = wfMessage( 'revertpage-nouser' );
3136 $summary = wfMessage( 'revertpage' );
3140 // Allow the custom summary to use the same args as the default message
3142 $target->getUserText(), $from, $s->rev_id
,
3143 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3144 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3146 if ( $summary instanceof Message
) {
3147 $summary = $summary->params( $args )->inContentLanguage()->text();
3149 $summary = wfMsgReplaceArgs( $summary, $args );
3152 // Trim spaces on user supplied text
3153 $summary = trim( $summary );
3155 // Truncate for whole multibyte characters.
3156 $summary = $wgContLang->truncate( $summary, 255 );
3159 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3161 if ( $guser->isAllowed( 'minoredit' ) ) {
3162 $flags |
= EDIT_MINOR
;
3165 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3166 $flags |
= EDIT_FORCE_BOT
;
3169 $targetContent = $target->getContent();
3170 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3172 // Actually store the edit
3173 $status = $this->doEditContent(
3183 // Set patrolling and bot flag on the edits, which gets rollbacked.
3184 // This is done even on edit failure to have patrolling in that case (T64157).
3186 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3187 // Mark all reverted edits as bot
3191 if ( $wgUseRCPatrol ) {
3192 // Mark all reverted edits as patrolled
3193 $set['rc_patrolled'] = 1;
3196 if ( count( $set ) ) {
3197 $dbw->update( 'recentchanges', $set,
3199 'rc_cur_id' => $current->getPage(),
3200 'rc_user_text' => $current->getUserText(),
3201 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3207 if ( !$status->isOK() ) {
3208 return $status->getErrorsArray();
3211 // raise error, when the edit is an edit without a new version
3212 $statusRev = isset( $status->value
['revision'] )
3213 ?
$status->value
['revision']
3215 if ( !( $statusRev instanceof Revision
) ) {
3216 $resultDetails = [ 'current' => $current ];
3217 return [ [ 'alreadyrolled',
3218 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3219 htmlspecialchars( $fromP ),
3220 htmlspecialchars( $current->getUserText() )
3224 if ( $changingContentModel ) {
3225 // If the content model changed during the rollback,
3226 // make sure it gets logged to Special:Log/contentmodel
3227 $log = new ManualLogEntry( 'contentmodel', 'change' );
3228 $log->setPerformer( $guser );
3229 $log->setTarget( $this->mTitle
);
3230 $log->setComment( $summary );
3231 $log->setParameters( [
3232 '4::oldmodel' => $current->getContentModel(),
3233 '5::newmodel' => $targetContent->getModel(),
3236 $logId = $log->insert( $dbw );
3237 $log->publish( $logId );
3240 $revId = $statusRev->getId();
3242 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3245 'summary' => $summary,
3246 'current' => $current,
3247 'target' => $target,
3255 * The onArticle*() functions are supposed to be a kind of hooks
3256 * which should be called whenever any of the specified actions
3259 * This is a good place to put code to clear caches, for instance.
3261 * This is called on page move and undelete, as well as edit
3263 * @param Title $title
3265 public static function onArticleCreate( Title
$title ) {
3266 // Update existence markers on article/talk tabs...
3267 $other = $title->getOtherPage();
3269 $other->purgeSquid();
3271 $title->touchLinks();
3272 $title->purgeSquid();
3273 $title->deleteTitleProtection();
3275 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3277 if ( $title->getNamespace() == NS_CATEGORY
) {
3278 // Load the Category object, which will schedule a job to create
3279 // the category table row if necessary. Checking a replica DB is ok
3280 // here, in the worst case it'll run an unnecessary recount job on
3281 // a category that probably doesn't have many members.
3282 Category
::newFromTitle( $title )->getID();
3287 * Clears caches when article is deleted
3289 * @param Title $title
3291 public static function onArticleDelete( Title
$title ) {
3292 // Update existence markers on article/talk tabs...
3293 $other = $title->getOtherPage();
3295 $other->purgeSquid();
3297 $title->touchLinks();
3298 $title->purgeSquid();
3300 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3303 HTMLFileCache
::clearFileCache( $title );
3304 InfoAction
::invalidateCache( $title );
3307 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3308 MessageCache
::singleton()->updateMessageOverride( $title, null );
3312 if ( $title->getNamespace() == NS_FILE
) {
3313 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3317 if ( $title->getNamespace() == NS_USER_TALK
) {
3318 $user = User
::newFromName( $title->getText(), false );
3320 $user->setNewtalk( false );
3325 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3329 * Purge caches on page update etc
3331 * @param Title $title
3332 * @param Revision|null $revision Revision that was just saved, may be null
3334 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3335 // Invalidate caches of articles which include this page
3336 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3338 // Invalidate the caches of all pages which redirect here
3339 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3341 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3343 // Purge CDN for this page only
3344 $title->purgeSquid();
3345 // Clear file cache for this page only
3346 HTMLFileCache
::clearFileCache( $title );
3348 $revid = $revision ?
$revision->getId() : null;
3349 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3350 InfoAction
::invalidateCache( $title, $revid );
3357 * Returns a list of categories this page is a member of.
3358 * Results will include hidden categories
3360 * @return TitleArray
3362 public function getCategories() {
3363 $id = $this->getId();
3365 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3368 $dbr = wfGetDB( DB_REPLICA
);
3369 $res = $dbr->select( 'categorylinks',
3370 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3371 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3372 // as not being aliases, and NS_CATEGORY is numeric
3373 [ 'cl_from' => $id ],
3376 return TitleArray
::newFromResult( $res );
3380 * Returns a list of hidden categories this page is a member of.
3381 * Uses the page_props and categorylinks tables.
3383 * @return array Array of Title objects
3385 public function getHiddenCategories() {
3387 $id = $this->getId();
3393 $dbr = wfGetDB( DB_REPLICA
);
3394 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3396 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3397 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3400 if ( $res !== false ) {
3401 foreach ( $res as $row ) {
3402 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3410 * Auto-generates a deletion reason
3412 * @param bool &$hasHistory Whether the page has a history
3413 * @return string|bool String containing deletion reason or empty string, or boolean false
3414 * if no revision occurred
3416 public function getAutoDeleteReason( &$hasHistory ) {
3417 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3421 * Update all the appropriate counts in the category table, given that
3422 * we've added the categories $added and deleted the categories $deleted.
3424 * This should only be called from deferred updates or jobs to avoid contention.
3426 * @param array $added The names of categories that were added
3427 * @param array $deleted The names of categories that were deleted
3428 * @param integer $id Page ID (this should be the original deleted page ID)
3430 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3431 $id = $id ?
: $this->getId();
3432 $ns = $this->getTitle()->getNamespace();
3434 $addFields = [ 'cat_pages = cat_pages + 1' ];
3435 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3436 if ( $ns == NS_CATEGORY
) {
3437 $addFields[] = 'cat_subcats = cat_subcats + 1';
3438 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3439 } elseif ( $ns == NS_FILE
) {
3440 $addFields[] = 'cat_files = cat_files + 1';
3441 $removeFields[] = 'cat_files = cat_files - 1';
3444 $dbw = wfGetDB( DB_MASTER
);
3446 if ( count( $added ) ) {
3447 $existingAdded = $dbw->selectFieldValues(
3450 [ 'cat_title' => $added ],
3454 // For category rows that already exist, do a plain
3455 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3456 // to avoid creating gaps in the cat_id sequence.
3457 if ( count( $existingAdded ) ) {
3461 [ 'cat_title' => $existingAdded ],
3466 $missingAdded = array_diff( $added, $existingAdded );
3467 if ( count( $missingAdded ) ) {
3469 foreach ( $missingAdded as $cat ) {
3471 'cat_title' => $cat,
3473 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3474 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3487 if ( count( $deleted ) ) {
3491 [ 'cat_title' => $deleted ],
3496 foreach ( $added as $catName ) {
3497 $cat = Category
::newFromName( $catName );
3498 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3501 foreach ( $deleted as $catName ) {
3502 $cat = Category
::newFromName( $catName );
3503 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3506 // Refresh counts on categories that should be empty now, to
3507 // trigger possible deletion. Check master for the most
3508 // up-to-date cat_pages.
3509 if ( count( $deleted ) ) {
3510 $rows = $dbw->select(
3512 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3513 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3516 foreach ( $rows as $row ) {
3517 $cat = Category
::newFromRow( $row );
3518 $cat->refreshCounts();
3524 * Opportunistically enqueue link update jobs given fresh parser output if useful
3526 * @param ParserOutput $parserOutput Current version page output
3529 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3530 if ( wfReadOnly() ) {
3534 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3535 [ $this, $this->mTitle
, $parserOutput ]
3540 $config = RequestContext
::getMain()->getConfig();
3543 'isOpportunistic' => true,
3544 'rootJobTimestamp' => $parserOutput->getCacheTime()
3547 if ( $this->mTitle
->areRestrictionsCascading() ) {
3548 // If the page is cascade protecting, the links should really be up-to-date
3549 JobQueueGroup
::singleton()->lazyPush(
3550 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3552 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3553 // Assume the output contains "dynamic" time/random based magic words.
3554 // Only update pages that expired due to dynamic content and NOT due to edits
3555 // to referenced templates/files. When the cache expires due to dynamic content,
3556 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3557 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3558 // template/file edit already triggered recursive RefreshLinksJob jobs.
3559 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3560 // If a page is uncacheable, do not keep spamming a job for it.
3561 // Although it would be de-duplicated, it would still waste I/O.
3562 $cache = ObjectCache
::getLocalClusterInstance();
3563 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3564 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3565 if ( $cache->add( $key, time(), $ttl ) ) {
3566 JobQueueGroup
::singleton()->lazyPush(
3567 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3575 * Returns a list of updates to be performed when this page is deleted. The
3576 * updates should remove any information about this page from secondary data
3577 * stores such as links tables.
3579 * @param Content|null $content Optional Content object for determining the
3580 * necessary updates.
3581 * @return DeferrableUpdate[]
3583 public function getDeletionUpdates( Content
$content = null ) {
3585 // load content object, which may be used to determine the necessary updates.
3586 // XXX: the content may not be needed to determine the updates.
3588 $content = $this->getContent( Revision
::RAW
);
3589 } catch ( Exception
$ex ) {
3590 // If we can't load the content, something is wrong. Perhaps that's why
3591 // the user is trying to delete the page, so let's not fail in that case.
3592 // Note that doDeleteArticleReal() will already have logged an issue with
3593 // loading the content.
3600 $updates = $content->getDeletionUpdates( $this );
3603 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3608 * Whether this content displayed on this page
3609 * comes from the local database
3614 public function isLocal() {
3619 * The display name for the site this content
3620 * come from. If a subclass overrides isLocal(),
3621 * this could return something other than the
3627 public function getWikiDisplayName() {
3633 * Get the source URL for the content on this page,
3634 * typically the canonical URL, but may be a remote
3635 * link if the content comes from another site
3640 public function getSourceURL() {
3641 return $this->getTitle()->getCanonicalURL();
3645 * @param WANObjectCache $cache
3649 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3650 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3652 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );