3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Edit\PreparedEdit
;
24 use \MediaWiki\Logger\LoggerFactory
;
25 use \MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\FakeResultWrapper
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\DBError
;
29 use Wikimedia\Rdbms\DBUnexpectedError
;
32 * Class representing a MediaWiki article and history.
34 * Some fields are public only for backwards-compatibility. Use accessors.
35 * In the past, this class was part of Article.php and everything was public.
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mLinksUpdated = '19700101000000';
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title
$title ) {
96 $this->mTitle
= $title;
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
103 public function __clone() {
104 $this->mTitle
= clone $this->mTitle
;
108 * Create a WikiPage object of the appropriate class for the given title.
110 * @param Title $title
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
115 public static function factory( Title
$title ) {
116 $ns = $title->getNamespace();
118 if ( $ns == NS_MEDIA
) {
119 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
120 } elseif ( $ns < 0 ) {
121 throw new MWException( "Invalid or virtual namespace $ns given." );
125 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
131 $page = new WikiFilePage( $title );
134 $page = new WikiCategoryPage( $title );
137 $page = new WikiPage( $title );
144 * Constructor from a page id
146 * @param int $id Article ID to load
147 * @param string|int $from One of the following values:
148 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
151 * @return WikiPage|null
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 // page ids are never 0 or negative, see T63166
159 $from = self
::convertSelectType( $from );
160 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
161 $row = $db->selectRow(
162 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
166 return self
::newFromRow( $row, $from );
170 * Constructor from a database row
173 * @param object $row Database row containing at least fields returned by selectFields().
174 * @param string|int $from Source of $data:
175 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
176 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
177 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
180 public static function newFromRow( $row, $from = 'fromdb' ) {
181 $page = self
::factory( Title
::newFromRow( $row ) );
182 $page->loadFromRow( $row, $from );
187 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
189 * @param object|string|int $type
192 private static function convertSelectType( $type ) {
195 return self
::READ_NORMAL
;
197 return self
::READ_LATEST
;
199 return self
::READ_LOCKING
;
201 // It may already be an integer or whatever else
207 * @todo Move this UI stuff somewhere else
209 * @see ContentHandler::getActionOverrides
212 public function getActionOverrides() {
213 return $this->getContentHandler()->getActionOverrides();
217 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
219 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
221 * @return ContentHandler
225 public function getContentHandler() {
226 return ContentHandler
::getForModelID( $this->getContentModel() );
230 * Get the title object of the article
231 * @return Title Title object of this page
233 public function getTitle() {
234 return $this->mTitle
;
241 public function clear() {
242 $this->mDataLoaded
= false;
243 $this->mDataLoadedFrom
= self
::READ_NONE
;
245 $this->clearCacheFields();
249 * Clear the object cache fields
252 protected function clearCacheFields() {
254 $this->mRedirectTarget
= null; // Title object if set
255 $this->mLastRevision
= null; // Latest revision
256 $this->mTouched
= '19700101000000';
257 $this->mLinksUpdated
= '19700101000000';
258 $this->mTimestamp
= '';
259 $this->mIsRedirect
= false;
260 $this->mLatest
= false;
261 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
262 // the requested rev ID and content against the cached one for equality. For most
263 // content types, the output should not change during the lifetime of this cache.
264 // Clearing it can cause extra parses on edit for no reason.
268 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
272 public function clearPreparedEdit() {
273 $this->mPreparedEdit
= false;
277 * Return the list of revision fields that should be selected to create
282 public static function selectFields() {
283 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
294 'page_links_updated',
299 if ( $wgContentHandlerUseDB ) {
300 $fields[] = 'page_content_model';
303 if ( $wgPageLanguageUseDB ) {
304 $fields[] = 'page_lang';
311 * Fetch a page record with the given conditions
312 * @param IDatabase $dbr
313 * @param array $conditions
314 * @param array $options
315 * @return object|bool Database result resource, or false on failure
317 protected function pageData( $dbr, $conditions, $options = [] ) {
318 $fields = self
::selectFields();
320 // Avoid PHP 7.1 warning of passing $this by reference
323 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
325 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
327 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
333 * Fetch a page record matching the Title object's namespace and title
334 * using a sanitized title string
336 * @param IDatabase $dbr
337 * @param Title $title
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
341 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
342 return $this->pageData( $dbr, [
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ], $options );
348 * Fetch a page record matching the requested ID
350 * @param IDatabase $dbr
352 * @param array $options
353 * @return object|bool Database result resource, or false on failure
355 public function pageDataFromId( $dbr, $id, $options = [] ) {
356 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
360 * Load the object from a given source by title
362 * @param object|string|int $from One of the following:
363 * - A DB query result object.
364 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
365 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
366 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
367 * using SELECT FOR UPDATE.
371 public function loadPageData( $from = 'fromdb' ) {
372 $from = self
::convertSelectType( $from );
373 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
374 // We already have the data from the correct location, no need to load it twice.
378 if ( is_int( $from ) ) {
379 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
380 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
381 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
384 && $index == DB_REPLICA
385 && $loadBalancer->getServerCount() > 1
386 && $loadBalancer->hasOrMadeRecentMasterChanges()
388 $from = self
::READ_LATEST
;
389 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
390 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
393 // No idea from where the caller got this data, assume replica DB.
395 $from = self
::READ_NORMAL
;
398 $this->loadFromRow( $data, $from );
402 * Load the object from a database row
405 * @param object|bool $data DB row containing fields returned by selectFields() or false
406 * @param string|int $from One of the following:
407 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
408 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
409 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
410 * the master DB using SELECT FOR UPDATE
412 public function loadFromRow( $data, $from ) {
413 $lc = LinkCache
::singleton();
414 $lc->clearLink( $this->mTitle
);
417 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
419 $this->mTitle
->loadFromRow( $data );
421 // Old-fashioned restrictions
422 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
424 $this->mId
= intval( $data->page_id
);
425 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
426 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
427 $this->mIsRedirect
= intval( $data->page_is_redirect
);
428 $this->mLatest
= intval( $data->page_latest
);
429 // T39225: $latest may no longer match the cached latest Revision object.
430 // Double-check the ID of any cached latest Revision object for consistency.
431 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
432 $this->mLastRevision
= null;
433 $this->mTimestamp
= '';
436 $lc->addBadLinkObj( $this->mTitle
);
438 $this->mTitle
->loadFromRow( false );
440 $this->clearCacheFields();
445 $this->mDataLoaded
= true;
446 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
450 * @return int Page ID
452 public function getId() {
453 if ( !$this->mDataLoaded
) {
454 $this->loadPageData();
460 * @return bool Whether or not the page exists in the database
462 public function exists() {
463 if ( !$this->mDataLoaded
) {
464 $this->loadPageData();
466 return $this->mId
> 0;
470 * Check if this page is something we're going to be showing
471 * some sort of sensible content for. If we return false, page
472 * views (plain action=view) will return an HTTP 404 response,
473 * so spiders and robots can know they're following a bad link.
477 public function hasViewableContent() {
478 return $this->mTitle
->isKnown();
482 * Tests if the article content represents a redirect
486 public function isRedirect() {
487 if ( !$this->mDataLoaded
) {
488 $this->loadPageData();
491 return (bool)$this->mIsRedirect
;
495 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
497 * Will use the revisions actual content model if the page exists,
498 * and the page's default if the page doesn't exist yet.
504 public function getContentModel() {
505 if ( $this->exists() ) {
506 $cache = ObjectCache
::getMainWANInstance();
508 return $cache->getWithSetCallback(
509 $cache->makeKey( 'page-content-model', $this->getLatest() ),
512 $rev = $this->getRevision();
514 // Look at the revision's actual content model
515 return $rev->getContentModel();
517 $title = $this->mTitle
->getPrefixedDBkey();
518 wfWarn( "Page $title exists but has no (visible) revisions!" );
519 return $this->mTitle
->getContentModel();
525 // use the default model for this page
526 return $this->mTitle
->getContentModel();
530 * Loads page_touched and returns a value indicating if it should be used
531 * @return bool True if this page exists and is not a redirect
533 public function checkTouched() {
534 if ( !$this->mDataLoaded
) {
535 $this->loadPageData();
537 return ( $this->mId
&& !$this->mIsRedirect
);
541 * Get the page_touched field
542 * @return string Containing GMT timestamp
544 public function getTouched() {
545 if ( !$this->mDataLoaded
) {
546 $this->loadPageData();
548 return $this->mTouched
;
552 * Get the page_links_updated field
553 * @return string|null Containing GMT timestamp
555 public function getLinksTimestamp() {
556 if ( !$this->mDataLoaded
) {
557 $this->loadPageData();
559 return $this->mLinksUpdated
;
563 * Get the page_latest field
564 * @return int The rev_id of current revision
566 public function getLatest() {
567 if ( !$this->mDataLoaded
) {
568 $this->loadPageData();
570 return (int)$this->mLatest
;
574 * Get the Revision object of the oldest revision
575 * @return Revision|null
577 public function getOldestRevision() {
578 // Try using the replica DB first, then try the master
579 $rev = $this->mTitle
->getFirstRevision();
581 $rev = $this->mTitle
->getFirstRevision( Title
::GAID_FOR_UPDATE
);
587 * Loads everything except the text
588 * This isn't necessary for all uses, so it's only done if needed.
590 protected function loadLastEdit() {
591 if ( $this->mLastRevision
!== null ) {
592 return; // already loaded
595 $latest = $this->getLatest();
597 return; // page doesn't exist or is missing page_latest info
600 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
601 // T39225: if session S1 loads the page row FOR UPDATE, the result always
602 // includes the latest changes committed. This is true even within REPEATABLE-READ
603 // transactions, where S1 normally only sees changes committed before the first S1
604 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
605 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
606 // happened after the first S1 SELECT.
607 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
608 $flags = Revision
::READ_LOCKING
;
609 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
610 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
611 // Bug T93976: if page_latest was loaded from the master, fetch the
612 // revision from there as well, as it may not exist yet on a replica DB.
613 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
614 $flags = Revision
::READ_LATEST
;
615 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
617 $dbr = wfGetDB( DB_REPLICA
);
618 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
621 if ( $revision ) { // sanity
622 $this->setLastEdit( $revision );
627 * Set the latest revision
628 * @param Revision $revision
630 protected function setLastEdit( Revision
$revision ) {
631 $this->mLastRevision
= $revision;
632 $this->mTimestamp
= $revision->getTimestamp();
636 * Get the latest revision
637 * @return Revision|null
639 public function getRevision() {
640 $this->loadLastEdit();
641 if ( $this->mLastRevision
) {
642 return $this->mLastRevision
;
648 * Get the content of the current revision. No side-effects...
650 * @param int $audience One of:
651 * Revision::FOR_PUBLIC to be displayed to all users
652 * Revision::FOR_THIS_USER to be displayed to $wgUser
653 * Revision::RAW get the text regardless of permissions
654 * @param User $user User object to check for, only if FOR_THIS_USER is passed
655 * to the $audience parameter
656 * @return Content|null The content of the current revision
660 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
661 $this->loadLastEdit();
662 if ( $this->mLastRevision
) {
663 return $this->mLastRevision
->getContent( $audience, $user );
669 * @return string MW timestamp of last article revision
671 public function getTimestamp() {
672 // Check if the field has been filled by WikiPage::setTimestamp()
673 if ( !$this->mTimestamp
) {
674 $this->loadLastEdit();
677 return wfTimestamp( TS_MW
, $this->mTimestamp
);
681 * Set the page timestamp (use only to avoid DB queries)
682 * @param string $ts MW timestamp of last article revision
685 public function setTimestamp( $ts ) {
686 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
690 * @param int $audience One of:
691 * Revision::FOR_PUBLIC to be displayed to all users
692 * Revision::FOR_THIS_USER to be displayed to the given user
693 * Revision::RAW get the text regardless of permissions
694 * @param User $user User object to check for, only if FOR_THIS_USER is passed
695 * to the $audience parameter
696 * @return int User ID for the user that made the last article revision
698 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
699 $this->loadLastEdit();
700 if ( $this->mLastRevision
) {
701 return $this->mLastRevision
->getUser( $audience, $user );
708 * Get the User object of the user who created the page
709 * @param int $audience One of:
710 * Revision::FOR_PUBLIC to be displayed to all users
711 * Revision::FOR_THIS_USER to be displayed to the given user
712 * Revision::RAW get the text regardless of permissions
713 * @param User $user User object to check for, only if FOR_THIS_USER is passed
714 * to the $audience parameter
717 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
718 $revision = $this->getOldestRevision();
720 $userName = $revision->getUserText( $audience, $user );
721 return User
::newFromName( $userName, false );
728 * @param int $audience One of:
729 * Revision::FOR_PUBLIC to be displayed to all users
730 * Revision::FOR_THIS_USER to be displayed to the given user
731 * Revision::RAW get the text regardless of permissions
732 * @param User $user User object to check for, only if FOR_THIS_USER is passed
733 * to the $audience parameter
734 * @return string Username of the user that made the last article revision
736 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
737 $this->loadLastEdit();
738 if ( $this->mLastRevision
) {
739 return $this->mLastRevision
->getUserText( $audience, $user );
746 * @param int $audience One of:
747 * Revision::FOR_PUBLIC to be displayed to all users
748 * Revision::FOR_THIS_USER to be displayed to the given user
749 * Revision::RAW get the text regardless of permissions
750 * @param User $user User object to check for, only if FOR_THIS_USER is passed
751 * to the $audience parameter
752 * @return string Comment stored for the last article revision
754 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
755 $this->loadLastEdit();
756 if ( $this->mLastRevision
) {
757 return $this->mLastRevision
->getComment( $audience, $user );
764 * Returns true if last revision was marked as "minor edit"
766 * @return bool Minor edit indicator for the last article revision.
768 public function getMinorEdit() {
769 $this->loadLastEdit();
770 if ( $this->mLastRevision
) {
771 return $this->mLastRevision
->isMinor();
778 * Determine whether a page would be suitable for being counted as an
779 * article in the site_stats table based on the title & its content
781 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
782 * if false, the current database state will be used
785 public function isCountable( $editInfo = false ) {
786 global $wgArticleCountMethod;
788 if ( !$this->mTitle
->isContentPage() ) {
793 $content = $editInfo->pstContent
;
795 $content = $this->getContent();
798 if ( !$content ||
$content->isRedirect() ) {
804 if ( $wgArticleCountMethod === 'link' ) {
805 // nasty special case to avoid re-parsing to detect links
808 // ParserOutput::getLinks() is a 2D array of page links, so
809 // to be really correct we would need to recurse in the array
810 // but the main array should only have items in it if there are
812 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
814 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
815 [ 'pl_from' => $this->getId() ], __METHOD__
);
819 return $content->isCountable( $hasLinks );
823 * If this page is a redirect, get its target
825 * The target will be fetched from the redirect table if possible.
826 * If this page doesn't have an entry there, call insertRedirect()
827 * @return Title|null Title object, or null if this page is not a redirect
829 public function getRedirectTarget() {
830 if ( !$this->mTitle
->isRedirect() ) {
834 if ( $this->mRedirectTarget
!== null ) {
835 return $this->mRedirectTarget
;
838 // Query the redirect table
839 $dbr = wfGetDB( DB_REPLICA
);
840 $row = $dbr->selectRow( 'redirect',
841 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
842 [ 'rd_from' => $this->getId() ],
846 // rd_fragment and rd_interwiki were added later, populate them if empty
847 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
848 $this->mRedirectTarget
= Title
::makeTitle(
849 $row->rd_namespace
, $row->rd_title
,
850 $row->rd_fragment
, $row->rd_interwiki
852 return $this->mRedirectTarget
;
855 // This page doesn't have an entry in the redirect table
856 $this->mRedirectTarget
= $this->insertRedirect();
857 return $this->mRedirectTarget
;
861 * Insert an entry for this page into the redirect table if the content is a redirect
863 * The database update will be deferred via DeferredUpdates
865 * Don't call this function directly unless you know what you're doing.
866 * @return Title|null Title object or null if not a redirect
868 public function insertRedirect() {
869 $content = $this->getContent();
870 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
875 // Update the DB post-send if the page has not cached since now
876 $latest = $this->getLatest();
877 DeferredUpdates
::addCallableUpdate(
878 function () use ( $retval, $latest ) {
879 $this->insertRedirectEntry( $retval, $latest );
881 DeferredUpdates
::POSTSEND
,
889 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
890 * @param Title $rt Redirect target
891 * @param int|null $oldLatest Prior page_latest for check and set
893 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
894 $dbw = wfGetDB( DB_MASTER
);
895 $dbw->startAtomic( __METHOD__
);
897 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
901 'rd_from' => $this->getId(),
902 'rd_namespace' => $rt->getNamespace(),
903 'rd_title' => $rt->getDBkey(),
904 'rd_fragment' => $rt->getFragment(),
905 'rd_interwiki' => $rt->getInterwiki(),
909 'rd_namespace' => $rt->getNamespace(),
910 'rd_title' => $rt->getDBkey(),
911 'rd_fragment' => $rt->getFragment(),
912 'rd_interwiki' => $rt->getInterwiki(),
918 $dbw->endAtomic( __METHOD__
);
922 * Get the Title object or URL this page redirects to
924 * @return bool|Title|string False, Title of in-wiki target, or string with URL
926 public function followRedirect() {
927 return $this->getRedirectURL( $this->getRedirectTarget() );
931 * Get the Title object or URL to use for a redirect. We use Title
932 * objects for same-wiki, non-special redirects and URLs for everything
934 * @param Title $rt Redirect target
935 * @return bool|Title|string False, Title object of local target, or string with URL
937 public function getRedirectURL( $rt ) {
942 if ( $rt->isExternal() ) {
943 if ( $rt->isLocal() ) {
944 // Offsite wikis need an HTTP redirect.
945 // This can be hard to reverse and may produce loops,
946 // so they may be disabled in the site configuration.
947 $source = $this->mTitle
->getFullURL( 'redirect=no' );
948 return $rt->getFullURL( [ 'rdfrom' => $source ] );
950 // External pages without "local" bit set are not valid
956 if ( $rt->isSpecialPage() ) {
957 // Gotta handle redirects to special pages differently:
958 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
959 // Some pages are not valid targets.
960 if ( $rt->isValidRedirectTarget() ) {
961 return $rt->getFullURL();
971 * Get a list of users who have edited this article, not including the user who made
972 * the most recent revision, which you can get from $article->getUser() if you want it
973 * @return UserArrayFromResult
975 public function getContributors() {
976 // @todo FIXME: This is expensive; cache this info somewhere.
978 $dbr = wfGetDB( DB_REPLICA
);
980 $tables = [ 'revision', 'user' ];
983 'user_id' => 'rev_user',
984 'user_name' => 'rev_user_text',
985 'user_real_name' => 'MIN(user_real_name)',
986 'timestamp' => 'MAX(rev_timestamp)',
989 $conds = [ 'rev_page' => $this->getId() ];
991 // The user who made the top revision gets credited as "this page was last edited by
992 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
993 $user = $this->getUser();
995 $conds[] = "rev_user != $user";
997 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1001 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1004 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1008 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1009 'ORDER BY' => 'timestamp DESC',
1012 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1013 return new UserArrayFromResult( $res );
1017 * Should the parser cache be used?
1019 * @param ParserOptions $parserOptions ParserOptions to check
1023 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1024 return $parserOptions->getStubThreshold() == 0
1026 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1027 && $this->getContentHandler()->isParserCacheSupported();
1031 * Get a ParserOutput for the given ParserOptions and revision ID.
1033 * The parser cache will be used if possible. Cache misses that result
1034 * in parser runs are debounced with PoolCounter.
1037 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1038 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1039 * get the current revision (default value)
1040 * @param bool $forceParse Force reindexing, regardless of cache settings
1041 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1043 public function getParserOutput(
1044 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1047 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1049 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1050 throw new InvalidArgumentException(
1051 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1055 wfDebug( __METHOD__
.
1056 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1057 if ( $parserOptions->getStubThreshold() ) {
1058 wfIncrStats( 'pcache.miss.stub' );
1061 if ( $useParserCache ) {
1062 $parserOutput = MediaWikiServices
::getInstance()->getParserCache()
1063 ->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 * Insert a new empty page record for this article.
1133 * This *must* be followed up by creating a revision
1134 * and running $this->updateRevisionOn( ... );
1135 * or else the record will be left in a funky state.
1136 * Best if all done inside a transaction.
1138 * @param IDatabase $dbw
1139 * @param int|null $pageId Custom page ID that will be used for the insert statement
1141 * @return bool|int The newly created page_id key; false if the row was not
1142 * inserted, e.g. because the title already existed or because the specified
1143 * page ID is already in use.
1145 public function insertOn( $dbw, $pageId = null ) {
1146 $pageIdForInsert = $pageId ?
[ 'page_id' => $pageId ] : [];
1150 'page_namespace' => $this->mTitle
->getNamespace(),
1151 'page_title' => $this->mTitle
->getDBkey(),
1152 'page_restrictions' => '',
1153 'page_is_redirect' => 0, // Will set this shortly...
1155 'page_random' => wfRandom(),
1156 'page_touched' => $dbw->timestamp(),
1157 'page_latest' => 0, // Fill this in shortly...
1158 'page_len' => 0, // Fill this in shortly...
1159 ] +
$pageIdForInsert,
1164 if ( $dbw->affectedRows() > 0 ) {
1165 $newid = $pageId ?
(int)$pageId : $dbw->insertId();
1166 $this->mId
= $newid;
1167 $this->mTitle
->resetArticleID( $newid );
1171 return false; // nothing changed
1176 * Update the page record to point to a newly saved revision.
1178 * @param IDatabase $dbw
1179 * @param Revision $revision For ID number, and text used to set
1180 * length and redirect status fields
1181 * @param int $lastRevision If given, will not overwrite the page field
1182 * when different from the currently set value.
1183 * Giving 0 indicates the new page flag should be set on.
1184 * @param bool $lastRevIsRedirect If given, will optimize adding and
1185 * removing rows in redirect table.
1186 * @return bool Success; false if the page row was missing or page_latest changed
1188 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1189 $lastRevIsRedirect = null
1191 global $wgContentHandlerUseDB;
1193 // Assertion to try to catch T92046
1194 if ( (int)$revision->getId() === 0 ) {
1195 throw new InvalidArgumentException(
1196 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1200 $content = $revision->getContent();
1201 $len = $content ?
$content->getSize() : 0;
1202 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1204 $conditions = [ 'page_id' => $this->getId() ];
1206 if ( !is_null( $lastRevision ) ) {
1207 // An extra check against threads stepping on each other
1208 $conditions['page_latest'] = $lastRevision;
1212 'page_latest' => $revision->getId(),
1213 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1214 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1215 'page_is_redirect' => $rt !== null ?
1 : 0,
1219 if ( $wgContentHandlerUseDB ) {
1220 $row['page_content_model'] = $revision->getContentModel();
1223 $dbw->update( 'page',
1228 $result = $dbw->affectedRows() > 0;
1230 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1231 $this->setLastEdit( $revision );
1232 $this->mLatest
= $revision->getId();
1233 $this->mIsRedirect
= (bool)$rt;
1234 // Update the LinkCache.
1235 LinkCache
::singleton()->addGoodLinkObj(
1241 $revision->getContentModel()
1249 * Add row to the redirect table if this is a redirect, remove otherwise.
1251 * @param IDatabase $dbw
1252 * @param Title $redirectTitle Title object pointing to the redirect target,
1253 * or NULL if this is not a redirect
1254 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1255 * removing rows in redirect table.
1256 * @return bool True on success, false on failure
1259 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1260 // Always update redirects (target link might have changed)
1261 // Update/Insert if we don't know if the last revision was a redirect or not
1262 // Delete if changing from redirect to non-redirect
1263 $isRedirect = !is_null( $redirectTitle );
1265 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1269 if ( $isRedirect ) {
1270 $this->insertRedirectEntry( $redirectTitle );
1272 // This is not a redirect, remove row from redirect table
1273 $where = [ 'rd_from' => $this->getId() ];
1274 $dbw->delete( 'redirect', $where, __METHOD__
);
1277 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1278 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1281 return ( $dbw->affectedRows() != 0 );
1285 * If the given revision is newer than the currently set page_latest,
1286 * update the page record. Otherwise, do nothing.
1288 * @deprecated since 1.24, use updateRevisionOn instead
1290 * @param IDatabase $dbw
1291 * @param Revision $revision
1294 public function updateIfNewerOn( $dbw, $revision ) {
1295 $row = $dbw->selectRow(
1296 [ 'revision', 'page' ],
1297 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1299 'page_id' => $this->getId(),
1300 'page_latest=rev_id' ],
1304 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1307 $prev = $row->rev_id
;
1308 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1310 // No or missing previous revision; mark the page as new
1312 $lastRevIsRedirect = null;
1315 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1321 * Get the content that needs to be saved in order to undo all revisions
1322 * between $undo and $undoafter. Revisions must belong to the same page,
1323 * must exist and must not be deleted
1324 * @param Revision $undo
1325 * @param Revision $undoafter Must be an earlier revision than $undo
1326 * @return Content|bool Content on success, false on failure
1328 * Before we had the Content object, this was done in getUndoText
1330 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1331 $handler = $undo->getContentHandler();
1332 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1336 * Returns true if this page's content model supports sections.
1340 * @todo The skin should check this and not offer section functionality if
1341 * sections are not supported.
1342 * @todo The EditPage should check this and not offer section functionality
1343 * if sections are not supported.
1345 public function supportsSections() {
1346 return $this->getContentHandler()->supportsSections();
1350 * @param string|int|null|bool $sectionId Section identifier as a number or string
1351 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1352 * or 'new' for a new section.
1353 * @param Content $sectionContent New content of the section.
1354 * @param string $sectionTitle New section's subject, only if $section is "new".
1355 * @param string $edittime Revision timestamp or null to use the current revision.
1357 * @throws MWException
1358 * @return Content|null New complete article content, or null if error.
1361 * @deprecated since 1.24, use replaceSectionAtRev instead
1363 public function replaceSectionContent(
1364 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1367 if ( $edittime && $sectionId !== 'new' ) {
1368 $dbr = wfGetDB( DB_REPLICA
);
1369 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1370 // Try the master if this thread may have just added it.
1371 // This could be abstracted into a Revision method, but we don't want
1372 // to encourage loading of revisions by timestamp.
1374 && wfGetLB()->getServerCount() > 1
1375 && wfGetLB()->hasOrMadeRecentMasterChanges()
1377 $dbw = wfGetDB( DB_MASTER
);
1378 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1381 $baseRevId = $rev->getId();
1385 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1389 * @param string|int|null|bool $sectionId Section identifier as a number or string
1390 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1391 * or 'new' for a new section.
1392 * @param Content $sectionContent New content of the section.
1393 * @param string $sectionTitle New section's subject, only if $section is "new".
1394 * @param int|null $baseRevId
1396 * @throws MWException
1397 * @return Content|null New complete article content, or null if error.
1401 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1402 $sectionTitle = '', $baseRevId = null
1404 if ( strval( $sectionId ) === '' ) {
1405 // Whole-page edit; let the whole text through
1406 $newContent = $sectionContent;
1408 if ( !$this->supportsSections() ) {
1409 throw new MWException( "sections not supported for content model " .
1410 $this->getContentHandler()->getModelID() );
1413 // T32711: always use current version when adding a new section
1414 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1415 $oldContent = $this->getContent();
1417 $rev = Revision
::newFromId( $baseRevId );
1419 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1420 $this->getId() . "; section: $sectionId)\n" );
1424 $oldContent = $rev->getContent();
1427 if ( !$oldContent ) {
1428 wfDebug( __METHOD__
. ": no page text\n" );
1432 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1439 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1441 * @return int Updated $flags
1443 public function checkFlags( $flags ) {
1444 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1445 if ( $this->exists() ) {
1446 $flags |
= EDIT_UPDATE
;
1456 * Change an existing article or create a new article. Updates RC and all necessary caches,
1457 * optionally via the deferred update array.
1459 * @param Content $content New content
1460 * @param string $summary Edit summary
1461 * @param int $flags Bitfield:
1463 * Article is known or assumed to be non-existent, create a new one
1465 * Article is known or assumed to be pre-existing, update it
1467 * Mark this edit minor, if the user is allowed to do so
1469 * Do not log the change in recentchanges
1471 * Mark the edit a "bot" edit regardless of user rights
1473 * Fill in blank summaries with generated text where possible
1475 * Signal that the page retrieve/save cycle happened entirely in this request.
1477 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1478 * article will be detected. If EDIT_UPDATE is specified and the article
1479 * doesn't exist, the function will return an edit-gone-missing error. If
1480 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1481 * error will be returned. These two conditions are also possible with
1482 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1484 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1485 * This is not the parent revision ID, rather the revision ID for older
1486 * content used as the source for a rollback, for example.
1487 * @param User $user The user doing the edit
1488 * @param string $serialFormat Format for storing the content in the
1490 * @param array|null $tags Change tags to apply to this edit
1491 * Callers are responsible for permission checks
1492 * (with ChangeTags::canAddTagsAccompanyingChange)
1493 * @param Int $undidRevId Id of revision that was undone or 0
1495 * @throws MWException
1496 * @return Status Possible errors:
1497 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1498 * set the fatal flag of $status.
1499 * edit-gone-missing: In update mode, but the article didn't exist.
1500 * edit-conflict: In update mode, the article changed unexpectedly.
1501 * edit-no-change: Warning that the text was the same as before.
1502 * edit-already-exists: In creation mode, but the article already exists.
1504 * Extensions may define additional errors.
1506 * $return->value will contain an associative array with members as follows:
1507 * new: Boolean indicating if the function attempted to create a new article.
1508 * revision: The revision object for the inserted revision, or null.
1511 * @throws MWException
1513 public function doEditContent(
1514 Content
$content, $summary, $flags = 0, $baseRevId = false,
1515 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1517 global $wgUser, $wgUseAutomaticEditSummaries;
1519 // Old default parameter for $tags was null
1520 if ( $tags === null ) {
1524 // Low-level sanity check
1525 if ( $this->mTitle
->getText() === '' ) {
1526 throw new MWException( 'Something is trying to edit an article with an empty title' );
1528 // Make sure the given content type is allowed for this page
1529 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1530 return Status
::newFatal( 'content-not-allowed-here',
1531 ContentHandler
::getLocalizedName( $content->getModel() ),
1532 $this->mTitle
->getPrefixedText()
1536 // Load the data from the master database if needed.
1537 // The caller may already loaded it from the master or even loaded it using
1538 // SELECT FOR UPDATE, so do not override that using clear().
1539 $this->loadPageData( 'fromdbmaster' );
1541 $user = $user ?
: $wgUser;
1542 $flags = $this->checkFlags( $flags );
1544 // Avoid PHP 7.1 warning of passing $this by reference
1547 // Trigger pre-save hook (using provided edit summary)
1548 $hookStatus = Status
::newGood( [] );
1549 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1550 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1551 // Check if the hook rejected the attempted save
1552 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1553 if ( $hookStatus->isOK() ) {
1554 // Hook returned false but didn't call fatal(); use generic message
1555 $hookStatus->fatal( 'edit-hook-aborted' );
1561 $old_revision = $this->getRevision(); // current revision
1562 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1564 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1565 $tags[] = 'mw-contentmodelchange';
1568 // Provide autosummaries if one is not provided and autosummaries are enabled
1569 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1570 $handler = $content->getContentHandler();
1571 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1574 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1575 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1581 // Get the pre-save transform content and final parser output
1582 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1583 $pstContent = $editInfo->pstContent
; // Content object
1585 'bot' => ( $flags & EDIT_FORCE_BOT
),
1586 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1587 'serialized' => $pstContent->serialize( $serialFormat ),
1588 'serialFormat' => $serialFormat,
1589 'baseRevId' => $baseRevId,
1590 'oldRevision' => $old_revision,
1591 'oldContent' => $old_content,
1592 'oldId' => $this->getLatest(),
1593 'oldIsRedirect' => $this->isRedirect(),
1594 'oldCountable' => $this->isCountable(),
1595 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1596 'undidRevId' => $undidRevId
1599 // Actually create the revision and create/update the page
1600 if ( $flags & EDIT_UPDATE
) {
1601 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1603 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1606 // Promote user to any groups they meet the criteria for
1607 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1608 $user->addAutopromoteOnceGroups( 'onEdit' );
1609 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1616 * @param Content $content Pre-save transform content
1619 * @param string $summary
1620 * @param array $meta
1622 * @throws DBUnexpectedError
1624 * @throws FatalError
1625 * @throws MWException
1627 private function doModify(
1628 Content
$content, $flags, User
$user, $summary, array $meta
1630 global $wgUseRCPatrol;
1632 // Update article, but only if changed.
1633 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1635 // Convenience variables
1636 $now = wfTimestampNow();
1637 $oldid = $meta['oldId'];
1638 /** @var Content|null $oldContent */
1639 $oldContent = $meta['oldContent'];
1640 $newsize = $content->getSize();
1643 // Article gone missing
1644 $status->fatal( 'edit-gone-missing' );
1647 } elseif ( !$oldContent ) {
1648 // Sanity check for T39225
1649 throw new MWException( "Could not find text for current revision {$oldid}." );
1652 // @TODO: pass content object?!
1653 $revision = new Revision( [
1654 'page' => $this->getId(),
1655 'title' => $this->mTitle
, // for determining the default content model
1656 'comment' => $summary,
1657 'minor_edit' => $meta['minor'],
1658 'text' => $meta['serialized'],
1660 'parent_id' => $oldid,
1661 'user' => $user->getId(),
1662 'user_text' => $user->getName(),
1663 'timestamp' => $now,
1664 'content_model' => $content->getModel(),
1665 'content_format' => $meta['serialFormat'],
1668 $changed = !$content->equals( $oldContent );
1670 $dbw = wfGetDB( DB_MASTER
);
1673 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1674 $status->merge( $prepStatus );
1675 if ( !$status->isOK() ) {
1679 $dbw->startAtomic( __METHOD__
);
1680 // Get the latest page_latest value while locking it.
1681 // Do a CAS style check to see if it's the same as when this method
1682 // started. If it changed then bail out before touching the DB.
1683 $latestNow = $this->lockAndGetLatest();
1684 if ( $latestNow != $oldid ) {
1685 $dbw->endAtomic( __METHOD__
);
1686 // Page updated or deleted in the mean time
1687 $status->fatal( 'edit-conflict' );
1692 // At this point we are now comitted to returning an OK
1693 // status unless some DB query error or other exception comes up.
1694 // This way callers don't have to call rollback() if $status is bad
1695 // unless they actually try to catch exceptions (which is rare).
1697 // Save the revision text
1698 $revisionId = $revision->insertOn( $dbw );
1699 // Update page_latest and friends to reflect the new revision
1700 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1701 throw new MWException( "Failed to update page row to use new revision." );
1704 Hooks
::run( 'NewRevisionFromEditComplete',
1705 [ $this, $revision, $meta['baseRevId'], $user ] );
1707 // Update recentchanges
1708 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1709 // Mark as patrolled if the user can do so
1710 $patrolled = $wgUseRCPatrol && !count(
1711 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1712 // Add RC row to the DB
1713 RecentChange
::notifyEdit(
1716 $revision->isMinor(),
1720 $this->getTimestamp(),
1723 $oldContent ?
$oldContent->getSize() : 0,
1731 $user->incEditCount();
1733 $dbw->endAtomic( __METHOD__
);
1734 $this->mTimestamp
= $now;
1736 // T34948: revision ID must be set to page {{REVISIONID}} and
1737 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1738 $revision->setId( $this->getLatest() );
1739 $revision->setUserIdAndName(
1740 $this->getUser( Revision
::RAW
),
1741 $this->getUserText( Revision
::RAW
)
1746 // Return the new revision to the caller
1747 $status->value
['revision'] = $revision;
1749 $status->warning( 'edit-no-change' );
1750 // Update page_touched as updateRevisionOn() was not called.
1751 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1752 $this->mTitle
->invalidateCache( $now );
1755 // Do secondary updates once the main changes have been committed...
1756 DeferredUpdates
::addUpdate(
1757 new AtomicSectionUpdate(
1761 $revision, &$user, $content, $summary, &$flags,
1762 $changed, $meta, &$status
1764 // Update links tables, site stats, etc.
1765 $this->doEditUpdates(
1769 'changed' => $changed,
1770 'oldcountable' => $meta['oldCountable'],
1771 'oldrevision' => $meta['oldRevision']
1774 // Avoid PHP 7.1 warning of passing $this by reference
1776 // Trigger post-save hook
1777 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1778 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1779 $meta['undidRevId'] ];
1780 Hooks
::run( 'PageContentSaveComplete', $params );
1783 DeferredUpdates
::PRESEND
1790 * @param Content $content Pre-save transform content
1793 * @param string $summary
1794 * @param array $meta
1796 * @throws DBUnexpectedError
1798 * @throws FatalError
1799 * @throws MWException
1801 private function doCreate(
1802 Content
$content, $flags, User
$user, $summary, array $meta
1804 global $wgUseRCPatrol, $wgUseNPPatrol;
1806 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1808 $now = wfTimestampNow();
1809 $newsize = $content->getSize();
1810 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1811 $status->merge( $prepStatus );
1812 if ( !$status->isOK() ) {
1816 $dbw = wfGetDB( DB_MASTER
);
1817 $dbw->startAtomic( __METHOD__
);
1819 // Add the page record unless one already exists for the title
1820 $newid = $this->insertOn( $dbw );
1821 if ( $newid === false ) {
1822 $dbw->endAtomic( __METHOD__
); // nothing inserted
1823 $status->fatal( 'edit-already-exists' );
1825 return $status; // nothing done
1828 // At this point we are now comitted to returning an OK
1829 // status unless some DB query error or other exception comes up.
1830 // This way callers don't have to call rollback() if $status is bad
1831 // unless they actually try to catch exceptions (which is rare).
1833 // @TODO: pass content object?!
1834 $revision = new Revision( [
1836 'title' => $this->mTitle
, // for determining the default content model
1837 'comment' => $summary,
1838 'minor_edit' => $meta['minor'],
1839 'text' => $meta['serialized'],
1841 'user' => $user->getId(),
1842 'user_text' => $user->getName(),
1843 'timestamp' => $now,
1844 'content_model' => $content->getModel(),
1845 'content_format' => $meta['serialFormat'],
1848 // Save the revision text...
1849 $revisionId = $revision->insertOn( $dbw );
1850 // Update the page record with revision data
1851 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1852 throw new MWException( "Failed to update page row to use new revision." );
1855 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1857 // Update recentchanges
1858 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1859 // Mark as patrolled if the user can do so
1860 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1861 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1862 // Add RC row to the DB
1863 RecentChange
::notifyNew(
1866 $revision->isMinor(),
1878 $user->incEditCount();
1880 $dbw->endAtomic( __METHOD__
);
1881 $this->mTimestamp
= $now;
1883 // Return the new revision to the caller
1884 $status->value
['revision'] = $revision;
1886 // Do secondary updates once the main changes have been committed...
1887 DeferredUpdates
::addUpdate(
1888 new AtomicSectionUpdate(
1892 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1894 // Update links, etc.
1895 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1896 // Avoid PHP 7.1 warning of passing $this by reference
1898 // Trigger post-create hook
1899 $params = [ &$wikiPage, &$user, $content, $summary,
1900 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1901 Hooks
::run( 'PageContentInsertComplete', $params );
1902 // Trigger post-save hook
1903 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1904 Hooks
::run( 'PageContentSaveComplete', $params );
1907 DeferredUpdates
::PRESEND
1914 * Get parser options suitable for rendering the primary article wikitext
1916 * @see ContentHandler::makeParserOptions
1918 * @param IContextSource|User|string $context One of the following:
1919 * - IContextSource: Use the User and the Language of the provided
1921 * - User: Use the provided User object and $wgLang for the language,
1922 * so use an IContextSource object if possible.
1923 * - 'canonical': Canonical options (anonymous user with default
1924 * preferences and content language).
1925 * @return ParserOptions
1927 public function makeParserOptions( $context ) {
1928 $options = $this->getContentHandler()->makeParserOptions( $context );
1930 if ( $this->getTitle()->isConversionTable() ) {
1931 // @todo ConversionTable should become a separate content model, so
1932 // we don't need special cases like this one.
1933 $options->disableContentConversion();
1940 * Prepare content which is about to be saved.
1942 * Prior to 1.30, this returned a stdClass object with the same class
1945 * @param Content $content
1946 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1947 * revision ID is also accepted, but this is deprecated.
1948 * @param User|null $user
1949 * @param string|null $serialFormat
1950 * @param bool $useCache Check shared prepared edit cache
1952 * @return PreparedEdit
1956 public function prepareContentForEdit(
1957 Content
$content, $revision = null, User
$user = null,
1958 $serialFormat = null, $useCache = true
1960 global $wgContLang, $wgUser, $wgAjaxEditStash;
1962 if ( is_object( $revision ) ) {
1963 $revid = $revision->getId();
1966 // This code path is deprecated, and nothing is known to
1967 // use it, so performance here shouldn't be a worry.
1968 if ( $revid !== null ) {
1969 wfDeprecated( __METHOD__
. ' with $revision = revision ID', '1.25' );
1970 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
1976 $user = is_null( $user ) ?
$wgUser : $user;
1977 // XXX: check $user->getId() here???
1979 // Use a sane default for $serialFormat, see T59026
1980 if ( $serialFormat === null ) {
1981 $serialFormat = $content->getContentHandler()->getDefaultFormat();
1984 if ( $this->mPreparedEdit
1985 && isset( $this->mPreparedEdit
->newContent
)
1986 && $this->mPreparedEdit
->newContent
->equals( $content )
1987 && $this->mPreparedEdit
->revid
== $revid
1988 && $this->mPreparedEdit
->format
== $serialFormat
1989 // XXX: also check $user here?
1992 return $this->mPreparedEdit
;
1995 // The edit may have already been prepared via api.php?action=stashedit
1996 $cachedEdit = $useCache && $wgAjaxEditStash
1997 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2000 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2001 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2003 $edit = new PreparedEdit();
2004 if ( $cachedEdit ) {
2005 $edit->timestamp
= $cachedEdit->timestamp
;
2007 $edit->timestamp
= wfTimestampNow();
2009 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2010 $edit->revid
= $revid;
2012 if ( $cachedEdit ) {
2013 $edit->pstContent
= $cachedEdit->pstContent
;
2015 $edit->pstContent
= $content
2016 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2020 $edit->format
= $serialFormat;
2021 $edit->popts
= $this->makeParserOptions( 'canonical' );
2022 if ( $cachedEdit ) {
2023 $edit->output
= $cachedEdit->output
;
2026 // We get here if vary-revision is set. This means that this page references
2027 // itself (such as via self-transclusion). In this case, we need to make sure
2028 // that any such self-references refer to the newly-saved revision, and not
2029 // to the previous one, which could otherwise happen due to replica DB lag.
2030 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2031 $edit->popts
->setCurrentRevisionCallback(
2032 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2033 if ( $title->equals( $revision->getTitle() ) ) {
2036 return call_user_func( $oldCallback, $title, $parser );
2041 // Try to avoid a second parse if {{REVISIONID}} is used
2042 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2043 ? DB_MASTER
// use the best possible guess
2044 : DB_REPLICA
; // T154554
2046 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2047 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2055 $edit->output
= $edit->pstContent
2056 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2060 $edit->newContent
= $content;
2061 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2063 // NOTE: B/C for hooks! don't use these fields!
2064 $edit->newText
= $edit->newContent
2065 ? ContentHandler
::getContentText( $edit->newContent
)
2067 $edit->oldText
= $edit->oldContent
2068 ? ContentHandler
::getContentText( $edit->oldContent
)
2070 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2072 if ( $edit->output
) {
2073 $edit->output
->setCacheTime( wfTimestampNow() );
2076 // Process cache the result
2077 $this->mPreparedEdit
= $edit;
2083 * Do standard deferred updates after page edit.
2084 * Update links tables, site stats, search index and message cache.
2085 * Purges pages that include this page if the text was changed here.
2086 * Every 100th edit, prune the recent changes table.
2088 * @param Revision $revision
2089 * @param User $user User object that did the revision
2090 * @param array $options Array of options, following indexes are used:
2091 * - changed: bool, whether the revision changed the content (default true)
2092 * - created: bool, whether the revision created the page (default false)
2093 * - moved: bool, whether the page was moved (default false)
2094 * - restored: bool, whether the page was undeleted (default false)
2095 * - oldrevision: Revision object for the pre-update revision (default null)
2096 * - oldcountable: bool, null, or string 'no-change' (default null):
2097 * - bool: whether the page was counted as an article before that
2098 * revision, only used in changed is true and created is false
2099 * - null: if created is false, don't update the article count; if created
2100 * is true, do update the article count
2101 * - 'no-change': don't update the article count, ever
2103 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2104 global $wgRCWatchCategoryMembership;
2110 'restored' => false,
2111 'oldrevision' => null,
2112 'oldcountable' => null
2114 $content = $revision->getContent();
2116 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2118 // See if the parser output before $revision was inserted is still valid
2120 if ( !$this->mPreparedEdit
) {
2121 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2122 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2123 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2124 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2125 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2127 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2128 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2129 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2131 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2132 $editInfo = $this->mPreparedEdit
;
2136 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2137 // $text is usually already pre-save transformed once. Avoid using the edit stash
2138 // as any prepared content from there or in doEditContent() was already rejected.
2139 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2142 // Save it to the parser cache.
2143 // Make sure the cache time matches page_touched to avoid double parsing.
2144 MediaWikiServices
::getInstance()->getParserCache()->save(
2145 $editInfo->output
, $this, $editInfo->popts
,
2146 $revision->getTimestamp(), $editInfo->revid
2149 // Update the links tables and other secondary data
2151 $recursive = $options['changed']; // T52785
2152 $updates = $content->getSecondaryDataUpdates(
2153 $this->getTitle(), null, $recursive, $editInfo->output
2155 foreach ( $updates as $update ) {
2156 $update->setCause( 'edit-page', $user->getName() );
2157 if ( $update instanceof LinksUpdate
) {
2158 $update->setRevision( $revision );
2159 $update->setTriggeringUser( $user );
2161 DeferredUpdates
::addUpdate( $update );
2163 if ( $wgRCWatchCategoryMembership
2164 && $this->getContentHandler()->supportsCategories() === true
2165 && ( $options['changed'] ||
$options['created'] )
2166 && !$options['restored']
2168 // Note: jobs are pushed after deferred updates, so the job should be able to see
2169 // the recent change entry (also done via deferred updates) and carry over any
2170 // bot/deletion/IP flags, ect.
2171 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2174 'pageId' => $this->getId(),
2175 'revTimestamp' => $revision->getTimestamp()
2181 // Avoid PHP 7.1 warning of passing $this by reference
2184 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2186 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2187 // Flush old entries from the `recentchanges` table
2188 if ( mt_rand( 0, 9 ) == 0 ) {
2189 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2193 if ( !$this->exists() ) {
2197 $id = $this->getId();
2198 $title = $this->mTitle
->getPrefixedDBkey();
2199 $shortTitle = $this->mTitle
->getDBkey();
2201 if ( $options['oldcountable'] === 'no-change' ||
2202 ( !$options['changed'] && !$options['moved'] )
2205 } elseif ( $options['created'] ) {
2206 $good = (int)$this->isCountable( $editInfo );
2207 } elseif ( $options['oldcountable'] !== null ) {
2208 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2212 $edits = $options['changed'] ?
1 : 0;
2213 $total = $options['created'] ?
1 : 0;
2215 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2216 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2218 // If this is another user's talk page, update newtalk.
2219 // Don't do this if $options['changed'] = false (null-edits) nor if
2220 // it's a minor edit and the user doesn't want notifications for those.
2221 if ( $options['changed']
2222 && $this->mTitle
->getNamespace() == NS_USER_TALK
2223 && $shortTitle != $user->getTitleKey()
2224 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2226 $recipient = User
::newFromName( $shortTitle, false );
2227 if ( !$recipient ) {
2228 wfDebug( __METHOD__
. ": invalid username\n" );
2230 // Avoid PHP 7.1 warning of passing $this by reference
2233 // Allow extensions to prevent user notification
2234 // when a new message is added to their talk page
2235 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2236 if ( User
::isIP( $shortTitle ) ) {
2237 // An anonymous user
2238 $recipient->setNewtalk( true, $revision );
2239 } elseif ( $recipient->isLoggedIn() ) {
2240 $recipient->setNewtalk( true, $revision );
2242 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2248 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2249 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2252 if ( $options['created'] ) {
2253 self
::onArticleCreate( $this->mTitle
);
2254 } elseif ( $options['changed'] ) { // T52785
2255 self
::onArticleEdit( $this->mTitle
, $revision );
2258 ResourceLoaderWikiModule
::invalidateModuleCache(
2259 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2264 * Update the article's restriction field, and leave a log entry.
2265 * This works for protection both existing and non-existing pages.
2267 * @param array $limit Set of restriction keys
2268 * @param array $expiry Per restriction type expiration
2269 * @param int &$cascade Set to false if cascading protection isn't allowed.
2270 * @param string $reason
2271 * @param User $user The user updating the restrictions
2272 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2273 * ($user should be able to add the specified tags before this is called)
2274 * @return Status Status object; if action is taken, $status->value is the log_id of the
2275 * protection log entry.
2277 public function doUpdateRestrictions( array $limit, array $expiry,
2278 &$cascade, $reason, User
$user, $tags = null
2280 global $wgCascadingRestrictionLevels;
2282 if ( wfReadOnly() ) {
2283 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2286 $this->loadPageData( 'fromdbmaster' );
2287 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2288 $id = $this->getId();
2294 // Take this opportunity to purge out expired restrictions
2295 Title
::purgeExpiredRestrictions();
2297 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2298 // we expect a single selection, but the schema allows otherwise.
2299 $isProtected = false;
2303 $dbw = wfGetDB( DB_MASTER
);
2305 foreach ( $restrictionTypes as $action ) {
2306 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2307 $expiry[$action] = 'infinity';
2309 if ( !isset( $limit[$action] ) ) {
2310 $limit[$action] = '';
2311 } elseif ( $limit[$action] != '' ) {
2315 // Get current restrictions on $action
2316 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2317 if ( $current != '' ) {
2318 $isProtected = true;
2321 if ( $limit[$action] != $current ) {
2323 } elseif ( $limit[$action] != '' ) {
2324 // Only check expiry change if the action is actually being
2325 // protected, since expiry does nothing on an not-protected
2327 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2333 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2337 // If nothing has changed, do nothing
2339 return Status
::newGood();
2342 if ( !$protect ) { // No protection at all means unprotection
2343 $revCommentMsg = 'unprotectedarticle-comment';
2344 $logAction = 'unprotect';
2345 } elseif ( $isProtected ) {
2346 $revCommentMsg = 'modifiedarticleprotection-comment';
2347 $logAction = 'modify';
2349 $revCommentMsg = 'protectedarticle-comment';
2350 $logAction = 'protect';
2353 $logRelationsValues = [];
2354 $logRelationsField = null;
2355 $logParamsDetails = [];
2357 // Null revision (used for change tag insertion)
2358 $nullRevision = null;
2360 if ( $id ) { // Protection of existing page
2361 // Avoid PHP 7.1 warning of passing $this by reference
2364 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2365 return Status
::newGood();
2368 // Only certain restrictions can cascade...
2369 $editrestriction = isset( $limit['edit'] )
2370 ?
[ $limit['edit'] ]
2371 : $this->mTitle
->getRestrictions( 'edit' );
2372 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2373 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2375 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2376 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2379 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2380 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2381 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2383 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2384 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2387 // The schema allows multiple restrictions
2388 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2392 // insert null revision to identify the page protection change as edit summary
2393 $latest = $this->getLatest();
2394 $nullRevision = $this->insertProtectNullRevision(
2403 if ( $nullRevision === null ) {
2404 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2407 $logRelationsField = 'pr_id';
2409 // Update restrictions table
2410 foreach ( $limit as $action => $restrictions ) {
2412 'page_restrictions',
2415 'pr_type' => $action
2419 if ( $restrictions != '' ) {
2420 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2422 'page_restrictions',
2425 'pr_type' => $action,
2426 'pr_level' => $restrictions,
2427 'pr_cascade' => $cascadeValue,
2428 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2432 $logRelationsValues[] = $dbw->insertId();
2433 $logParamsDetails[] = [
2435 'level' => $restrictions,
2436 'expiry' => $expiry[$action],
2437 'cascade' => (bool)$cascadeValue,
2442 // Clear out legacy restriction fields
2445 [ 'page_restrictions' => '' ],
2446 [ 'page_id' => $id ],
2450 // Avoid PHP 7.1 warning of passing $this by reference
2453 Hooks
::run( 'NewRevisionFromEditComplete',
2454 [ $this, $nullRevision, $latest, $user ] );
2455 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2456 } else { // Protection of non-existing page (also known as "title protection")
2457 // Cascade protection is meaningless in this case
2460 if ( $limit['create'] != '' ) {
2461 $commentFields = CommentStore
::newKey( 'pt_reason' )->insert( $dbw, $reason );
2462 $dbw->replace( 'protected_titles',
2463 [ [ 'pt_namespace', 'pt_title' ] ],
2465 'pt_namespace' => $this->mTitle
->getNamespace(),
2466 'pt_title' => $this->mTitle
->getDBkey(),
2467 'pt_create_perm' => $limit['create'],
2468 'pt_timestamp' => $dbw->timestamp(),
2469 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2470 'pt_user' => $user->getId(),
2471 ] +
$commentFields, __METHOD__
2473 $logParamsDetails[] = [
2475 'level' => $limit['create'],
2476 'expiry' => $expiry['create'],
2479 $dbw->delete( 'protected_titles',
2481 'pt_namespace' => $this->mTitle
->getNamespace(),
2482 'pt_title' => $this->mTitle
->getDBkey()
2488 $this->mTitle
->flushRestrictions();
2489 InfoAction
::invalidateCache( $this->mTitle
);
2491 if ( $logAction == 'unprotect' ) {
2494 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2496 '4::description' => $protectDescriptionLog, // parameter for IRC
2497 '5:bool:cascade' => $cascade,
2498 'details' => $logParamsDetails, // parameter for localize and api
2502 // Update the protection log
2503 $logEntry = new ManualLogEntry( 'protect', $logAction );
2504 $logEntry->setTarget( $this->mTitle
);
2505 $logEntry->setComment( $reason );
2506 $logEntry->setPerformer( $user );
2507 $logEntry->setParameters( $params );
2508 if ( !is_null( $nullRevision ) ) {
2509 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2511 $logEntry->setTags( $tags );
2512 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2513 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2515 $logId = $logEntry->insert();
2516 $logEntry->publish( $logId );
2518 return Status
::newGood( $logId );
2522 * Insert a new null revision for this page.
2524 * @param string $revCommentMsg Comment message key for the revision
2525 * @param array $limit Set of restriction keys
2526 * @param array $expiry Per restriction type expiration
2527 * @param int $cascade Set to false if cascading protection isn't allowed.
2528 * @param string $reason
2529 * @param User|null $user
2530 * @return Revision|null Null on error
2532 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2533 array $expiry, $cascade, $reason, $user = null
2535 $dbw = wfGetDB( DB_MASTER
);
2537 // Prepare a null revision to be added to the history
2538 $editComment = wfMessage(
2540 $this->mTitle
->getPrefixedText(),
2541 $user ?
$user->getName() : ''
2542 )->inContentLanguage()->text();
2544 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2546 $protectDescription = $this->protectDescription( $limit, $expiry );
2547 if ( $protectDescription ) {
2548 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2549 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2550 ->inContentLanguage()->text();
2553 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2554 $editComment .= wfMessage( 'brackets' )->params(
2555 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2556 )->inContentLanguage()->text();
2559 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2561 $nullRev->insertOn( $dbw );
2563 // Update page record and touch page
2564 $oldLatest = $nullRev->getParentId();
2565 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2572 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2575 protected function formatExpiry( $expiry ) {
2578 if ( $expiry != 'infinity' ) {
2581 $wgContLang->timeanddate( $expiry, false, false ),
2582 $wgContLang->date( $expiry, false, false ),
2583 $wgContLang->time( $expiry, false, false )
2584 )->inContentLanguage()->text();
2586 return wfMessage( 'protect-expiry-indefinite' )
2587 ->inContentLanguage()->text();
2592 * Builds the description to serve as comment for the edit.
2594 * @param array $limit Set of restriction keys
2595 * @param array $expiry Per restriction type expiration
2598 public function protectDescription( array $limit, array $expiry ) {
2599 $protectDescription = '';
2601 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2602 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2603 # All possible message keys are listed here for easier grepping:
2604 # * restriction-create
2605 # * restriction-edit
2606 # * restriction-move
2607 # * restriction-upload
2608 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2609 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2610 # with '' filtered out. All possible message keys are listed below:
2611 # * protect-level-autoconfirmed
2612 # * protect-level-sysop
2613 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2614 ->inContentLanguage()->text();
2616 $expiryText = $this->formatExpiry( $expiry[$action] );
2618 if ( $protectDescription !== '' ) {
2619 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2621 $protectDescription .= wfMessage( 'protect-summary-desc' )
2622 ->params( $actionText, $restrictionsText, $expiryText )
2623 ->inContentLanguage()->text();
2626 return $protectDescription;
2630 * Builds the description to serve as comment for the log entry.
2632 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2633 * protect description text. Keep them in old format to avoid breaking compatibility.
2634 * TODO: Fix protection log to store structured description and format it on-the-fly.
2636 * @param array $limit Set of restriction keys
2637 * @param array $expiry Per restriction type expiration
2640 public function protectDescriptionLog( array $limit, array $expiry ) {
2643 $protectDescriptionLog = '';
2645 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2646 $expiryText = $this->formatExpiry( $expiry[$action] );
2647 $protectDescriptionLog .= $wgContLang->getDirMark() .
2648 "[$action=$restrictions] ($expiryText)";
2651 return trim( $protectDescriptionLog );
2655 * Take an array of page restrictions and flatten it to a string
2656 * suitable for insertion into the page_restrictions field.
2658 * @param string[] $limit
2660 * @throws MWException
2663 protected static function flattenRestrictions( $limit ) {
2664 if ( !is_array( $limit ) ) {
2665 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2671 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2672 $bits[] = "$action=$restrictions";
2675 return implode( ':', $bits );
2679 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2680 * backwards compatibility, if you care about error reporting you should use
2681 * doDeleteArticleReal() instead.
2683 * Deletes the article with database consistency, writes logs, purges caches
2685 * @param string $reason Delete reason for deletion log
2686 * @param bool $suppress Suppress all revisions and log the deletion in
2687 * the suppression log instead of the deletion log
2688 * @param int $u1 Unused
2689 * @param bool $u2 Unused
2690 * @param array|string &$error Array of errors to append to
2691 * @param User $user The deleting user
2692 * @return bool True if successful
2694 public function doDeleteArticle(
2695 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2697 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2698 return $status->isGood();
2702 * Back-end article deletion
2703 * Deletes the article with database consistency, writes logs, purges caches
2707 * @param string $reason Delete reason for deletion log
2708 * @param bool $suppress Suppress all revisions and log the deletion in
2709 * the suppression log instead of the deletion log
2710 * @param int $u1 Unused
2711 * @param bool $u2 Unused
2712 * @param array|string &$error Array of errors to append to
2713 * @param User $user The deleting user
2714 * @param array $tags Tags to apply to the deletion action
2715 * @param string $logsubtype
2716 * @return Status Status object; if successful, $status->value is the log_id of the
2717 * deletion log entry. If the page couldn't be deleted because it wasn't
2718 * found, $status is a non-fatal 'cannotdelete' error
2720 public function doDeleteArticleReal(
2721 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2722 $tags = [], $logsubtype = 'delete'
2724 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2726 wfDebug( __METHOD__
. "\n" );
2728 $status = Status
::newGood();
2730 if ( $this->mTitle
->getDBkey() === '' ) {
2731 $status->error( 'cannotdelete',
2732 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2736 // Avoid PHP 7.1 warning of passing $this by reference
2739 $user = is_null( $user ) ?
$wgUser : $user;
2740 if ( !Hooks
::run( 'ArticleDelete',
2741 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2743 if ( $status->isOK() ) {
2744 // Hook aborted but didn't set a fatal status
2745 $status->fatal( 'delete-hook-aborted' );
2750 $dbw = wfGetDB( DB_MASTER
);
2751 $dbw->startAtomic( __METHOD__
);
2753 $this->loadPageData( self
::READ_LATEST
);
2754 $id = $this->getId();
2755 // T98706: lock the page from various other updates but avoid using
2756 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2757 // the revisions queries (which also JOIN on user). Only lock the page
2758 // row and CAS check on page_latest to see if the trx snapshot matches.
2759 $lockedLatest = $this->lockAndGetLatest();
2760 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2761 $dbw->endAtomic( __METHOD__
);
2762 // Page not there or trx snapshot is stale
2763 $status->error( 'cannotdelete',
2764 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2768 // Given the lock above, we can be confident in the title and page ID values
2769 $namespace = $this->getTitle()->getNamespace();
2770 $dbKey = $this->getTitle()->getDBkey();
2772 // At this point we are now comitted to returning an OK
2773 // status unless some DB query error or other exception comes up.
2774 // This way callers don't have to call rollback() if $status is bad
2775 // unless they actually try to catch exceptions (which is rare).
2777 // we need to remember the old content so we can use it to generate all deletion updates.
2778 $revision = $this->getRevision();
2780 $content = $this->getContent( Revision
::RAW
);
2781 } catch ( Exception
$ex ) {
2782 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2783 . $ex->getMessage() );
2788 $revCommentStore = new CommentStore( 'rev_comment' );
2789 $arCommentStore = new CommentStore( 'ar_comment' );
2791 $fields = Revision
::selectFields();
2794 // Bitfields to further suppress the content
2796 $bitfield = Revision
::SUPPRESSED_ALL
;
2797 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2800 // For now, shunt the revision data into the archive table.
2801 // Text is *not* removed from the text table; bulk storage
2802 // is left intact to avoid breaking block-compression or
2803 // immutable storage schemes.
2804 // In the future, we may keep revisions and mark them with
2805 // the rev_deleted field, which is reserved for this purpose.
2807 // Get all of the page revisions
2808 $commentQuery = $revCommentStore->getJoin();
2809 $res = $dbw->select(
2810 [ 'revision' ] +
$commentQuery['tables'],
2811 $fields +
$commentQuery['fields'],
2812 [ 'rev_page' => $id ],
2815 $commentQuery['joins']
2818 // Build their equivalent archive rows
2822 /** @var int[] Revision IDs of edits that were made by IPs */
2825 foreach ( $res as $row ) {
2826 $comment = $revCommentStore->getComment( $row );
2828 'ar_namespace' => $namespace,
2829 'ar_title' => $dbKey,
2830 'ar_user' => $row->rev_user
,
2831 'ar_user_text' => $row->rev_user_text
,
2832 'ar_timestamp' => $row->rev_timestamp
,
2833 'ar_minor_edit' => $row->rev_minor_edit
,
2834 'ar_rev_id' => $row->rev_id
,
2835 'ar_parent_id' => $row->rev_parent_id
,
2836 'ar_text_id' => $row->rev_text_id
,
2839 'ar_len' => $row->rev_len
,
2840 'ar_page_id' => $id,
2841 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2842 'ar_sha1' => $row->rev_sha1
,
2843 ] +
$arCommentStore->insert( $dbw, $comment );
2844 if ( $wgContentHandlerUseDB ) {
2845 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2846 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2848 $rowsInsert[] = $rowInsert;
2849 $revids[] = $row->rev_id
;
2851 // Keep track of IP edits, so that the corresponding rows can
2852 // be deleted in the ip_changes table.
2853 if ( (int)$row->rev_user
=== 0 && IP
::isValid( $row->rev_user_text
) ) {
2854 $ipRevIds[] = $row->rev_id
;
2857 // Copy them into the archive table
2858 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2859 // Save this so we can pass it to the ArticleDeleteComplete hook.
2860 $archivedRevisionCount = $dbw->affectedRows();
2862 // Clone the title and wikiPage, so we have the information we need when
2863 // we log and run the ArticleDeleteComplete hook.
2864 $logTitle = clone $this->mTitle
;
2865 $wikiPageBeforeDelete = clone $this;
2867 // Now that it's safely backed up, delete it
2868 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2869 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2870 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2871 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__
);
2874 // Also delete records from ip_changes as applicable.
2875 if ( count( $ipRevIds ) > 0 ) {
2876 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__
);
2879 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2880 $logtype = $suppress ?
'suppress' : 'delete';
2882 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2883 $logEntry->setPerformer( $user );
2884 $logEntry->setTarget( $logTitle );
2885 $logEntry->setComment( $reason );
2886 $logEntry->setTags( $tags );
2887 $logid = $logEntry->insert();
2889 $dbw->onTransactionPreCommitOrIdle(
2890 function () use ( $dbw, $logEntry, $logid ) {
2891 // T58776: avoid deadlocks (especially from FileDeleteForm)
2892 $logEntry->publish( $logid );
2897 $dbw->endAtomic( __METHOD__
);
2899 $this->doDeleteUpdates( $id, $content, $revision, $user );
2901 Hooks
::run( 'ArticleDeleteComplete', [
2902 &$wikiPageBeforeDelete,
2908 $archivedRevisionCount
2910 $status->value
= $logid;
2912 // Show log excerpt on 404 pages rather than just a link
2913 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
2914 $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2915 $cache->set( $key, 1, $cache::TTL_DAY
);
2921 * Lock the page row for this title+id and return page_latest (or 0)
2923 * @return int Returns 0 if no row was found with this title+id
2926 public function lockAndGetLatest() {
2927 return (int)wfGetDB( DB_MASTER
)->selectField(
2931 'page_id' => $this->getId(),
2932 // Typically page_id is enough, but some code might try to do
2933 // updates assuming the title is the same, so verify that
2934 'page_namespace' => $this->getTitle()->getNamespace(),
2935 'page_title' => $this->getTitle()->getDBkey()
2943 * Do some database updates after deletion
2945 * @param int $id The page_id value of the page being deleted
2946 * @param Content|null $content Optional page content to be used when determining
2947 * the required updates. This may be needed because $this->getContent()
2948 * may already return null when the page proper was deleted.
2949 * @param Revision|null $revision The latest page revision
2950 * @param User|null $user The user that caused the deletion
2952 public function doDeleteUpdates(
2953 $id, Content
$content = null, Revision
$revision = null, User
$user = null
2956 $countable = $this->isCountable();
2957 } catch ( Exception
$ex ) {
2958 // fallback for deleting broken pages for which we cannot load the content for
2959 // some reason. Note that doDeleteArticleReal() already logged this problem.
2963 // Update site status
2964 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2966 // Delete pagelinks, update secondary indexes, etc
2967 $updates = $this->getDeletionUpdates( $content );
2968 foreach ( $updates as $update ) {
2969 DeferredUpdates
::addUpdate( $update );
2972 $causeAgent = $user ?
$user->getName() : 'unknown';
2973 // Reparse any pages transcluding this page
2974 LinksUpdate
::queueRecursiveJobsForTable(
2975 $this->mTitle
, 'templatelinks', 'delete-page', $causeAgent );
2976 // Reparse any pages including this image
2977 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2978 LinksUpdate
::queueRecursiveJobsForTable(
2979 $this->mTitle
, 'imagelinks', 'delete-page', $causeAgent );
2983 self
::onArticleDelete( $this->mTitle
);
2984 ResourceLoaderWikiModule
::invalidateModuleCache(
2985 $this->mTitle
, $revision, null, wfWikiID()
2988 // Reset this object and the Title object
2989 $this->loadFromRow( false, self
::READ_LATEST
);
2992 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2996 * Roll back the most recent consecutive set of edits to a page
2997 * from the same user; fails if there are no eligible edits to
2998 * roll back to, e.g. user is the sole contributor. This function
2999 * performs permissions checks on $user, then calls commitRollback()
3000 * to do the dirty work
3002 * @todo Separate the business/permission stuff out from backend code
3003 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3005 * @param string $fromP Name of the user whose edits to rollback.
3006 * @param string $summary Custom summary. Set to default summary if empty.
3007 * @param string $token Rollback token.
3008 * @param bool $bot If true, mark all reverted edits as bot.
3010 * @param array &$resultDetails Array contains result-specific array of additional values
3011 * 'alreadyrolled' : 'current' (rev)
3012 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3014 * @param User $user The user performing the rollback
3015 * @param array|null $tags Change tags to apply to the rollback
3016 * Callers are responsible for permission checks
3017 * (with ChangeTags::canAddTagsAccompanyingChange)
3019 * @return array Array of errors, each error formatted as
3020 * array(messagekey, param1, param2, ...).
3021 * On success, the array is empty. This array can also be passed to
3022 * OutputPage::showPermissionsErrorPage().
3024 public function doRollback(
3025 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3027 $resultDetails = null;
3029 // Check permissions
3030 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3031 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3032 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3034 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3035 $errors[] = [ 'sessionfailure' ];
3038 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3039 $errors[] = [ 'actionthrottledtext' ];
3042 // If there were errors, bail out now
3043 if ( !empty( $errors ) ) {
3047 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3051 * Backend implementation of doRollback(), please refer there for parameter
3052 * and return value documentation
3054 * NOTE: This function does NOT check ANY permissions, it just commits the
3055 * rollback to the DB. Therefore, you should only call this function direct-
3056 * ly if you want to use custom permissions checks. If you don't, use
3057 * doRollback() instead.
3058 * @param string $fromP Name of the user whose edits to rollback.
3059 * @param string $summary Custom summary. Set to default summary if empty.
3060 * @param bool $bot If true, mark all reverted edits as bot.
3062 * @param array &$resultDetails Contains result-specific array of additional values
3063 * @param User $guser The user performing the rollback
3064 * @param array|null $tags Change tags to apply to the rollback
3065 * Callers are responsible for permission checks
3066 * (with ChangeTags::canAddTagsAccompanyingChange)
3070 public function commitRollback( $fromP, $summary, $bot,
3071 &$resultDetails, User
$guser, $tags = null
3073 global $wgUseRCPatrol, $wgContLang;
3075 $dbw = wfGetDB( DB_MASTER
);
3077 if ( wfReadOnly() ) {
3078 return [ [ 'readonlytext' ] ];
3081 // Get the last editor
3082 $current = $this->getRevision();
3083 if ( is_null( $current ) ) {
3084 // Something wrong... no page?
3085 return [ [ 'notanarticle' ] ];
3088 $from = str_replace( '_', ' ', $fromP );
3089 // User name given should match up with the top revision.
3090 // If the user was deleted then $from should be empty.
3091 if ( $from != $current->getUserText() ) {
3092 $resultDetails = [ 'current' => $current ];
3093 return [ [ 'alreadyrolled',
3094 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3095 htmlspecialchars( $fromP ),
3096 htmlspecialchars( $current->getUserText() )
3100 // Get the last edit not by this person...
3101 // Note: these may not be public values
3102 $user = intval( $current->getUser( Revision
::RAW
) );
3103 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3104 $s = $dbw->selectRow( 'revision',
3105 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3106 [ 'rev_page' => $current->getPage(),
3107 "rev_user != {$user} OR rev_user_text != {$user_text}"
3109 [ 'USE INDEX' => 'page_timestamp',
3110 'ORDER BY' => 'rev_timestamp DESC' ]
3112 if ( $s === false ) {
3113 // No one else ever edited this page
3114 return [ [ 'cantrollback' ] ];
3115 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3116 ||
$s->rev_deleted
& Revision
::DELETED_USER
3118 // Only admins can see this text
3119 return [ [ 'notvisiblerev' ] ];
3122 // Generate the edit summary if necessary
3123 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3124 if ( empty( $summary ) ) {
3125 if ( $from == '' ) { // no public user name
3126 $summary = wfMessage( 'revertpage-nouser' );
3128 $summary = wfMessage( 'revertpage' );
3132 // Allow the custom summary to use the same args as the default message
3134 $target->getUserText(), $from, $s->rev_id
,
3135 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3136 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3138 if ( $summary instanceof Message
) {
3139 $summary = $summary->params( $args )->inContentLanguage()->text();
3141 $summary = wfMsgReplaceArgs( $summary, $args );
3144 // Trim spaces on user supplied text
3145 $summary = trim( $summary );
3148 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3150 if ( $guser->isAllowed( 'minoredit' ) ) {
3151 $flags |
= EDIT_MINOR
;
3154 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3155 $flags |
= EDIT_FORCE_BOT
;
3158 $targetContent = $target->getContent();
3159 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3161 // Actually store the edit
3162 $status = $this->doEditContent(
3172 // Set patrolling and bot flag on the edits, which gets rollbacked.
3173 // This is done even on edit failure to have patrolling in that case (T64157).
3175 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3176 // Mark all reverted edits as bot
3180 if ( $wgUseRCPatrol ) {
3181 // Mark all reverted edits as patrolled
3182 $set['rc_patrolled'] = 1;
3185 if ( count( $set ) ) {
3186 $dbw->update( 'recentchanges', $set,
3188 'rc_cur_id' => $current->getPage(),
3189 'rc_user_text' => $current->getUserText(),
3190 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3196 if ( !$status->isOK() ) {
3197 return $status->getErrorsArray();
3200 // raise error, when the edit is an edit without a new version
3201 $statusRev = isset( $status->value
['revision'] )
3202 ?
$status->value
['revision']
3204 if ( !( $statusRev instanceof Revision
) ) {
3205 $resultDetails = [ 'current' => $current ];
3206 return [ [ 'alreadyrolled',
3207 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3208 htmlspecialchars( $fromP ),
3209 htmlspecialchars( $current->getUserText() )
3213 if ( $changingContentModel ) {
3214 // If the content model changed during the rollback,
3215 // make sure it gets logged to Special:Log/contentmodel
3216 $log = new ManualLogEntry( 'contentmodel', 'change' );
3217 $log->setPerformer( $guser );
3218 $log->setTarget( $this->mTitle
);
3219 $log->setComment( $summary );
3220 $log->setParameters( [
3221 '4::oldmodel' => $current->getContentModel(),
3222 '5::newmodel' => $targetContent->getModel(),
3225 $logId = $log->insert( $dbw );
3226 $log->publish( $logId );
3229 $revId = $statusRev->getId();
3231 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3234 'summary' => $summary,
3235 'current' => $current,
3236 'target' => $target,
3244 * The onArticle*() functions are supposed to be a kind of hooks
3245 * which should be called whenever any of the specified actions
3248 * This is a good place to put code to clear caches, for instance.
3250 * This is called on page move and undelete, as well as edit
3252 * @param Title $title
3254 public static function onArticleCreate( Title
$title ) {
3255 // Update existence markers on article/talk tabs...
3256 $other = $title->getOtherPage();
3258 $other->purgeSquid();
3260 $title->touchLinks();
3261 $title->purgeSquid();
3262 $title->deleteTitleProtection();
3264 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3266 // Invalidate caches of articles which include this page
3267 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3269 if ( $title->getNamespace() == NS_CATEGORY
) {
3270 // Load the Category object, which will schedule a job to create
3271 // the category table row if necessary. Checking a replica DB is ok
3272 // here, in the worst case it'll run an unnecessary recount job on
3273 // a category that probably doesn't have many members.
3274 Category
::newFromTitle( $title )->getID();
3279 * Clears caches when article is deleted
3281 * @param Title $title
3283 public static function onArticleDelete( Title
$title ) {
3284 // Update existence markers on article/talk tabs...
3285 $other = $title->getOtherPage();
3287 $other->purgeSquid();
3289 $title->touchLinks();
3290 $title->purgeSquid();
3292 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3295 HTMLFileCache
::clearFileCache( $title );
3296 InfoAction
::invalidateCache( $title );
3299 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3300 MessageCache
::singleton()->updateMessageOverride( $title, null );
3304 if ( $title->getNamespace() == NS_FILE
) {
3305 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3309 if ( $title->getNamespace() == NS_USER_TALK
) {
3310 $user = User
::newFromName( $title->getText(), false );
3312 $user->setNewtalk( false );
3317 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3321 * Purge caches on page update etc
3323 * @param Title $title
3324 * @param Revision|null $revision Revision that was just saved, may be null
3326 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3327 // Invalidate caches of articles which include this page
3328 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3330 // Invalidate the caches of all pages which redirect here
3331 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3333 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3335 // Purge CDN for this page only
3336 $title->purgeSquid();
3337 // Clear file cache for this page only
3338 HTMLFileCache
::clearFileCache( $title );
3340 $revid = $revision ?
$revision->getId() : null;
3341 DeferredUpdates
::addCallableUpdate( function () use ( $title, $revid ) {
3342 InfoAction
::invalidateCache( $title, $revid );
3349 * Returns a list of categories this page is a member of.
3350 * Results will include hidden categories
3352 * @return TitleArray
3354 public function getCategories() {
3355 $id = $this->getId();
3357 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3360 $dbr = wfGetDB( DB_REPLICA
);
3361 $res = $dbr->select( 'categorylinks',
3362 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3363 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3364 // as not being aliases, and NS_CATEGORY is numeric
3365 [ 'cl_from' => $id ],
3368 return TitleArray
::newFromResult( $res );
3372 * Returns a list of hidden categories this page is a member of.
3373 * Uses the page_props and categorylinks tables.
3375 * @return array Array of Title objects
3377 public function getHiddenCategories() {
3379 $id = $this->getId();
3385 $dbr = wfGetDB( DB_REPLICA
);
3386 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3388 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3389 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3392 if ( $res !== false ) {
3393 foreach ( $res as $row ) {
3394 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3402 * Auto-generates a deletion reason
3404 * @param bool &$hasHistory Whether the page has a history
3405 * @return string|bool String containing deletion reason or empty string, or boolean false
3406 * if no revision occurred
3408 public function getAutoDeleteReason( &$hasHistory ) {
3409 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3413 * Update all the appropriate counts in the category table, given that
3414 * we've added the categories $added and deleted the categories $deleted.
3416 * This should only be called from deferred updates or jobs to avoid contention.
3418 * @param array $added The names of categories that were added
3419 * @param array $deleted The names of categories that were deleted
3420 * @param int $id Page ID (this should be the original deleted page ID)
3422 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3423 $id = $id ?
: $this->getId();
3424 $ns = $this->getTitle()->getNamespace();
3426 $addFields = [ 'cat_pages = cat_pages + 1' ];
3427 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3428 if ( $ns == NS_CATEGORY
) {
3429 $addFields[] = 'cat_subcats = cat_subcats + 1';
3430 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3431 } elseif ( $ns == NS_FILE
) {
3432 $addFields[] = 'cat_files = cat_files + 1';
3433 $removeFields[] = 'cat_files = cat_files - 1';
3436 $dbw = wfGetDB( DB_MASTER
);
3438 if ( count( $added ) ) {
3439 $existingAdded = $dbw->selectFieldValues(
3442 [ 'cat_title' => $added ],
3446 // For category rows that already exist, do a plain
3447 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3448 // to avoid creating gaps in the cat_id sequence.
3449 if ( count( $existingAdded ) ) {
3453 [ 'cat_title' => $existingAdded ],
3458 $missingAdded = array_diff( $added, $existingAdded );
3459 if ( count( $missingAdded ) ) {
3461 foreach ( $missingAdded as $cat ) {
3463 'cat_title' => $cat,
3465 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3466 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3479 if ( count( $deleted ) ) {
3483 [ 'cat_title' => $deleted ],
3488 foreach ( $added as $catName ) {
3489 $cat = Category
::newFromName( $catName );
3490 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3493 foreach ( $deleted as $catName ) {
3494 $cat = Category
::newFromName( $catName );
3495 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3498 // Refresh counts on categories that should be empty now, to
3499 // trigger possible deletion. Check master for the most
3500 // up-to-date cat_pages.
3501 if ( count( $deleted ) ) {
3502 $rows = $dbw->select(
3504 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3505 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3508 foreach ( $rows as $row ) {
3509 $cat = Category
::newFromRow( $row );
3510 // T166757: do the update after this DB commit
3511 DeferredUpdates
::addCallableUpdate( function () use ( $cat ) {
3512 $cat->refreshCounts();
3519 * Opportunistically enqueue link update jobs given fresh parser output if useful
3521 * @param ParserOutput $parserOutput Current version page output
3524 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3525 if ( wfReadOnly() ) {
3529 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3530 [ $this, $this->mTitle
, $parserOutput ]
3535 $config = RequestContext
::getMain()->getConfig();
3538 'isOpportunistic' => true,
3539 'rootJobTimestamp' => $parserOutput->getCacheTime()
3542 if ( $this->mTitle
->areRestrictionsCascading() ) {
3543 // If the page is cascade protecting, the links should really be up-to-date
3544 JobQueueGroup
::singleton()->lazyPush(
3545 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3547 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3548 // Assume the output contains "dynamic" time/random based magic words.
3549 // Only update pages that expired due to dynamic content and NOT due to edits
3550 // to referenced templates/files. When the cache expires due to dynamic content,
3551 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3552 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3553 // template/file edit already triggered recursive RefreshLinksJob jobs.
3554 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3555 // If a page is uncacheable, do not keep spamming a job for it.
3556 // Although it would be de-duplicated, it would still waste I/O.
3557 $cache = ObjectCache
::getLocalClusterInstance();
3558 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3559 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3560 if ( $cache->add( $key, time(), $ttl ) ) {
3561 JobQueueGroup
::singleton()->lazyPush(
3562 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3570 * Returns a list of updates to be performed when this page is deleted. The
3571 * updates should remove any information about this page from secondary data
3572 * stores such as links tables.
3574 * @param Content|null $content Optional Content object for determining the
3575 * necessary updates.
3576 * @return DeferrableUpdate[]
3578 public function getDeletionUpdates( Content
$content = null ) {
3580 // load content object, which may be used to determine the necessary updates.
3581 // XXX: the content may not be needed to determine the updates.
3583 $content = $this->getContent( Revision
::RAW
);
3584 } catch ( Exception
$ex ) {
3585 // If we can't load the content, something is wrong. Perhaps that's why
3586 // the user is trying to delete the page, so let's not fail in that case.
3587 // Note that doDeleteArticleReal() will already have logged an issue with
3588 // loading the content.
3595 $updates = $content->getDeletionUpdates( $this );
3598 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3603 * Whether this content displayed on this page
3604 * comes from the local database
3609 public function isLocal() {
3614 * The display name for the site this content
3615 * come from. If a subclass overrides isLocal(),
3616 * this could return something other than the
3622 public function getWikiDisplayName() {
3628 * Get the source URL for the content on this page,
3629 * typically the canonical URL, but may be a remote
3630 * link if the content comes from another site
3635 public function getSourceURL() {
3636 return $this->getTitle()->getCanonicalURL();
3640 * @param WANObjectCache $cache
3644 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3645 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3647 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );