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() {
579 // Try using the replica DB first, then try the master
580 $rev = $this->mTitle
->getFirstRevision();
582 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
588 * Loads everything except the text
589 * This isn't necessary for all uses, so it's only done if needed.
591 protected function loadLastEdit() {
592 if ( $this->mLastRevision
!== null ) {
593 return; // already loaded
596 $latest = $this->getLatest();
598 return; // page doesn't exist or is missing page_latest info
601 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
602 // T39225: if session S1 loads the page row FOR UPDATE, the result always
603 // includes the latest changes committed. This is true even within REPEATABLE-READ
604 // transactions, where S1 normally only sees changes committed before the first S1
605 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
606 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
607 // happened after the first S1 SELECT.
608 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
609 $flags = Revision
::READ_LOCKING
;
610 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
611 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
612 // Bug T93976: if page_latest was loaded from the master, fetch the
613 // revision from there as well, as it may not exist yet on a replica DB.
614 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
615 $flags = Revision
::READ_LATEST
;
616 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
618 $dbr = wfGetDB( DB_REPLICA
);
619 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
622 if ( $revision ) { // sanity
623 $this->setLastEdit( $revision );
628 * Set the latest revision
629 * @param Revision $revision
631 protected function setLastEdit( Revision
$revision ) {
632 $this->mLastRevision
= $revision;
633 $this->mTimestamp
= $revision->getTimestamp();
637 * Get the latest revision
638 * @return Revision|null
640 public function getRevision() {
641 $this->loadLastEdit();
642 if ( $this->mLastRevision
) {
643 return $this->mLastRevision
;
649 * Get the content of the current revision. No side-effects...
651 * @param int $audience One of:
652 * Revision::FOR_PUBLIC to be displayed to all users
653 * Revision::FOR_THIS_USER to be displayed to $wgUser
654 * Revision::RAW get the text regardless of permissions
655 * @param User $user User object to check for, only if FOR_THIS_USER is passed
656 * to the $audience parameter
657 * @return Content|null The content of the current revision
661 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
662 $this->loadLastEdit();
663 if ( $this->mLastRevision
) {
664 return $this->mLastRevision
->getContent( $audience, $user );
670 * @return string MW timestamp of last article revision
672 public function getTimestamp() {
673 // Check if the field has been filled by WikiPage::setTimestamp()
674 if ( !$this->mTimestamp
) {
675 $this->loadLastEdit();
678 return wfTimestamp( TS_MW
, $this->mTimestamp
);
682 * Set the page timestamp (use only to avoid DB queries)
683 * @param string $ts MW timestamp of last article revision
686 public function setTimestamp( $ts ) {
687 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
691 * @param int $audience One of:
692 * Revision::FOR_PUBLIC to be displayed to all users
693 * Revision::FOR_THIS_USER to be displayed to the given user
694 * Revision::RAW get the text regardless of permissions
695 * @param User $user User object to check for, only if FOR_THIS_USER is passed
696 * to the $audience parameter
697 * @return int User ID for the user that made the last article revision
699 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
700 $this->loadLastEdit();
701 if ( $this->mLastRevision
) {
702 return $this->mLastRevision
->getUser( $audience, $user );
709 * Get the User object of the user who created the page
710 * @param int $audience One of:
711 * Revision::FOR_PUBLIC to be displayed to all users
712 * Revision::FOR_THIS_USER to be displayed to the given user
713 * Revision::RAW get the text regardless of permissions
714 * @param User $user User object to check for, only if FOR_THIS_USER is passed
715 * to the $audience parameter
718 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
719 $revision = $this->getOldestRevision();
721 $userName = $revision->getUserText( $audience, $user );
722 return User
::newFromName( $userName, false );
729 * @param int $audience One of:
730 * Revision::FOR_PUBLIC to be displayed to all users
731 * Revision::FOR_THIS_USER to be displayed to the given user
732 * Revision::RAW get the text regardless of permissions
733 * @param User $user User object to check for, only if FOR_THIS_USER is passed
734 * to the $audience parameter
735 * @return string Username of the user that made the last article revision
737 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
738 $this->loadLastEdit();
739 if ( $this->mLastRevision
) {
740 return $this->mLastRevision
->getUserText( $audience, $user );
747 * @param int $audience One of:
748 * Revision::FOR_PUBLIC to be displayed to all users
749 * Revision::FOR_THIS_USER to be displayed to the given user
750 * Revision::RAW get the text regardless of permissions
751 * @param User $user User object to check for, only if FOR_THIS_USER is passed
752 * to the $audience parameter
753 * @return string Comment stored for the last article revision
755 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
756 $this->loadLastEdit();
757 if ( $this->mLastRevision
) {
758 return $this->mLastRevision
->getComment( $audience, $user );
765 * Returns true if last revision was marked as "minor edit"
767 * @return bool Minor edit indicator for the last article revision.
769 public function getMinorEdit() {
770 $this->loadLastEdit();
771 if ( $this->mLastRevision
) {
772 return $this->mLastRevision
->isMinor();
779 * Determine whether a page would be suitable for being counted as an
780 * article in the site_stats table based on the title & its content
782 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
783 * if false, the current database state will be used
786 public function isCountable( $editInfo = false ) {
787 global $wgArticleCountMethod;
789 if ( !$this->mTitle
->isContentPage() ) {
794 $content = $editInfo->pstContent
;
796 $content = $this->getContent();
799 if ( !$content ||
$content->isRedirect() ) {
805 if ( $wgArticleCountMethod === 'link' ) {
806 // nasty special case to avoid re-parsing to detect links
809 // ParserOutput::getLinks() is a 2D array of page links, so
810 // to be really correct we would need to recurse in the array
811 // but the main array should only have items in it if there are
813 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
815 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
816 [ 'pl_from' => $this->getId() ], __METHOD__
);
820 return $content->isCountable( $hasLinks );
824 * If this page is a redirect, get its target
826 * The target will be fetched from the redirect table if possible.
827 * If this page doesn't have an entry there, call insertRedirect()
828 * @return Title|null Title object, or null if this page is not a redirect
830 public function getRedirectTarget() {
831 if ( !$this->mTitle
->isRedirect() ) {
835 if ( $this->mRedirectTarget
!== null ) {
836 return $this->mRedirectTarget
;
839 // Query the redirect table
840 $dbr = wfGetDB( DB_REPLICA
);
841 $row = $dbr->selectRow( 'redirect',
842 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
843 [ 'rd_from' => $this->getId() ],
847 // rd_fragment and rd_interwiki were added later, populate them if empty
848 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
849 $this->mRedirectTarget
= Title
::makeTitle(
850 $row->rd_namespace
, $row->rd_title
,
851 $row->rd_fragment
, $row->rd_interwiki
853 return $this->mRedirectTarget
;
856 // This page doesn't have an entry in the redirect table
857 $this->mRedirectTarget
= $this->insertRedirect();
858 return $this->mRedirectTarget
;
862 * Insert an entry for this page into the redirect table if the content is a redirect
864 * The database update will be deferred via DeferredUpdates
866 * Don't call this function directly unless you know what you're doing.
867 * @return Title|null Title object or null if not a redirect
869 public function insertRedirect() {
870 $content = $this->getContent();
871 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
876 // Update the DB post-send if the page has not cached since now
878 $latest = $this->getLatest();
879 DeferredUpdates
::addCallableUpdate(
880 function () use ( $that, $retval, $latest ) {
881 $that->insertRedirectEntry( $retval, $latest );
883 DeferredUpdates
::POSTSEND
,
891 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
892 * @param Title $rt Redirect target
893 * @param int|null $oldLatest Prior page_latest for check and set
895 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
896 $dbw = wfGetDB( DB_MASTER
);
897 $dbw->startAtomic( __METHOD__
);
899 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
903 'rd_from' => $this->getId(),
904 'rd_namespace' => $rt->getNamespace(),
905 'rd_title' => $rt->getDBkey(),
906 'rd_fragment' => $rt->getFragment(),
907 'rd_interwiki' => $rt->getInterwiki(),
911 'rd_namespace' => $rt->getNamespace(),
912 'rd_title' => $rt->getDBkey(),
913 'rd_fragment' => $rt->getFragment(),
914 'rd_interwiki' => $rt->getInterwiki(),
920 $dbw->endAtomic( __METHOD__
);
924 * Get the Title object or URL this page redirects to
926 * @return bool|Title|string False, Title of in-wiki target, or string with URL
928 public function followRedirect() {
929 return $this->getRedirectURL( $this->getRedirectTarget() );
933 * Get the Title object or URL to use for a redirect. We use Title
934 * objects for same-wiki, non-special redirects and URLs for everything
936 * @param Title $rt Redirect target
937 * @return bool|Title|string False, Title object of local target, or string with URL
939 public function getRedirectURL( $rt ) {
944 if ( $rt->isExternal() ) {
945 if ( $rt->isLocal() ) {
946 // Offsite wikis need an HTTP redirect.
947 // This can be hard to reverse and may produce loops,
948 // so they may be disabled in the site configuration.
949 $source = $this->mTitle
->getFullURL( 'redirect=no' );
950 return $rt->getFullURL( [ 'rdfrom' => $source ] );
952 // External pages without "local" bit set are not valid
958 if ( $rt->isSpecialPage() ) {
959 // Gotta handle redirects to special pages differently:
960 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
961 // Some pages are not valid targets.
962 if ( $rt->isValidRedirectTarget() ) {
963 return $rt->getFullURL();
973 * Get a list of users who have edited this article, not including the user who made
974 * the most recent revision, which you can get from $article->getUser() if you want it
975 * @return UserArrayFromResult
977 public function getContributors() {
978 // @todo FIXME: This is expensive; cache this info somewhere.
980 $dbr = wfGetDB( DB_REPLICA
);
982 if ( $dbr->implicitGroupby() ) {
983 $realNameField = 'user_real_name';
985 $realNameField = 'MIN(user_real_name) AS user_real_name';
988 $tables = [ 'revision', 'user' ];
991 'user_id' => 'rev_user',
992 'user_name' => 'rev_user_text',
994 'timestamp' => 'MAX(rev_timestamp)',
997 $conds = [ 'rev_page' => $this->getId() ];
999 // The user who made the top revision gets credited as "this page was last edited by
1000 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1001 $user = $this->getUser();
1003 $conds[] = "rev_user != $user";
1005 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1009 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1012 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1016 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1017 'ORDER BY' => 'timestamp DESC',
1020 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1021 return new UserArrayFromResult( $res );
1025 * Should the parser cache be used?
1027 * @param ParserOptions $parserOptions ParserOptions to check
1031 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1032 return $parserOptions->getStubThreshold() == 0
1034 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1035 && $this->getContentHandler()->isParserCacheSupported();
1039 * Get a ParserOutput for the given ParserOptions and revision ID.
1041 * The parser cache will be used if possible. Cache misses that result
1042 * in parser runs are debounced with PoolCounter.
1045 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1046 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1047 * get the current revision (default value)
1048 * @param bool $forceParse Force reindexing, regardless of cache settings
1049 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1051 public function getParserOutput(
1052 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1055 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1056 wfDebug( __METHOD__
.
1057 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1058 if ( $parserOptions->getStubThreshold() ) {
1059 wfIncrStats( 'pcache.miss.stub' );
1062 if ( $useParserCache ) {
1063 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1064 if ( $parserOutput !== false ) {
1065 return $parserOutput;
1069 if ( $oldid === null ||
$oldid === 0 ) {
1070 $oldid = $this->getLatest();
1073 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1076 return $pool->getParserOutput();
1080 * Do standard deferred updates after page view (existing or missing page)
1081 * @param User $user The relevant user
1082 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1084 public function doViewUpdates( User
$user, $oldid = 0 ) {
1085 if ( wfReadOnly() ) {
1089 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1090 // Update newtalk / watchlist notification status
1092 $user->clearNotification( $this->mTitle
, $oldid );
1093 } catch ( DBError
$e ) {
1094 // Avoid outage if the master is not reachable
1095 MWExceptionHandler
::logException( $e );
1100 * Perform the actions of a page purging
1102 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1103 * controlled how much purging was done.
1105 public function doPurge() {
1106 // Avoid PHP 7.1 warning of passing $this by reference
1109 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1113 $this->mTitle
->invalidateCache();
1116 HTMLFileCache
::clearFileCache( $this->getTitle() );
1117 // Send purge after above page_touched update was committed
1118 DeferredUpdates
::addUpdate(
1119 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1120 DeferredUpdates
::PRESEND
1123 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1124 $messageCache = MessageCache
::singleton();
1125 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1132 * Get the last time a user explicitly purged the page via action=purge
1134 * @return string|bool TS_MW timestamp or false
1136 * @deprecated since 1.29. It will always return false.
1138 public function getLastPurgeTimestamp() {
1139 wfDeprecated( __METHOD__
, '1.29' );
1144 * Insert a new empty page record for this article.
1145 * This *must* be followed up by creating a revision
1146 * and running $this->updateRevisionOn( ... );
1147 * or else the record will be left in a funky state.
1148 * Best if all done inside a transaction.
1150 * @param IDatabase $dbw
1151 * @param int|null $pageId Custom page ID that will be used for the insert statement
1153 * @return bool|int The newly created page_id key; false if the row was not
1154 * inserted, e.g. because the title already existed or because the specified
1155 * page ID is already in use.
1157 public function insertOn( $dbw, $pageId = null ) {
1158 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1162 'page_id' => $pageIdForInsert,
1163 'page_namespace' => $this->mTitle
->getNamespace(),
1164 'page_title' => $this->mTitle
->getDBkey(),
1165 'page_restrictions' => '',
1166 'page_is_redirect' => 0, // Will set this shortly...
1168 'page_random' => wfRandom(),
1169 'page_touched' => $dbw->timestamp(),
1170 'page_latest' => 0, // Fill this in shortly...
1171 'page_len' => 0, // Fill this in shortly...
1177 if ( $dbw->affectedRows() > 0 ) {
1178 $newid = $pageId ?
: $dbw->insertId();
1179 $this->mId
= $newid;
1180 $this->mTitle
->resetArticleID( $newid );
1184 return false; // nothing changed
1189 * Update the page record to point to a newly saved revision.
1191 * @param IDatabase $dbw
1192 * @param Revision $revision For ID number, and text used to set
1193 * length and redirect status fields
1194 * @param int $lastRevision If given, will not overwrite the page field
1195 * when different from the currently set value.
1196 * Giving 0 indicates the new page flag should be set on.
1197 * @param bool $lastRevIsRedirect If given, will optimize adding and
1198 * removing rows in redirect table.
1199 * @return bool Success; false if the page row was missing or page_latest changed
1201 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1202 $lastRevIsRedirect = null
1204 global $wgContentHandlerUseDB;
1206 // Assertion to try to catch T92046
1207 if ( (int)$revision->getId() === 0 ) {
1208 throw new InvalidArgumentException(
1209 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1213 $content = $revision->getContent();
1214 $len = $content ?
$content->getSize() : 0;
1215 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1217 $conditions = [ 'page_id' => $this->getId() ];
1219 if ( !is_null( $lastRevision ) ) {
1220 // An extra check against threads stepping on each other
1221 $conditions['page_latest'] = $lastRevision;
1225 'page_latest' => $revision->getId(),
1226 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1227 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1228 'page_is_redirect' => $rt !== null ?
1 : 0,
1232 if ( $wgContentHandlerUseDB ) {
1233 $row['page_content_model'] = $revision->getContentModel();
1236 $dbw->update( 'page',
1241 $result = $dbw->affectedRows() > 0;
1243 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1244 $this->setLastEdit( $revision );
1245 $this->mLatest
= $revision->getId();
1246 $this->mIsRedirect
= (bool)$rt;
1247 // Update the LinkCache.
1248 LinkCache
::singleton()->addGoodLinkObj(
1254 $revision->getContentModel()
1262 * Add row to the redirect table if this is a redirect, remove otherwise.
1264 * @param IDatabase $dbw
1265 * @param Title $redirectTitle Title object pointing to the redirect target,
1266 * or NULL if this is not a redirect
1267 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1268 * removing rows in redirect table.
1269 * @return bool True on success, false on failure
1272 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1273 // Always update redirects (target link might have changed)
1274 // Update/Insert if we don't know if the last revision was a redirect or not
1275 // Delete if changing from redirect to non-redirect
1276 $isRedirect = !is_null( $redirectTitle );
1278 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1282 if ( $isRedirect ) {
1283 $this->insertRedirectEntry( $redirectTitle );
1285 // This is not a redirect, remove row from redirect table
1286 $where = [ 'rd_from' => $this->getId() ];
1287 $dbw->delete( 'redirect', $where, __METHOD__
);
1290 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1291 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1294 return ( $dbw->affectedRows() != 0 );
1298 * If the given revision is newer than the currently set page_latest,
1299 * update the page record. Otherwise, do nothing.
1301 * @deprecated since 1.24, use updateRevisionOn instead
1303 * @param IDatabase $dbw
1304 * @param Revision $revision
1307 public function updateIfNewerOn( $dbw, $revision ) {
1309 $row = $dbw->selectRow(
1310 [ 'revision', 'page' ],
1311 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1313 'page_id' => $this->getId(),
1314 'page_latest=rev_id' ],
1318 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1321 $prev = $row->rev_id
;
1322 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1324 // No or missing previous revision; mark the page as new
1326 $lastRevIsRedirect = null;
1329 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1335 * Get the content that needs to be saved in order to undo all revisions
1336 * between $undo and $undoafter. Revisions must belong to the same page,
1337 * must exist and must not be deleted
1338 * @param Revision $undo
1339 * @param Revision $undoafter Must be an earlier revision than $undo
1340 * @return Content|bool Content on success, false on failure
1342 * Before we had the Content object, this was done in getUndoText
1344 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1345 $handler = $undo->getContentHandler();
1346 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1350 * Returns true if this page's content model supports sections.
1354 * @todo The skin should check this and not offer section functionality if
1355 * sections are not supported.
1356 * @todo The EditPage should check this and not offer section functionality
1357 * if sections are not supported.
1359 public function supportsSections() {
1360 return $this->getContentHandler()->supportsSections();
1364 * @param string|int|null|bool $sectionId Section identifier as a number or string
1365 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1366 * or 'new' for a new section.
1367 * @param Content $sectionContent New content of the section.
1368 * @param string $sectionTitle New section's subject, only if $section is "new".
1369 * @param string $edittime Revision timestamp or null to use the current revision.
1371 * @throws MWException
1372 * @return Content|null New complete article content, or null if error.
1375 * @deprecated since 1.24, use replaceSectionAtRev instead
1377 public function replaceSectionContent(
1378 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1382 if ( $edittime && $sectionId !== 'new' ) {
1383 $dbr = wfGetDB( DB_REPLICA
);
1384 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1385 // Try the master if this thread may have just added it.
1386 // This could be abstracted into a Revision method, but we don't want
1387 // to encourage loading of revisions by timestamp.
1389 && wfGetLB()->getServerCount() > 1
1390 && wfGetLB()->hasOrMadeRecentMasterChanges()
1392 $dbw = wfGetDB( DB_MASTER
);
1393 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1396 $baseRevId = $rev->getId();
1400 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1404 * @param string|int|null|bool $sectionId Section identifier as a number or string
1405 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1406 * or 'new' for a new section.
1407 * @param Content $sectionContent New content of the section.
1408 * @param string $sectionTitle New section's subject, only if $section is "new".
1409 * @param int|null $baseRevId
1411 * @throws MWException
1412 * @return Content|null New complete article content, or null if error.
1416 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1417 $sectionTitle = '', $baseRevId = null
1420 if ( strval( $sectionId ) === '' ) {
1421 // Whole-page edit; let the whole text through
1422 $newContent = $sectionContent;
1424 if ( !$this->supportsSections() ) {
1425 throw new MWException( "sections not supported for content model " .
1426 $this->getContentHandler()->getModelID() );
1429 // T32711: always use current version when adding a new section
1430 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1431 $oldContent = $this->getContent();
1433 $rev = Revision
::newFromId( $baseRevId );
1435 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1436 $this->getId() . "; section: $sectionId)\n" );
1440 $oldContent = $rev->getContent();
1443 if ( !$oldContent ) {
1444 wfDebug( __METHOD__
. ": no page text\n" );
1448 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1455 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1457 * @return int Updated $flags
1459 public function checkFlags( $flags ) {
1460 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1461 if ( $this->exists() ) {
1462 $flags |
= EDIT_UPDATE
;
1472 * Change an existing article or create a new article. Updates RC and all necessary caches,
1473 * optionally via the deferred update array.
1475 * @param Content $content New content
1476 * @param string $summary Edit summary
1477 * @param int $flags Bitfield:
1479 * Article is known or assumed to be non-existent, create a new one
1481 * Article is known or assumed to be pre-existing, update it
1483 * Mark this edit minor, if the user is allowed to do so
1485 * Do not log the change in recentchanges
1487 * Mark the edit a "bot" edit regardless of user rights
1489 * Fill in blank summaries with generated text where possible
1491 * Signal that the page retrieve/save cycle happened entirely in this request.
1493 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1494 * article will be detected. If EDIT_UPDATE is specified and the article
1495 * doesn't exist, the function will return an edit-gone-missing error. If
1496 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1497 * error will be returned. These two conditions are also possible with
1498 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1500 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1501 * This is not the parent revision ID, rather the revision ID for older
1502 * content used as the source for a rollback, for example.
1503 * @param User $user The user doing the edit
1504 * @param string $serialFormat Format for storing the content in the
1506 * @param array|null $tags Change tags to apply to this edit
1507 * Callers are responsible for permission checks
1508 * (with ChangeTags::canAddTagsAccompanyingChange)
1509 * @param Int $undidRevId Id of revision that was undone or 0
1511 * @throws MWException
1512 * @return Status Possible errors:
1513 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1514 * set the fatal flag of $status.
1515 * edit-gone-missing: In update mode, but the article didn't exist.
1516 * edit-conflict: In update mode, the article changed unexpectedly.
1517 * edit-no-change: Warning that the text was the same as before.
1518 * edit-already-exists: In creation mode, but the article already exists.
1520 * Extensions may define additional errors.
1522 * $return->value will contain an associative array with members as follows:
1523 * new: Boolean indicating if the function attempted to create a new article.
1524 * revision: The revision object for the inserted revision, or null.
1527 * @throws MWException
1529 public function doEditContent(
1530 Content
$content, $summary, $flags = 0, $baseRevId = false,
1531 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1533 global $wgUser, $wgUseAutomaticEditSummaries;
1535 // Old default parameter for $tags was null
1536 if ( $tags === null ) {
1540 // Low-level sanity check
1541 if ( $this->mTitle
->getText() === '' ) {
1542 throw new MWException( 'Something is trying to edit an article with an empty title' );
1544 // Make sure the given content type is allowed for this page
1545 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1546 return Status
::newFatal( 'content-not-allowed-here',
1547 ContentHandler
::getLocalizedName( $content->getModel() ),
1548 $this->mTitle
->getPrefixedText()
1552 // Load the data from the master database if needed.
1553 // The caller may already loaded it from the master or even loaded it using
1554 // SELECT FOR UPDATE, so do not override that using clear().
1555 $this->loadPageData( 'fromdbmaster' );
1557 $user = $user ?
: $wgUser;
1558 $flags = $this->checkFlags( $flags );
1560 // Avoid PHP 7.1 warning of passing $this by reference
1563 // Trigger pre-save hook (using provided edit summary)
1564 $hookStatus = Status
::newGood( [] );
1565 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1566 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1567 // Check if the hook rejected the attempted save
1568 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1569 if ( $hookStatus->isOK() ) {
1570 // Hook returned false but didn't call fatal(); use generic message
1571 $hookStatus->fatal( 'edit-hook-aborted' );
1577 $old_revision = $this->getRevision(); // current revision
1578 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1580 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1581 $tags[] = 'mw-contentmodelchange';
1584 // Provide autosummaries if one is not provided and autosummaries are enabled
1585 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1586 $handler = $content->getContentHandler();
1587 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1590 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1591 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1597 // Get the pre-save transform content and final parser output
1598 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1599 $pstContent = $editInfo->pstContent
; // Content object
1601 'bot' => ( $flags & EDIT_FORCE_BOT
),
1602 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1603 'serialized' => $editInfo->pst
,
1604 'serialFormat' => $serialFormat,
1605 'baseRevId' => $baseRevId,
1606 'oldRevision' => $old_revision,
1607 'oldContent' => $old_content,
1608 'oldId' => $this->getLatest(),
1609 'oldIsRedirect' => $this->isRedirect(),
1610 'oldCountable' => $this->isCountable(),
1611 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1612 'undidRevId' => $undidRevId
1615 // Actually create the revision and create/update the page
1616 if ( $flags & EDIT_UPDATE
) {
1617 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1619 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1622 // Promote user to any groups they meet the criteria for
1623 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1624 $user->addAutopromoteOnceGroups( 'onEdit' );
1625 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1632 * @param Content $content Pre-save transform content
1633 * @param integer $flags
1635 * @param string $summary
1636 * @param array $meta
1638 * @throws DBUnexpectedError
1640 * @throws FatalError
1641 * @throws MWException
1643 private function doModify(
1644 Content
$content, $flags, User
$user, $summary, array $meta
1646 global $wgUseRCPatrol;
1648 // Update article, but only if changed.
1649 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1651 // Convenience variables
1652 $now = wfTimestampNow();
1653 $oldid = $meta['oldId'];
1654 /** @var $oldContent Content|null */
1655 $oldContent = $meta['oldContent'];
1656 $newsize = $content->getSize();
1659 // Article gone missing
1660 $status->fatal( 'edit-gone-missing' );
1663 } elseif ( !$oldContent ) {
1664 // Sanity check for T39225
1665 throw new MWException( "Could not find text for current revision {$oldid}." );
1668 // @TODO: pass content object?!
1669 $revision = new Revision( [
1670 'page' => $this->getId(),
1671 'title' => $this->mTitle
, // for determining the default content model
1672 'comment' => $summary,
1673 'minor_edit' => $meta['minor'],
1674 'text' => $meta['serialized'],
1676 'parent_id' => $oldid,
1677 'user' => $user->getId(),
1678 'user_text' => $user->getName(),
1679 'timestamp' => $now,
1680 'content_model' => $content->getModel(),
1681 'content_format' => $meta['serialFormat'],
1684 $changed = !$content->equals( $oldContent );
1686 $dbw = wfGetDB( DB_MASTER
);
1689 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1690 $status->merge( $prepStatus );
1691 if ( !$status->isOK() ) {
1695 $dbw->startAtomic( __METHOD__
);
1696 // Get the latest page_latest value while locking it.
1697 // Do a CAS style check to see if it's the same as when this method
1698 // started. If it changed then bail out before touching the DB.
1699 $latestNow = $this->lockAndGetLatest();
1700 if ( $latestNow != $oldid ) {
1701 $dbw->endAtomic( __METHOD__
);
1702 // Page updated or deleted in the mean time
1703 $status->fatal( 'edit-conflict' );
1708 // At this point we are now comitted to returning an OK
1709 // status unless some DB query error or other exception comes up.
1710 // This way callers don't have to call rollback() if $status is bad
1711 // unless they actually try to catch exceptions (which is rare).
1713 // Save the revision text
1714 $revisionId = $revision->insertOn( $dbw );
1715 // Update page_latest and friends to reflect the new revision
1716 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1717 throw new MWException( "Failed to update page row to use new revision." );
1720 Hooks
::run( 'NewRevisionFromEditComplete',
1721 [ $this, $revision, $meta['baseRevId'], $user ] );
1723 // Update recentchanges
1724 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1725 // Mark as patrolled if the user can do so
1726 $patrolled = $wgUseRCPatrol && !count(
1727 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1728 // Add RC row to the DB
1729 RecentChange
::notifyEdit(
1732 $revision->isMinor(),
1736 $this->getTimestamp(),
1739 $oldContent ?
$oldContent->getSize() : 0,
1747 $user->incEditCount();
1749 $dbw->endAtomic( __METHOD__
);
1750 $this->mTimestamp
= $now;
1752 // T34948: revision ID must be set to page {{REVISIONID}} and
1753 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1754 $revision->setId( $this->getLatest() );
1755 $revision->setUserIdAndName(
1756 $this->getUser( Revision
::RAW
),
1757 $this->getUserText( Revision
::RAW
)
1762 // Return the new revision to the caller
1763 $status->value
['revision'] = $revision;
1765 $status->warning( 'edit-no-change' );
1766 // Update page_touched as updateRevisionOn() was not called.
1767 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1768 $this->mTitle
->invalidateCache( $now );
1771 // Do secondary updates once the main changes have been committed...
1772 DeferredUpdates
::addUpdate(
1773 new AtomicSectionUpdate(
1777 $revision, &$user, $content, $summary, &$flags,
1778 $changed, $meta, &$status
1780 // Update links tables, site stats, etc.
1781 $this->doEditUpdates(
1785 'changed' => $changed,
1786 'oldcountable' => $meta['oldCountable'],
1787 'oldrevision' => $meta['oldRevision']
1790 // Avoid PHP 7.1 warning of passing $this by reference
1792 // Trigger post-save hook
1793 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1794 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1795 $meta['undidRevId'] ];
1796 Hooks
::run( 'PageContentSaveComplete', $params );
1799 DeferredUpdates
::PRESEND
1806 * @param Content $content Pre-save transform content
1807 * @param integer $flags
1809 * @param string $summary
1810 * @param array $meta
1812 * @throws DBUnexpectedError
1814 * @throws FatalError
1815 * @throws MWException
1817 private function doCreate(
1818 Content
$content, $flags, User
$user, $summary, array $meta
1820 global $wgUseRCPatrol, $wgUseNPPatrol;
1822 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1824 $now = wfTimestampNow();
1825 $newsize = $content->getSize();
1826 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1827 $status->merge( $prepStatus );
1828 if ( !$status->isOK() ) {
1832 $dbw = wfGetDB( DB_MASTER
);
1833 $dbw->startAtomic( __METHOD__
);
1835 // Add the page record unless one already exists for the title
1836 $newid = $this->insertOn( $dbw );
1837 if ( $newid === false ) {
1838 $dbw->endAtomic( __METHOD__
); // nothing inserted
1839 $status->fatal( 'edit-already-exists' );
1841 return $status; // nothing done
1844 // At this point we are now comitted to returning an OK
1845 // status unless some DB query error or other exception comes up.
1846 // This way callers don't have to call rollback() if $status is bad
1847 // unless they actually try to catch exceptions (which is rare).
1849 // @TODO: pass content object?!
1850 $revision = new Revision( [
1852 'title' => $this->mTitle
, // for determining the default content model
1853 'comment' => $summary,
1854 'minor_edit' => $meta['minor'],
1855 'text' => $meta['serialized'],
1857 'user' => $user->getId(),
1858 'user_text' => $user->getName(),
1859 'timestamp' => $now,
1860 'content_model' => $content->getModel(),
1861 'content_format' => $meta['serialFormat'],
1864 // Save the revision text...
1865 $revisionId = $revision->insertOn( $dbw );
1866 // Update the page record with revision data
1867 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1868 throw new MWException( "Failed to update page row to use new revision." );
1871 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1873 // Update recentchanges
1874 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1875 // Mark as patrolled if the user can do so
1876 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1877 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1878 // Add RC row to the DB
1879 RecentChange
::notifyNew(
1882 $revision->isMinor(),
1894 $user->incEditCount();
1896 $dbw->endAtomic( __METHOD__
);
1897 $this->mTimestamp
= $now;
1899 // Return the new revision to the caller
1900 $status->value
['revision'] = $revision;
1902 // Do secondary updates once the main changes have been committed...
1903 DeferredUpdates
::addUpdate(
1904 new AtomicSectionUpdate(
1908 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1910 // Update links, etc.
1911 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1912 // Avoid PHP 7.1 warning of passing $this by reference
1914 // Trigger post-create hook
1915 $params = [ &$wikiPage, &$user, $content, $summary,
1916 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1917 Hooks
::run( 'PageContentInsertComplete', $params );
1918 // Trigger post-save hook
1919 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1920 Hooks
::run( 'PageContentSaveComplete', $params );
1923 DeferredUpdates
::PRESEND
1930 * Get parser options suitable for rendering the primary article wikitext
1932 * @see ContentHandler::makeParserOptions
1934 * @param IContextSource|User|string $context One of the following:
1935 * - IContextSource: Use the User and the Language of the provided
1937 * - User: Use the provided User object and $wgLang for the language,
1938 * so use an IContextSource object if possible.
1939 * - 'canonical': Canonical options (anonymous user with default
1940 * preferences and content language).
1941 * @return ParserOptions
1943 public function makeParserOptions( $context ) {
1944 $options = $this->getContentHandler()->makeParserOptions( $context );
1946 if ( $this->getTitle()->isConversionTable() ) {
1947 // @todo ConversionTable should become a separate content model, so
1948 // we don't need special cases like this one.
1949 $options->disableContentConversion();
1956 * Prepare content which is about to be saved.
1957 * Returns a stdClass with source, pst and output members
1959 * @param Content $content
1960 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1961 * revision ID is also accepted, but this is deprecated.
1962 * @param User|null $user
1963 * @param string|null $serialFormat
1964 * @param bool $useCache Check shared prepared edit cache
1970 public function prepareContentForEdit(
1971 Content
$content, $revision = null, User
$user = null,
1972 $serialFormat = null, $useCache = true
1974 global $wgContLang, $wgUser, $wgAjaxEditStash;
1976 if ( is_object( $revision ) ) {
1977 $revid = $revision->getId();
1980 // This code path is deprecated, and nothing is known to
1981 // use it, so performance here shouldn't be a worry.
1982 if ( $revid !== null ) {
1983 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
1989 $user = is_null( $user ) ?
$wgUser : $user;
1990 // XXX: check $user->getId() here???
1992 // Use a sane default for $serialFormat, see T59026
1993 if ( $serialFormat === null ) {
1994 $serialFormat = $content->getContentHandler()->getDefaultFormat();
1997 if ( $this->mPreparedEdit
1998 && isset( $this->mPreparedEdit
->newContent
)
1999 && $this->mPreparedEdit
->newContent
->equals( $content )
2000 && $this->mPreparedEdit
->revid
== $revid
2001 && $this->mPreparedEdit
->format
== $serialFormat
2002 // XXX: also check $user here?
2005 return $this->mPreparedEdit
;
2008 // The edit may have already been prepared via api.php?action=stashedit
2009 $cachedEdit = $useCache && $wgAjaxEditStash
2010 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2013 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2014 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2017 if ( $cachedEdit ) {
2018 $edit->timestamp
= $cachedEdit->timestamp
;
2020 $edit->timestamp
= wfTimestampNow();
2022 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2023 $edit->revid
= $revid;
2025 if ( $cachedEdit ) {
2026 $edit->pstContent
= $cachedEdit->pstContent
;
2028 $edit->pstContent
= $content
2029 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2033 $edit->format
= $serialFormat;
2034 $edit->popts
= $this->makeParserOptions( 'canonical' );
2035 if ( $cachedEdit ) {
2036 $edit->output
= $cachedEdit->output
;
2039 // We get here if vary-revision is set. This means that this page references
2040 // itself (such as via self-transclusion). In this case, we need to make sure
2041 // that any such self-references refer to the newly-saved revision, and not
2042 // to the previous one, which could otherwise happen due to replica DB lag.
2043 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2044 $edit->popts
->setCurrentRevisionCallback(
2045 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2046 if ( $title->equals( $revision->getTitle() ) ) {
2049 return call_user_func( $oldCallback, $title, $parser );
2054 // Try to avoid a second parse if {{REVISIONID}} is used
2055 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2056 ? DB_MASTER
// use the best possible guess
2057 : DB_REPLICA
; // T154554
2059 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2060 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2068 $edit->output
= $edit->pstContent
2069 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2073 $edit->newContent
= $content;
2074 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2076 // NOTE: B/C for hooks! don't use these fields!
2077 $edit->newText
= $edit->newContent
2078 ? ContentHandler
::getContentText( $edit->newContent
)
2080 $edit->oldText
= $edit->oldContent
2081 ? ContentHandler
::getContentText( $edit->oldContent
)
2083 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2085 if ( $edit->output
) {
2086 $edit->output
->setCacheTime( wfTimestampNow() );
2089 // Process cache the result
2090 $this->mPreparedEdit
= $edit;
2096 * Do standard deferred updates after page edit.
2097 * Update links tables, site stats, search index and message cache.
2098 * Purges pages that include this page if the text was changed here.
2099 * Every 100th edit, prune the recent changes table.
2101 * @param Revision $revision
2102 * @param User $user User object that did the revision
2103 * @param array $options Array of options, following indexes are used:
2104 * - changed: boolean, whether the revision changed the content (default true)
2105 * - created: boolean, whether the revision created the page (default false)
2106 * - moved: boolean, whether the page was moved (default false)
2107 * - restored: boolean, whether the page was undeleted (default false)
2108 * - oldrevision: Revision object for the pre-update revision (default null)
2109 * - oldcountable: boolean, null, or string 'no-change' (default null):
2110 * - boolean: whether the page was counted as an article before that
2111 * revision, only used in changed is true and created is false
2112 * - null: if created is false, don't update the article count; if created
2113 * is true, do update the article count
2114 * - 'no-change': don't update the article count, ever
2116 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2117 global $wgRCWatchCategoryMembership;
2123 'restored' => false,
2124 'oldrevision' => null,
2125 'oldcountable' => null
2127 $content = $revision->getContent();
2129 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2131 // See if the parser output before $revision was inserted is still valid
2133 if ( !$this->mPreparedEdit
) {
2134 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2135 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2136 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2137 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2138 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2140 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2141 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2142 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2144 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2145 $editInfo = $this->mPreparedEdit
;
2149 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2150 // $text is usually already pre-save transformed once. Avoid using the edit stash
2151 // as any prepared content from there or in doEditContent() was already rejected.
2152 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2155 // Save it to the parser cache.
2156 // Make sure the cache time matches page_touched to avoid double parsing.
2157 ParserCache
::singleton()->save(
2158 $editInfo->output
, $this, $editInfo->popts
,
2159 $revision->getTimestamp(), $editInfo->revid
2162 // Update the links tables and other secondary data
2164 $recursive = $options['changed']; // T52785
2165 $updates = $content->getSecondaryDataUpdates(
2166 $this->getTitle(), null, $recursive, $editInfo->output
2168 foreach ( $updates as $update ) {
2169 if ( $update instanceof LinksUpdate
) {
2170 $update->setRevision( $revision );
2171 $update->setTriggeringUser( $user );
2173 DeferredUpdates
::addUpdate( $update );
2175 if ( $wgRCWatchCategoryMembership
2176 && $this->getContentHandler()->supportsCategories() === true
2177 && ( $options['changed'] ||
$options['created'] )
2178 && !$options['restored']
2180 // Note: jobs are pushed after deferred updates, so the job should be able to see
2181 // the recent change entry (also done via deferred updates) and carry over any
2182 // bot/deletion/IP flags, ect.
2183 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2186 'pageId' => $this->getId(),
2187 'revTimestamp' => $revision->getTimestamp()
2193 // Avoid PHP 7.1 warning of passing $this by reference
2196 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2198 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2199 // Flush old entries from the `recentchanges` table
2200 if ( mt_rand( 0, 9 ) == 0 ) {
2201 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2205 if ( !$this->exists() ) {
2209 $id = $this->getId();
2210 $title = $this->mTitle
->getPrefixedDBkey();
2211 $shortTitle = $this->mTitle
->getDBkey();
2213 if ( $options['oldcountable'] === 'no-change' ||
2214 ( !$options['changed'] && !$options['moved'] )
2217 } elseif ( $options['created'] ) {
2218 $good = (int)$this->isCountable( $editInfo );
2219 } elseif ( $options['oldcountable'] !== null ) {
2220 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2224 $edits = $options['changed'] ?
1 : 0;
2225 $total = $options['created'] ?
1 : 0;
2227 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2228 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2230 // If this is another user's talk page, update newtalk.
2231 // Don't do this if $options['changed'] = false (null-edits) nor if
2232 // it's a minor edit and the user doesn't want notifications for those.
2233 if ( $options['changed']
2234 && $this->mTitle
->getNamespace() == NS_USER_TALK
2235 && $shortTitle != $user->getTitleKey()
2236 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2238 $recipient = User
::newFromName( $shortTitle, false );
2239 if ( !$recipient ) {
2240 wfDebug( __METHOD__
. ": invalid username\n" );
2242 // Avoid PHP 7.1 warning of passing $this by reference
2245 // Allow extensions to prevent user notification
2246 // when a new message is added to their talk page
2247 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2248 if ( User
::isIP( $shortTitle ) ) {
2249 // An anonymous user
2250 $recipient->setNewtalk( true, $revision );
2251 } elseif ( $recipient->isLoggedIn() ) {
2252 $recipient->setNewtalk( true, $revision );
2254 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2260 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2261 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2264 if ( $options['created'] ) {
2265 self
::onArticleCreate( $this->mTitle
);
2266 } elseif ( $options['changed'] ) { // T52785
2267 self
::onArticleEdit( $this->mTitle
, $revision );
2270 ResourceLoaderWikiModule
::invalidateModuleCache(
2271 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2276 * Update the article's restriction field, and leave a log entry.
2277 * This works for protection both existing and non-existing pages.
2279 * @param array $limit Set of restriction keys
2280 * @param array $expiry Per restriction type expiration
2281 * @param int &$cascade Set to false if cascading protection isn't allowed.
2282 * @param string $reason
2283 * @param User $user The user updating the restrictions
2284 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2285 * ($user should be able to add the specified tags before this is called)
2286 * @return Status Status object; if action is taken, $status->value is the log_id of the
2287 * protection log entry.
2289 public function doUpdateRestrictions( array $limit, array $expiry,
2290 &$cascade, $reason, User
$user, $tags = null
2292 global $wgCascadingRestrictionLevels, $wgContLang;
2294 if ( wfReadOnly() ) {
2295 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2298 $this->loadPageData( 'fromdbmaster' );
2299 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2300 $id = $this->getId();
2306 // Take this opportunity to purge out expired restrictions
2307 Title
::purgeExpiredRestrictions();
2309 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2310 // we expect a single selection, but the schema allows otherwise.
2311 $isProtected = false;
2315 $dbw = wfGetDB( DB_MASTER
);
2317 foreach ( $restrictionTypes as $action ) {
2318 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2319 $expiry[$action] = 'infinity';
2321 if ( !isset( $limit[$action] ) ) {
2322 $limit[$action] = '';
2323 } elseif ( $limit[$action] != '' ) {
2327 // Get current restrictions on $action
2328 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2329 if ( $current != '' ) {
2330 $isProtected = true;
2333 if ( $limit[$action] != $current ) {
2335 } elseif ( $limit[$action] != '' ) {
2336 // Only check expiry change if the action is actually being
2337 // protected, since expiry does nothing on an not-protected
2339 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2345 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2349 // If nothing has changed, do nothing
2351 return Status
::newGood();
2354 if ( !$protect ) { // No protection at all means unprotection
2355 $revCommentMsg = 'unprotectedarticle-comment';
2356 $logAction = 'unprotect';
2357 } elseif ( $isProtected ) {
2358 $revCommentMsg = 'modifiedarticleprotection-comment';
2359 $logAction = 'modify';
2361 $revCommentMsg = 'protectedarticle-comment';
2362 $logAction = 'protect';
2365 // Truncate for whole multibyte characters
2366 $reason = $wgContLang->truncate( $reason, 255 );
2368 $logRelationsValues = [];
2369 $logRelationsField = null;
2370 $logParamsDetails = [];
2372 // Null revision (used for change tag insertion)
2373 $nullRevision = null;
2375 if ( $id ) { // Protection of existing page
2376 // Avoid PHP 7.1 warning of passing $this by reference
2379 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2380 return Status
::newGood();
2383 // Only certain restrictions can cascade...
2384 $editrestriction = isset( $limit['edit'] )
2385 ?
[ $limit['edit'] ]
2386 : $this->mTitle
->getRestrictions( 'edit' );
2387 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2388 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2390 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2391 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2394 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2395 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2396 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2398 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2399 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2402 // The schema allows multiple restrictions
2403 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2407 // insert null revision to identify the page protection change as edit summary
2408 $latest = $this->getLatest();
2409 $nullRevision = $this->insertProtectNullRevision(
2418 if ( $nullRevision === null ) {
2419 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2422 $logRelationsField = 'pr_id';
2424 // Update restrictions table
2425 foreach ( $limit as $action => $restrictions ) {
2427 'page_restrictions',
2430 'pr_type' => $action
2434 if ( $restrictions != '' ) {
2435 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2437 'page_restrictions',
2439 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2441 'pr_type' => $action,
2442 'pr_level' => $restrictions,
2443 'pr_cascade' => $cascadeValue,
2444 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2448 $logRelationsValues[] = $dbw->insertId();
2449 $logParamsDetails[] = [
2451 'level' => $restrictions,
2452 'expiry' => $expiry[$action],
2453 'cascade' => (bool)$cascadeValue,
2458 // Clear out legacy restriction fields
2461 [ 'page_restrictions' => '' ],
2462 [ 'page_id' => $id ],
2466 // Avoid PHP 7.1 warning of passing $this by reference
2469 Hooks
::run( 'NewRevisionFromEditComplete',
2470 [ $this, $nullRevision, $latest, $user ] );
2471 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2472 } else { // Protection of non-existing page (also known as "title protection")
2473 // Cascade protection is meaningless in this case
2476 if ( $limit['create'] != '' ) {
2477 $dbw->replace( 'protected_titles',
2478 [ [ 'pt_namespace', 'pt_title' ] ],
2480 'pt_namespace' => $this->mTitle
->getNamespace(),
2481 'pt_title' => $this->mTitle
->getDBkey(),
2482 'pt_create_perm' => $limit['create'],
2483 'pt_timestamp' => $dbw->timestamp(),
2484 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2485 'pt_user' => $user->getId(),
2486 'pt_reason' => $reason,
2489 $logParamsDetails[] = [
2491 'level' => $limit['create'],
2492 'expiry' => $expiry['create'],
2495 $dbw->delete( 'protected_titles',
2497 'pt_namespace' => $this->mTitle
->getNamespace(),
2498 'pt_title' => $this->mTitle
->getDBkey()
2504 $this->mTitle
->flushRestrictions();
2505 InfoAction
::invalidateCache( $this->mTitle
);
2507 if ( $logAction == 'unprotect' ) {
2510 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2512 '4::description' => $protectDescriptionLog, // parameter for IRC
2513 '5:bool:cascade' => $cascade,
2514 'details' => $logParamsDetails, // parameter for localize and api
2518 // Update the protection log
2519 $logEntry = new ManualLogEntry( 'protect', $logAction );
2520 $logEntry->setTarget( $this->mTitle
);
2521 $logEntry->setComment( $reason );
2522 $logEntry->setPerformer( $user );
2523 $logEntry->setParameters( $params );
2524 if ( !is_null( $nullRevision ) ) {
2525 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2527 $logEntry->setTags( $tags );
2528 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2529 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2531 $logId = $logEntry->insert();
2532 $logEntry->publish( $logId );
2534 return Status
::newGood( $logId );
2538 * Insert a new null revision for this page.
2540 * @param string $revCommentMsg Comment message key for the revision
2541 * @param array $limit Set of restriction keys
2542 * @param array $expiry Per restriction type expiration
2543 * @param int $cascade Set to false if cascading protection isn't allowed.
2544 * @param string $reason
2545 * @param User|null $user
2546 * @return Revision|null Null on error
2548 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2549 array $expiry, $cascade, $reason, $user = null
2551 $dbw = wfGetDB( DB_MASTER
);
2553 // Prepare a null revision to be added to the history
2554 $editComment = wfMessage(
2556 $this->mTitle
->getPrefixedText(),
2557 $user ?
$user->getName() : ''
2558 )->inContentLanguage()->text();
2560 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2562 $protectDescription = $this->protectDescription( $limit, $expiry );
2563 if ( $protectDescription ) {
2564 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2565 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2566 ->inContentLanguage()->text();
2569 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2570 $editComment .= wfMessage( 'brackets' )->params(
2571 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2572 )->inContentLanguage()->text();
2575 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2577 $nullRev->insertOn( $dbw );
2579 // Update page record and touch page
2580 $oldLatest = $nullRev->getParentId();
2581 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2588 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2591 protected function formatExpiry( $expiry ) {
2594 if ( $expiry != 'infinity' ) {
2597 $wgContLang->timeanddate( $expiry, false, false ),
2598 $wgContLang->date( $expiry, false, false ),
2599 $wgContLang->time( $expiry, false, false )
2600 )->inContentLanguage()->text();
2602 return wfMessage( 'protect-expiry-indefinite' )
2603 ->inContentLanguage()->text();
2608 * Builds the description to serve as comment for the edit.
2610 * @param array $limit Set of restriction keys
2611 * @param array $expiry Per restriction type expiration
2614 public function protectDescription( array $limit, array $expiry ) {
2615 $protectDescription = '';
2617 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2618 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2619 # All possible message keys are listed here for easier grepping:
2620 # * restriction-create
2621 # * restriction-edit
2622 # * restriction-move
2623 # * restriction-upload
2624 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2625 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2626 # with '' filtered out. All possible message keys are listed below:
2627 # * protect-level-autoconfirmed
2628 # * protect-level-sysop
2629 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2630 ->inContentLanguage()->text();
2632 $expiryText = $this->formatExpiry( $expiry[$action] );
2634 if ( $protectDescription !== '' ) {
2635 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2637 $protectDescription .= wfMessage( 'protect-summary-desc' )
2638 ->params( $actionText, $restrictionsText, $expiryText )
2639 ->inContentLanguage()->text();
2642 return $protectDescription;
2646 * Builds the description to serve as comment for the log entry.
2648 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2649 * protect description text. Keep them in old format to avoid breaking compatibility.
2650 * TODO: Fix protection log to store structured description and format it on-the-fly.
2652 * @param array $limit Set of restriction keys
2653 * @param array $expiry Per restriction type expiration
2656 public function protectDescriptionLog( array $limit, array $expiry ) {
2659 $protectDescriptionLog = '';
2661 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2662 $expiryText = $this->formatExpiry( $expiry[$action] );
2663 $protectDescriptionLog .= $wgContLang->getDirMark() .
2664 "[$action=$restrictions] ($expiryText)";
2667 return trim( $protectDescriptionLog );
2671 * Take an array of page restrictions and flatten it to a string
2672 * suitable for insertion into the page_restrictions field.
2674 * @param string[] $limit
2676 * @throws MWException
2679 protected static function flattenRestrictions( $limit ) {
2680 if ( !is_array( $limit ) ) {
2681 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2687 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2688 $bits[] = "$action=$restrictions";
2691 return implode( ':', $bits );
2695 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2696 * backwards compatibility, if you care about error reporting you should use
2697 * doDeleteArticleReal() instead.
2699 * Deletes the article with database consistency, writes logs, purges caches
2701 * @param string $reason Delete reason for deletion log
2702 * @param bool $suppress Suppress all revisions and log the deletion in
2703 * the suppression log instead of the deletion log
2704 * @param int $u1 Unused
2705 * @param bool $u2 Unused
2706 * @param array|string &$error Array of errors to append to
2707 * @param User $user The deleting user
2708 * @return bool True if successful
2710 public function doDeleteArticle(
2711 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2713 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2714 return $status->isGood();
2718 * Back-end article deletion
2719 * Deletes the article with database consistency, writes logs, purges caches
2723 * @param string $reason Delete reason for deletion log
2724 * @param bool $suppress Suppress all revisions and log the deletion in
2725 * the suppression log instead of the deletion log
2726 * @param int $u1 Unused
2727 * @param bool $u2 Unused
2728 * @param array|string &$error Array of errors to append to
2729 * @param User $user The deleting user
2730 * @param array $tags Tags to apply to the deletion action
2731 * @return Status Status object; if successful, $status->value is the log_id of the
2732 * deletion log entry. If the page couldn't be deleted because it wasn't
2733 * found, $status is a non-fatal 'cannotdelete' error
2735 public function doDeleteArticleReal(
2736 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2737 $tags = [], $logsubtype = 'delete'
2739 global $wgUser, $wgContentHandlerUseDB;
2741 wfDebug( __METHOD__
. "\n" );
2743 $status = Status
::newGood();
2745 if ( $this->mTitle
->getDBkey() === '' ) {
2746 $status->error( 'cannotdelete',
2747 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2751 // Avoid PHP 7.1 warning of passing $this by reference
2754 $user = is_null( $user ) ?
$wgUser : $user;
2755 if ( !Hooks
::run( 'ArticleDelete',
2756 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2758 if ( $status->isOK() ) {
2759 // Hook aborted but didn't set a fatal status
2760 $status->fatal( 'delete-hook-aborted' );
2765 $dbw = wfGetDB( DB_MASTER
);
2766 $dbw->startAtomic( __METHOD__
);
2768 $this->loadPageData( self
::READ_LATEST
);
2769 $id = $this->getId();
2770 // T98706: lock the page from various other updates but avoid using
2771 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2772 // the revisions queries (which also JOIN on user). Only lock the page
2773 // row and CAS check on page_latest to see if the trx snapshot matches.
2774 $lockedLatest = $this->lockAndGetLatest();
2775 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2776 $dbw->endAtomic( __METHOD__
);
2777 // Page not there or trx snapshot is stale
2778 $status->error( 'cannotdelete',
2779 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2783 // Given the lock above, we can be confident in the title and page ID values
2784 $namespace = $this->getTitle()->getNamespace();
2785 $dbKey = $this->getTitle()->getDBkey();
2787 // At this point we are now comitted to returning an OK
2788 // status unless some DB query error or other exception comes up.
2789 // This way callers don't have to call rollback() if $status is bad
2790 // unless they actually try to catch exceptions (which is rare).
2792 // we need to remember the old content so we can use it to generate all deletion updates.
2793 $revision = $this->getRevision();
2795 $content = $this->getContent( Revision
::RAW
);
2796 } catch ( Exception
$ex ) {
2797 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2798 . $ex->getMessage() );
2803 $fields = Revision
::selectFields();
2806 // Bitfields to further suppress the content
2808 $bitfield = Revision
::SUPPRESSED_ALL
;
2809 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2812 // For now, shunt the revision data into the archive table.
2813 // Text is *not* removed from the text table; bulk storage
2814 // is left intact to avoid breaking block-compression or
2815 // immutable storage schemes.
2816 // In the future, we may keep revisions and mark them with
2817 // the rev_deleted field, which is reserved for this purpose.
2819 // Get all of the page revisions
2820 $res = $dbw->select(
2823 [ 'rev_page' => $id ],
2827 // Build their equivalent archive rows
2829 foreach ( $res as $row ) {
2831 'ar_namespace' => $namespace,
2832 'ar_title' => $dbKey,
2833 'ar_comment' => $row->rev_comment
,
2834 'ar_user' => $row->rev_user
,
2835 'ar_user_text' => $row->rev_user_text
,
2836 'ar_timestamp' => $row->rev_timestamp
,
2837 'ar_minor_edit' => $row->rev_minor_edit
,
2838 'ar_rev_id' => $row->rev_id
,
2839 'ar_parent_id' => $row->rev_parent_id
,
2840 'ar_text_id' => $row->rev_text_id
,
2843 'ar_len' => $row->rev_len
,
2844 'ar_page_id' => $id,
2845 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2846 'ar_sha1' => $row->rev_sha1
,
2848 if ( $wgContentHandlerUseDB ) {
2849 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2850 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2852 $rowsInsert[] = $rowInsert;
2854 // Copy them into the archive table
2855 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2856 // Save this so we can pass it to the ArticleDeleteComplete hook.
2857 $archivedRevisionCount = $dbw->affectedRows();
2859 // Clone the title and wikiPage, so we have the information we need when
2860 // we log and run the ArticleDeleteComplete hook.
2861 $logTitle = clone $this->mTitle
;
2862 $wikiPageBeforeDelete = clone $this;
2864 // Now that it's safely backed up, delete it
2865 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2866 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2868 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2869 $logtype = $suppress ?
'suppress' : 'delete';
2871 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2872 $logEntry->setPerformer( $user );
2873 $logEntry->setTarget( $logTitle );
2874 $logEntry->setComment( $reason );
2875 $logEntry->setTags( $tags );
2876 $logid = $logEntry->insert();
2878 $dbw->onTransactionPreCommitOrIdle(
2879 function () use ( $dbw, $logEntry, $logid ) {
2880 // T58776: avoid deadlocks (especially from FileDeleteForm)
2881 $logEntry->publish( $logid );
2886 $dbw->endAtomic( __METHOD__
);
2888 $this->doDeleteUpdates( $id, $content, $revision );
2890 Hooks
::run( 'ArticleDeleteComplete', [
2891 &$wikiPageBeforeDelete,
2897 $archivedRevisionCount
2899 $status->value
= $logid;
2901 // Show log excerpt on 404 pages rather than just a link
2902 $cache = ObjectCache
::getMainStashInstance();
2903 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2904 $cache->set( $key, 1, $cache::TTL_DAY
);
2910 * Lock the page row for this title+id and return page_latest (or 0)
2912 * @return integer Returns 0 if no row was found with this title+id
2915 public function lockAndGetLatest() {
2916 return (int)wfGetDB( DB_MASTER
)->selectField(
2920 'page_id' => $this->getId(),
2921 // Typically page_id is enough, but some code might try to do
2922 // updates assuming the title is the same, so verify that
2923 'page_namespace' => $this->getTitle()->getNamespace(),
2924 'page_title' => $this->getTitle()->getDBkey()
2932 * Do some database updates after deletion
2934 * @param int $id The page_id value of the page being deleted
2935 * @param Content|null $content Optional page content to be used when determining
2936 * the required updates. This may be needed because $this->getContent()
2937 * may already return null when the page proper was deleted.
2938 * @param Revision|null $revision The latest page revision
2940 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2942 $countable = $this->isCountable();
2943 } catch ( Exception
$ex ) {
2944 // fallback for deleting broken pages for which we cannot load the content for
2945 // some reason. Note that doDeleteArticleReal() already logged this problem.
2949 // Update site status
2950 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2952 // Delete pagelinks, update secondary indexes, etc
2953 $updates = $this->getDeletionUpdates( $content );
2954 foreach ( $updates as $update ) {
2955 DeferredUpdates
::addUpdate( $update );
2958 // Reparse any pages transcluding this page
2959 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2961 // Reparse any pages including this image
2962 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2963 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2967 WikiPage
::onArticleDelete( $this->mTitle
);
2968 ResourceLoaderWikiModule
::invalidateModuleCache(
2969 $this->mTitle
, $revision, null, wfWikiID()
2972 // Reset this object and the Title object
2973 $this->loadFromRow( false, self
::READ_LATEST
);
2976 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2980 * Roll back the most recent consecutive set of edits to a page
2981 * from the same user; fails if there are no eligible edits to
2982 * roll back to, e.g. user is the sole contributor. This function
2983 * performs permissions checks on $user, then calls commitRollback()
2984 * to do the dirty work
2986 * @todo Separate the business/permission stuff out from backend code
2987 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
2989 * @param string $fromP Name of the user whose edits to rollback.
2990 * @param string $summary Custom summary. Set to default summary if empty.
2991 * @param string $token Rollback token.
2992 * @param bool $bot If true, mark all reverted edits as bot.
2994 * @param array $resultDetails Array contains result-specific array of additional values
2995 * 'alreadyrolled' : 'current' (rev)
2996 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2998 * @param User $user The user performing the rollback
2999 * @param array|null $tags Change tags to apply to the rollback
3000 * Callers are responsible for permission checks
3001 * (with ChangeTags::canAddTagsAccompanyingChange)
3003 * @return array Array of errors, each error formatted as
3004 * array(messagekey, param1, param2, ...).
3005 * On success, the array is empty. This array can also be passed to
3006 * OutputPage::showPermissionsErrorPage().
3008 public function doRollback(
3009 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3011 $resultDetails = null;
3013 // Check permissions
3014 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3015 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3016 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3018 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3019 $errors[] = [ 'sessionfailure' ];
3022 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3023 $errors[] = [ 'actionthrottledtext' ];
3026 // If there were errors, bail out now
3027 if ( !empty( $errors ) ) {
3031 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3035 * Backend implementation of doRollback(), please refer there for parameter
3036 * and return value documentation
3038 * NOTE: This function does NOT check ANY permissions, it just commits the
3039 * rollback to the DB. Therefore, you should only call this function direct-
3040 * ly if you want to use custom permissions checks. If you don't, use
3041 * doRollback() instead.
3042 * @param string $fromP Name of the user whose edits to rollback.
3043 * @param string $summary Custom summary. Set to default summary if empty.
3044 * @param bool $bot If true, mark all reverted edits as bot.
3046 * @param array $resultDetails Contains result-specific array of additional values
3047 * @param User $guser The user performing the rollback
3048 * @param array|null $tags Change tags to apply to the rollback
3049 * Callers are responsible for permission checks
3050 * (with ChangeTags::canAddTagsAccompanyingChange)
3054 public function commitRollback( $fromP, $summary, $bot,
3055 &$resultDetails, User
$guser, $tags = null
3057 global $wgUseRCPatrol, $wgContLang;
3059 $dbw = wfGetDB( DB_MASTER
);
3061 if ( wfReadOnly() ) {
3062 return [ [ 'readonlytext' ] ];
3065 // Get the last editor
3066 $current = $this->getRevision();
3067 if ( is_null( $current ) ) {
3068 // Something wrong... no page?
3069 return [ [ 'notanarticle' ] ];
3072 $from = str_replace( '_', ' ', $fromP );
3073 // User name given should match up with the top revision.
3074 // If the user was deleted then $from should be empty.
3075 if ( $from != $current->getUserText() ) {
3076 $resultDetails = [ 'current' => $current ];
3077 return [ [ 'alreadyrolled',
3078 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3079 htmlspecialchars( $fromP ),
3080 htmlspecialchars( $current->getUserText() )
3084 // Get the last edit not by this person...
3085 // Note: these may not be public values
3086 $user = intval( $current->getUser( Revision
::RAW
) );
3087 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3088 $s = $dbw->selectRow( 'revision',
3089 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3090 [ 'rev_page' => $current->getPage(),
3091 "rev_user != {$user} OR rev_user_text != {$user_text}"
3093 [ 'USE INDEX' => 'page_timestamp',
3094 'ORDER BY' => 'rev_timestamp DESC' ]
3096 if ( $s === false ) {
3097 // No one else ever edited this page
3098 return [ [ 'cantrollback' ] ];
3099 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3100 ||
$s->rev_deleted
& Revision
::DELETED_USER
3102 // Only admins can see this text
3103 return [ [ 'notvisiblerev' ] ];
3106 // Generate the edit summary if necessary
3107 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3108 if ( empty( $summary ) ) {
3109 if ( $from == '' ) { // no public user name
3110 $summary = wfMessage( 'revertpage-nouser' );
3112 $summary = wfMessage( 'revertpage' );
3116 // Allow the custom summary to use the same args as the default message
3118 $target->getUserText(), $from, $s->rev_id
,
3119 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3120 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3122 if ( $summary instanceof Message
) {
3123 $summary = $summary->params( $args )->inContentLanguage()->text();
3125 $summary = wfMsgReplaceArgs( $summary, $args );
3128 // Trim spaces on user supplied text
3129 $summary = trim( $summary );
3131 // Truncate for whole multibyte characters.
3132 $summary = $wgContLang->truncate( $summary, 255 );
3135 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3137 if ( $guser->isAllowed( 'minoredit' ) ) {
3138 $flags |
= EDIT_MINOR
;
3141 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3142 $flags |
= EDIT_FORCE_BOT
;
3145 $targetContent = $target->getContent();
3146 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3148 // Actually store the edit
3149 $status = $this->doEditContent(
3159 // Set patrolling and bot flag on the edits, which gets rollbacked.
3160 // This is done even on edit failure to have patrolling in that case (T64157).
3162 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3163 // Mark all reverted edits as bot
3167 if ( $wgUseRCPatrol ) {
3168 // Mark all reverted edits as patrolled
3169 $set['rc_patrolled'] = 1;
3172 if ( count( $set ) ) {
3173 $dbw->update( 'recentchanges', $set,
3175 'rc_cur_id' => $current->getPage(),
3176 'rc_user_text' => $current->getUserText(),
3177 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3183 if ( !$status->isOK() ) {
3184 return $status->getErrorsArray();
3187 // raise error, when the edit is an edit without a new version
3188 $statusRev = isset( $status->value
['revision'] )
3189 ?
$status->value
['revision']
3191 if ( !( $statusRev instanceof Revision
) ) {
3192 $resultDetails = [ 'current' => $current ];
3193 return [ [ 'alreadyrolled',
3194 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3195 htmlspecialchars( $fromP ),
3196 htmlspecialchars( $current->getUserText() )
3200 if ( $changingContentModel ) {
3201 // If the content model changed during the rollback,
3202 // make sure it gets logged to Special:Log/contentmodel
3203 $log = new ManualLogEntry( 'contentmodel', 'change' );
3204 $log->setPerformer( $guser );
3205 $log->setTarget( $this->mTitle
);
3206 $log->setComment( $summary );
3207 $log->setParameters( [
3208 '4::oldmodel' => $current->getContentModel(),
3209 '5::newmodel' => $targetContent->getModel(),
3212 $logId = $log->insert( $dbw );
3213 $log->publish( $logId );
3216 $revId = $statusRev->getId();
3218 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3221 'summary' => $summary,
3222 'current' => $current,
3223 'target' => $target,
3231 * The onArticle*() functions are supposed to be a kind of hooks
3232 * which should be called whenever any of the specified actions
3235 * This is a good place to put code to clear caches, for instance.
3237 * This is called on page move and undelete, as well as edit
3239 * @param Title $title
3241 public static function onArticleCreate( Title
$title ) {
3242 // Update existence markers on article/talk tabs...
3243 $other = $title->getOtherPage();
3245 $other->purgeSquid();
3247 $title->touchLinks();
3248 $title->purgeSquid();
3249 $title->deleteTitleProtection();
3251 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3253 if ( $title->getNamespace() == NS_CATEGORY
) {
3254 // Load the Category object, which will schedule a job to create
3255 // the category table row if necessary. Checking a replica DB is ok
3256 // here, in the worst case it'll run an unnecessary recount job on
3257 // a category that probably doesn't have many members.
3258 Category
::newFromTitle( $title )->getID();
3263 * Clears caches when article is deleted
3265 * @param Title $title
3267 public static function onArticleDelete( Title
$title ) {
3268 // Update existence markers on article/talk tabs...
3269 $other = $title->getOtherPage();
3271 $other->purgeSquid();
3273 $title->touchLinks();
3274 $title->purgeSquid();
3276 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3279 HTMLFileCache
::clearFileCache( $title );
3280 InfoAction
::invalidateCache( $title );
3283 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3284 MessageCache
::singleton()->updateMessageOverride( $title, null );
3288 if ( $title->getNamespace() == NS_FILE
) {
3289 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3293 if ( $title->getNamespace() == NS_USER_TALK
) {
3294 $user = User
::newFromName( $title->getText(), false );
3296 $user->setNewtalk( false );
3301 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3305 * Purge caches on page update etc
3307 * @param Title $title
3308 * @param Revision|null $revision Revision that was just saved, may be null
3310 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3311 // Invalidate caches of articles which include this page
3312 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3314 // Invalidate the caches of all pages which redirect here
3315 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3317 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3319 // Purge CDN for this page only
3320 $title->purgeSquid();
3321 // Clear file cache for this page only
3322 HTMLFileCache
::clearFileCache( $title );
3324 $revid = $revision ?
$revision->getId() : null;
3325 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3326 InfoAction
::invalidateCache( $title, $revid );
3333 * Returns a list of categories this page is a member of.
3334 * Results will include hidden categories
3336 * @return TitleArray
3338 public function getCategories() {
3339 $id = $this->getId();
3341 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3344 $dbr = wfGetDB( DB_REPLICA
);
3345 $res = $dbr->select( 'categorylinks',
3346 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3347 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3348 // as not being aliases, and NS_CATEGORY is numeric
3349 [ 'cl_from' => $id ],
3352 return TitleArray
::newFromResult( $res );
3356 * Returns a list of hidden categories this page is a member of.
3357 * Uses the page_props and categorylinks tables.
3359 * @return array Array of Title objects
3361 public function getHiddenCategories() {
3363 $id = $this->getId();
3369 $dbr = wfGetDB( DB_REPLICA
);
3370 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3372 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3373 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3376 if ( $res !== false ) {
3377 foreach ( $res as $row ) {
3378 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3386 * Auto-generates a deletion reason
3388 * @param bool &$hasHistory Whether the page has a history
3389 * @return string|bool String containing deletion reason or empty string, or boolean false
3390 * if no revision occurred
3392 public function getAutoDeleteReason( &$hasHistory ) {
3393 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3397 * Update all the appropriate counts in the category table, given that
3398 * we've added the categories $added and deleted the categories $deleted.
3400 * This should only be called from deferred updates or jobs to avoid contention.
3402 * @param array $added The names of categories that were added
3403 * @param array $deleted The names of categories that were deleted
3404 * @param integer $id Page ID (this should be the original deleted page ID)
3406 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3407 $id = $id ?
: $this->getId();
3408 $ns = $this->getTitle()->getNamespace();
3410 $addFields = [ 'cat_pages = cat_pages + 1' ];
3411 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3412 if ( $ns == NS_CATEGORY
) {
3413 $addFields[] = 'cat_subcats = cat_subcats + 1';
3414 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3415 } elseif ( $ns == NS_FILE
) {
3416 $addFields[] = 'cat_files = cat_files + 1';
3417 $removeFields[] = 'cat_files = cat_files - 1';
3420 $dbw = wfGetDB( DB_MASTER
);
3422 if ( count( $added ) ) {
3423 $existingAdded = $dbw->selectFieldValues(
3426 [ 'cat_title' => $added ],
3430 // For category rows that already exist, do a plain
3431 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3432 // to avoid creating gaps in the cat_id sequence.
3433 if ( count( $existingAdded ) ) {
3437 [ 'cat_title' => $existingAdded ],
3442 $missingAdded = array_diff( $added, $existingAdded );
3443 if ( count( $missingAdded ) ) {
3445 foreach ( $missingAdded as $cat ) {
3447 'cat_title' => $cat,
3449 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3450 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3463 if ( count( $deleted ) ) {
3467 [ 'cat_title' => $deleted ],
3472 foreach ( $added as $catName ) {
3473 $cat = Category
::newFromName( $catName );
3474 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3477 foreach ( $deleted as $catName ) {
3478 $cat = Category
::newFromName( $catName );
3479 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3482 // Refresh counts on categories that should be empty now, to
3483 // trigger possible deletion. Check master for the most
3484 // up-to-date cat_pages.
3485 if ( count( $deleted ) ) {
3486 $rows = $dbw->select(
3488 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3489 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3492 foreach ( $rows as $row ) {
3493 $cat = Category
::newFromRow( $row );
3494 $cat->refreshCounts();
3500 * Opportunistically enqueue link update jobs given fresh parser output if useful
3502 * @param ParserOutput $parserOutput Current version page output
3505 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3506 if ( wfReadOnly() ) {
3510 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3511 [ $this, $this->mTitle
, $parserOutput ]
3516 $config = RequestContext
::getMain()->getConfig();
3519 'isOpportunistic' => true,
3520 'rootJobTimestamp' => $parserOutput->getCacheTime()
3523 if ( $this->mTitle
->areRestrictionsCascading() ) {
3524 // If the page is cascade protecting, the links should really be up-to-date
3525 JobQueueGroup
::singleton()->lazyPush(
3526 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3528 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3529 // Assume the output contains "dynamic" time/random based magic words.
3530 // Only update pages that expired due to dynamic content and NOT due to edits
3531 // to referenced templates/files. When the cache expires due to dynamic content,
3532 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3533 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3534 // template/file edit already triggered recursive RefreshLinksJob jobs.
3535 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3536 // If a page is uncacheable, do not keep spamming a job for it.
3537 // Although it would be de-duplicated, it would still waste I/O.
3538 $cache = ObjectCache
::getLocalClusterInstance();
3539 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3540 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3541 if ( $cache->add( $key, time(), $ttl ) ) {
3542 JobQueueGroup
::singleton()->lazyPush(
3543 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3551 * Returns a list of updates to be performed when this page is deleted. The
3552 * updates should remove any information about this page from secondary data
3553 * stores such as links tables.
3555 * @param Content|null $content Optional Content object for determining the
3556 * necessary updates.
3557 * @return DeferrableUpdate[]
3559 public function getDeletionUpdates( Content
$content = null ) {
3561 // load content object, which may be used to determine the necessary updates.
3562 // XXX: the content may not be needed to determine the updates.
3564 $content = $this->getContent( Revision
::RAW
);
3565 } catch ( Exception
$ex ) {
3566 // If we can't load the content, something is wrong. Perhaps that's why
3567 // the user is trying to delete the page, so let's not fail in that case.
3568 // Note that doDeleteArticleReal() will already have logged an issue with
3569 // loading the content.
3576 $updates = $content->getDeletionUpdates( $this );
3579 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3584 * Whether this content displayed on this page
3585 * comes from the local database
3590 public function isLocal() {
3595 * The display name for the site this content
3596 * come from. If a subclass overrides isLocal(),
3597 * this could return something other than the
3603 public function getWikiDisplayName() {
3609 * Get the source URL for the content on this page,
3610 * typically the canonical URL, but may be a remote
3611 * link if the content comes from another site
3616 public function getSourceURL() {
3617 return $this->getTitle()->getCanonicalURL();
3621 * @param WANObjectCache $cache
3625 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3626 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3628 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );