3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use \MediaWiki\Logger\LoggerFactory
;
24 use \MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\FakeResultWrapper
;
28 * Class representing a MediaWiki article and history.
30 * Some fields are public only for backwards-compatibility. Use accessors.
31 * In the past, this class was part of Article.php and everything was public.
33 class WikiPage
implements Page
, IDBAccessObject
{
34 // Constants for $mDataLoadedFrom and related
39 public $mTitle = null;
44 public $mDataLoaded = false; // !< Boolean
45 public $mIsRedirect = false; // !< Boolean
46 public $mLatest = false; // !< Integer (false means "not loaded")
49 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
50 public $mPreparedEdit = false;
55 protected $mId = null;
58 * @var int One of the READ_* constants
60 protected $mDataLoadedFrom = self
::READ_NONE
;
65 protected $mRedirectTarget = null;
70 protected $mLastRevision = null;
73 * @var string Timestamp of the current revision or empty string if not loaded
75 protected $mTimestamp = '';
80 protected $mTouched = '19700101000000';
85 protected $mLinksUpdated = '19700101000000';
87 /** @deprecated since 1.29. Added in 1.28 for partial purging, no longer used. */
88 const PURGE_CDN_CACHE
= 1;
89 const PURGE_CLUSTER_PCACHE
= 2;
90 const PURGE_GLOBAL_PCACHE
= 4;
94 * Constructor and clear the article
95 * @param Title $title Reference to a Title object.
97 public function __construct( Title
$title ) {
98 $this->mTitle
= $title;
102 * Makes sure that the mTitle object is cloned
103 * to the newly cloned WikiPage.
105 public function __clone() {
106 $this->mTitle
= clone $this->mTitle
;
110 * Create a WikiPage object of the appropriate class for the given title.
112 * @param Title $title
114 * @throws MWException
115 * @return WikiPage|WikiCategoryPage|WikiFilePage
117 public static function factory( Title
$title ) {
118 $ns = $title->getNamespace();
120 if ( $ns == NS_MEDIA
) {
121 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
122 } elseif ( $ns < 0 ) {
123 throw new MWException( "Invalid or virtual namespace $ns given." );
127 if ( !Hooks
::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
133 $page = new WikiFilePage( $title );
136 $page = new WikiCategoryPage( $title );
139 $page = new WikiPage( $title );
146 * Constructor from a page id
148 * @param int $id Article ID to load
149 * @param string|int $from One of the following values:
150 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
151 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
153 * @return WikiPage|null
155 public static function newFromID( $id, $from = 'fromdb' ) {
156 // page ids are never 0 or negative, see T63166
161 $from = self
::convertSelectType( $from );
162 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
163 $row = $db->selectRow(
164 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
168 return self
::newFromRow( $row, $from );
172 * Constructor from a database row
175 * @param object $row Database row containing at least fields returned by selectFields().
176 * @param string|int $from Source of $data:
177 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
178 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
179 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
182 public static function newFromRow( $row, $from = 'fromdb' ) {
183 $page = self
::factory( Title
::newFromRow( $row ) );
184 $page->loadFromRow( $row, $from );
189 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
191 * @param object|string|int $type
194 private static function convertSelectType( $type ) {
197 return self
::READ_NORMAL
;
199 return self
::READ_LATEST
;
201 return self
::READ_LOCKING
;
203 // It may already be an integer or whatever else
209 * @todo Move this UI stuff somewhere else
211 * @see ContentHandler::getActionOverrides
213 public function getActionOverrides() {
214 return $this->getContentHandler()->getActionOverrides();
218 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
220 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
222 * @return ContentHandler
226 public function getContentHandler() {
227 return ContentHandler
::getForModelID( $this->getContentModel() );
231 * Get the title object of the article
232 * @return Title Title object of this page
234 public function getTitle() {
235 return $this->mTitle
;
242 public function clear() {
243 $this->mDataLoaded
= false;
244 $this->mDataLoadedFrom
= self
::READ_NONE
;
246 $this->clearCacheFields();
250 * Clear the object cache fields
253 protected function clearCacheFields() {
255 $this->mRedirectTarget
= null; // Title object if set
256 $this->mLastRevision
= null; // Latest revision
257 $this->mTouched
= '19700101000000';
258 $this->mLinksUpdated
= '19700101000000';
259 $this->mTimestamp
= '';
260 $this->mIsRedirect
= false;
261 $this->mLatest
= false;
262 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
263 // the requested rev ID and content against the cached one for equality. For most
264 // content types, the output should not change during the lifetime of this cache.
265 // Clearing it can cause extra parses on edit for no reason.
269 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
273 public function clearPreparedEdit() {
274 $this->mPreparedEdit
= false;
278 * Return the list of revision fields that should be selected to create
283 public static function selectFields() {
284 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
295 'page_links_updated',
300 if ( $wgContentHandlerUseDB ) {
301 $fields[] = 'page_content_model';
304 if ( $wgPageLanguageUseDB ) {
305 $fields[] = 'page_lang';
312 * Fetch a page record with the given conditions
313 * @param IDatabase $dbr
314 * @param array $conditions
315 * @param array $options
316 * @return object|bool Database result resource, or false on failure
318 protected function pageData( $dbr, $conditions, $options = [] ) {
319 $fields = self
::selectFields();
321 // Avoid PHP 7.1 warning of passing $this by reference
324 Hooks
::run( 'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
326 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
328 Hooks
::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
334 * Fetch a page record matching the Title object's namespace and title
335 * using a sanitized title string
337 * @param IDatabase $dbr
338 * @param Title $title
339 * @param array $options
340 * @return object|bool Database result resource, or false on failure
342 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
343 return $this->pageData( $dbr, [
344 'page_namespace' => $title->getNamespace(),
345 'page_title' => $title->getDBkey() ], $options );
349 * Fetch a page record matching the requested ID
351 * @param IDatabase $dbr
353 * @param array $options
354 * @return object|bool Database result resource, or false on failure
356 public function pageDataFromId( $dbr, $id, $options = [] ) {
357 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
361 * Load the object from a given source by title
363 * @param object|string|int $from One of the following:
364 * - A DB query result object.
365 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
366 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
367 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
368 * using SELECT FOR UPDATE.
372 public function loadPageData( $from = 'fromdb' ) {
373 $from = self
::convertSelectType( $from );
374 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
375 // We already have the data from the correct location, no need to load it twice.
379 if ( is_int( $from ) ) {
380 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
381 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
384 && $index == DB_REPLICA
385 && wfGetLB()->getServerCount() > 1
386 && wfGetLB()->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() {
579 // Try using the replica DB first, then try the master
581 $db = wfGetDB( DB_REPLICA
);
582 $revSelectFields = Revision
::selectFields();
585 while ( $continue ) {
586 $row = $db->selectRow(
590 'rev_page' => $this->getId()
594 'ORDER BY' => 'rev_timestamp ASC'
601 $db = wfGetDB( DB_MASTER
);
606 return $row ? Revision
::newFromRow( $row ) : null;
610 * Loads everything except the text
611 * This isn't necessary for all uses, so it's only done if needed.
613 protected function loadLastEdit() {
614 if ( $this->mLastRevision
!== null ) {
615 return; // already loaded
618 $latest = $this->getLatest();
620 return; // page doesn't exist or is missing page_latest info
623 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
624 // T39225: if session S1 loads the page row FOR UPDATE, the result always
625 // includes the latest changes committed. This is true even within REPEATABLE-READ
626 // transactions, where S1 normally only sees changes committed before the first S1
627 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
628 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
629 // happened after the first S1 SELECT.
630 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
631 $flags = Revision
::READ_LOCKING
;
632 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
633 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
634 // Bug T93976: if page_latest was loaded from the master, fetch the
635 // revision from there as well, as it may not exist yet on a replica DB.
636 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
637 $flags = Revision
::READ_LATEST
;
638 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
640 $dbr = wfGetDB( DB_REPLICA
);
641 $revision = Revision
::newKnownCurrent( $dbr, $this->getId(), $latest );
644 if ( $revision ) { // sanity
645 $this->setLastEdit( $revision );
650 * Set the latest revision
651 * @param Revision $revision
653 protected function setLastEdit( Revision
$revision ) {
654 $this->mLastRevision
= $revision;
655 $this->mTimestamp
= $revision->getTimestamp();
659 * Get the latest revision
660 * @return Revision|null
662 public function getRevision() {
663 $this->loadLastEdit();
664 if ( $this->mLastRevision
) {
665 return $this->mLastRevision
;
671 * Get the content of the current revision. No side-effects...
673 * @param int $audience One of:
674 * Revision::FOR_PUBLIC to be displayed to all users
675 * Revision::FOR_THIS_USER to be displayed to $wgUser
676 * Revision::RAW get the text regardless of permissions
677 * @param User $user User object to check for, only if FOR_THIS_USER is passed
678 * to the $audience parameter
679 * @return Content|null The content of the current revision
683 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
684 $this->loadLastEdit();
685 if ( $this->mLastRevision
) {
686 return $this->mLastRevision
->getContent( $audience, $user );
692 * @return string MW timestamp of last article revision
694 public function getTimestamp() {
695 // Check if the field has been filled by WikiPage::setTimestamp()
696 if ( !$this->mTimestamp
) {
697 $this->loadLastEdit();
700 return wfTimestamp( TS_MW
, $this->mTimestamp
);
704 * Set the page timestamp (use only to avoid DB queries)
705 * @param string $ts MW timestamp of last article revision
708 public function setTimestamp( $ts ) {
709 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
713 * @param int $audience One of:
714 * Revision::FOR_PUBLIC to be displayed to all users
715 * Revision::FOR_THIS_USER to be displayed to the given user
716 * Revision::RAW get the text regardless of permissions
717 * @param User $user User object to check for, only if FOR_THIS_USER is passed
718 * to the $audience parameter
719 * @return int User ID for the user that made the last article revision
721 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
722 $this->loadLastEdit();
723 if ( $this->mLastRevision
) {
724 return $this->mLastRevision
->getUser( $audience, $user );
731 * Get the User object of the user who created the page
732 * @param int $audience One of:
733 * Revision::FOR_PUBLIC to be displayed to all users
734 * Revision::FOR_THIS_USER to be displayed to the given user
735 * Revision::RAW get the text regardless of permissions
736 * @param User $user User object to check for, only if FOR_THIS_USER is passed
737 * to the $audience parameter
740 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
741 $revision = $this->getOldestRevision();
743 $userName = $revision->getUserText( $audience, $user );
744 return User
::newFromName( $userName, false );
751 * @param int $audience One of:
752 * Revision::FOR_PUBLIC to be displayed to all users
753 * Revision::FOR_THIS_USER to be displayed to the given user
754 * Revision::RAW get the text regardless of permissions
755 * @param User $user User object to check for, only if FOR_THIS_USER is passed
756 * to the $audience parameter
757 * @return string Username of the user that made the last article revision
759 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
760 $this->loadLastEdit();
761 if ( $this->mLastRevision
) {
762 return $this->mLastRevision
->getUserText( $audience, $user );
769 * @param int $audience One of:
770 * Revision::FOR_PUBLIC to be displayed to all users
771 * Revision::FOR_THIS_USER to be displayed to the given user
772 * Revision::RAW get the text regardless of permissions
773 * @param User $user User object to check for, only if FOR_THIS_USER is passed
774 * to the $audience parameter
775 * @return string Comment stored for the last article revision
777 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
778 $this->loadLastEdit();
779 if ( $this->mLastRevision
) {
780 return $this->mLastRevision
->getComment( $audience, $user );
787 * Returns true if last revision was marked as "minor edit"
789 * @return bool Minor edit indicator for the last article revision.
791 public function getMinorEdit() {
792 $this->loadLastEdit();
793 if ( $this->mLastRevision
) {
794 return $this->mLastRevision
->isMinor();
801 * Determine whether a page would be suitable for being counted as an
802 * article in the site_stats table based on the title & its content
804 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
805 * if false, the current database state will be used
808 public function isCountable( $editInfo = false ) {
809 global $wgArticleCountMethod;
811 if ( !$this->mTitle
->isContentPage() ) {
816 $content = $editInfo->pstContent
;
818 $content = $this->getContent();
821 if ( !$content ||
$content->isRedirect() ) {
827 if ( $wgArticleCountMethod === 'link' ) {
828 // nasty special case to avoid re-parsing to detect links
831 // ParserOutput::getLinks() is a 2D array of page links, so
832 // to be really correct we would need to recurse in the array
833 // but the main array should only have items in it if there are
835 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
837 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
838 [ 'pl_from' => $this->getId() ], __METHOD__
);
842 return $content->isCountable( $hasLinks );
846 * If this page is a redirect, get its target
848 * The target will be fetched from the redirect table if possible.
849 * If this page doesn't have an entry there, call insertRedirect()
850 * @return Title|null Title object, or null if this page is not a redirect
852 public function getRedirectTarget() {
853 if ( !$this->mTitle
->isRedirect() ) {
857 if ( $this->mRedirectTarget
!== null ) {
858 return $this->mRedirectTarget
;
861 // Query the redirect table
862 $dbr = wfGetDB( DB_REPLICA
);
863 $row = $dbr->selectRow( 'redirect',
864 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
865 [ 'rd_from' => $this->getId() ],
869 // rd_fragment and rd_interwiki were added later, populate them if empty
870 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
871 $this->mRedirectTarget
= Title
::makeTitle(
872 $row->rd_namespace
, $row->rd_title
,
873 $row->rd_fragment
, $row->rd_interwiki
875 return $this->mRedirectTarget
;
878 // This page doesn't have an entry in the redirect table
879 $this->mRedirectTarget
= $this->insertRedirect();
880 return $this->mRedirectTarget
;
884 * Insert an entry for this page into the redirect table if the content is a redirect
886 * The database update will be deferred via DeferredUpdates
888 * Don't call this function directly unless you know what you're doing.
889 * @return Title|null Title object or null if not a redirect
891 public function insertRedirect() {
892 $content = $this->getContent();
893 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
898 // Update the DB post-send if the page has not cached since now
900 $latest = $this->getLatest();
901 DeferredUpdates
::addCallableUpdate(
902 function () use ( $that, $retval, $latest ) {
903 $that->insertRedirectEntry( $retval, $latest );
905 DeferredUpdates
::POSTSEND
,
913 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
914 * @param Title $rt Redirect target
915 * @param int|null $oldLatest Prior page_latest for check and set
917 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
918 $dbw = wfGetDB( DB_MASTER
);
919 $dbw->startAtomic( __METHOD__
);
921 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
925 'rd_from' => $this->getId(),
926 'rd_namespace' => $rt->getNamespace(),
927 'rd_title' => $rt->getDBkey(),
928 'rd_fragment' => $rt->getFragment(),
929 'rd_interwiki' => $rt->getInterwiki(),
933 'rd_namespace' => $rt->getNamespace(),
934 'rd_title' => $rt->getDBkey(),
935 'rd_fragment' => $rt->getFragment(),
936 'rd_interwiki' => $rt->getInterwiki(),
942 $dbw->endAtomic( __METHOD__
);
946 * Get the Title object or URL this page redirects to
948 * @return bool|Title|string False, Title of in-wiki target, or string with URL
950 public function followRedirect() {
951 return $this->getRedirectURL( $this->getRedirectTarget() );
955 * Get the Title object or URL to use for a redirect. We use Title
956 * objects for same-wiki, non-special redirects and URLs for everything
958 * @param Title $rt Redirect target
959 * @return bool|Title|string False, Title object of local target, or string with URL
961 public function getRedirectURL( $rt ) {
966 if ( $rt->isExternal() ) {
967 if ( $rt->isLocal() ) {
968 // Offsite wikis need an HTTP redirect.
969 // This can be hard to reverse and may produce loops,
970 // so they may be disabled in the site configuration.
971 $source = $this->mTitle
->getFullURL( 'redirect=no' );
972 return $rt->getFullURL( [ 'rdfrom' => $source ] );
974 // External pages without "local" bit set are not valid
980 if ( $rt->isSpecialPage() ) {
981 // Gotta handle redirects to special pages differently:
982 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
983 // Some pages are not valid targets.
984 if ( $rt->isValidRedirectTarget() ) {
985 return $rt->getFullURL();
995 * Get a list of users who have edited this article, not including the user who made
996 * the most recent revision, which you can get from $article->getUser() if you want it
997 * @return UserArrayFromResult
999 public function getContributors() {
1000 // @todo FIXME: This is expensive; cache this info somewhere.
1002 $dbr = wfGetDB( DB_REPLICA
);
1004 if ( $dbr->implicitGroupby() ) {
1005 $realNameField = 'user_real_name';
1007 $realNameField = 'MIN(user_real_name) AS user_real_name';
1010 $tables = [ 'revision', 'user' ];
1013 'user_id' => 'rev_user',
1014 'user_name' => 'rev_user_text',
1016 'timestamp' => 'MAX(rev_timestamp)',
1019 $conds = [ 'rev_page' => $this->getId() ];
1021 // The user who made the top revision gets credited as "this page was last edited by
1022 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1023 $user = $this->getUser();
1025 $conds[] = "rev_user != $user";
1027 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1031 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1034 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1038 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1039 'ORDER BY' => 'timestamp DESC',
1042 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1043 return new UserArrayFromResult( $res );
1047 * Should the parser cache be used?
1049 * @param ParserOptions $parserOptions ParserOptions to check
1053 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1054 return $parserOptions->getStubThreshold() == 0
1056 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1057 && $this->getContentHandler()->isParserCacheSupported();
1061 * Get a ParserOutput for the given ParserOptions and revision ID.
1063 * The parser cache will be used if possible. Cache misses that result
1064 * in parser runs are debounced with PoolCounter.
1067 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1068 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1069 * get the current revision (default value)
1070 * @param bool $forceParse Force reindexing, regardless of cache settings
1071 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1073 public function getParserOutput(
1074 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1077 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1078 wfDebug( __METHOD__
.
1079 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1080 if ( $parserOptions->getStubThreshold() ) {
1081 wfIncrStats( 'pcache.miss.stub' );
1084 if ( $useParserCache ) {
1085 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1086 if ( $parserOutput !== false ) {
1087 return $parserOutput;
1091 if ( $oldid === null ||
$oldid === 0 ) {
1092 $oldid = $this->getLatest();
1095 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1098 return $pool->getParserOutput();
1102 * Do standard deferred updates after page view (existing or missing page)
1103 * @param User $user The relevant user
1104 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1106 public function doViewUpdates( User
$user, $oldid = 0 ) {
1107 if ( wfReadOnly() ) {
1111 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1112 // Update newtalk / watchlist notification status
1114 $user->clearNotification( $this->mTitle
, $oldid );
1115 } catch ( DBError
$e ) {
1116 // Avoid outage if the master is not reachable
1117 MWExceptionHandler
::logException( $e );
1122 * Perform the actions of a page purging
1124 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1125 * controlled how much purging was done.
1127 public function doPurge() {
1128 // Avoid PHP 7.1 warning of passing $this by reference
1131 if ( !Hooks
::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1135 $this->mTitle
->invalidateCache();
1138 HTMLFileCache
::clearFileCache( $this->getTitle() );
1139 // Send purge after above page_touched update was committed
1140 DeferredUpdates
::addUpdate(
1141 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1142 DeferredUpdates
::PRESEND
1145 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1146 $messageCache = MessageCache
::singleton();
1147 $messageCache->updateMessageOverride( $this->mTitle
, $this->getContent() );
1154 * Get the last time a user explicitly purged the page via action=purge
1156 * @return string|bool TS_MW timestamp or false
1158 * @deprecated since 1.29. It will always return false.
1160 public function getLastPurgeTimestamp() {
1161 wfDeprecated( __METHOD__
, '1.29' );
1166 * Insert a new empty page record for this article.
1167 * This *must* be followed up by creating a revision
1168 * and running $this->updateRevisionOn( ... );
1169 * or else the record will be left in a funky state.
1170 * Best if all done inside a transaction.
1172 * @param IDatabase $dbw
1173 * @param int|null $pageId Custom page ID that will be used for the insert statement
1175 * @return bool|int The newly created page_id key; false if the row was not
1176 * inserted, e.g. because the title already existed or because the specified
1177 * page ID is already in use.
1179 public function insertOn( $dbw, $pageId = null ) {
1180 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1184 'page_id' => $pageIdForInsert,
1185 'page_namespace' => $this->mTitle
->getNamespace(),
1186 'page_title' => $this->mTitle
->getDBkey(),
1187 'page_restrictions' => '',
1188 'page_is_redirect' => 0, // Will set this shortly...
1190 'page_random' => wfRandom(),
1191 'page_touched' => $dbw->timestamp(),
1192 'page_latest' => 0, // Fill this in shortly...
1193 'page_len' => 0, // Fill this in shortly...
1199 if ( $dbw->affectedRows() > 0 ) {
1200 $newid = $pageId ?
: $dbw->insertId();
1201 $this->mId
= $newid;
1202 $this->mTitle
->resetArticleID( $newid );
1206 return false; // nothing changed
1211 * Update the page record to point to a newly saved revision.
1213 * @param IDatabase $dbw
1214 * @param Revision $revision For ID number, and text used to set
1215 * length and redirect status fields
1216 * @param int $lastRevision If given, will not overwrite the page field
1217 * when different from the currently set value.
1218 * Giving 0 indicates the new page flag should be set on.
1219 * @param bool $lastRevIsRedirect If given, will optimize adding and
1220 * removing rows in redirect table.
1221 * @return bool Success; false if the page row was missing or page_latest changed
1223 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1224 $lastRevIsRedirect = null
1226 global $wgContentHandlerUseDB;
1228 // Assertion to try to catch T92046
1229 if ( (int)$revision->getId() === 0 ) {
1230 throw new InvalidArgumentException(
1231 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1235 $content = $revision->getContent();
1236 $len = $content ?
$content->getSize() : 0;
1237 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1239 $conditions = [ 'page_id' => $this->getId() ];
1241 if ( !is_null( $lastRevision ) ) {
1242 // An extra check against threads stepping on each other
1243 $conditions['page_latest'] = $lastRevision;
1247 'page_latest' => $revision->getId(),
1248 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1249 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1250 'page_is_redirect' => $rt !== null ?
1 : 0,
1254 if ( $wgContentHandlerUseDB ) {
1255 $row['page_content_model'] = $revision->getContentModel();
1258 $dbw->update( 'page',
1263 $result = $dbw->affectedRows() > 0;
1265 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1266 $this->setLastEdit( $revision );
1267 $this->mLatest
= $revision->getId();
1268 $this->mIsRedirect
= (bool)$rt;
1269 // Update the LinkCache.
1270 LinkCache
::singleton()->addGoodLinkObj(
1276 $revision->getContentModel()
1284 * Add row to the redirect table if this is a redirect, remove otherwise.
1286 * @param IDatabase $dbw
1287 * @param Title $redirectTitle Title object pointing to the redirect target,
1288 * or NULL if this is not a redirect
1289 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1290 * removing rows in redirect table.
1291 * @return bool True on success, false on failure
1294 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1295 // Always update redirects (target link might have changed)
1296 // Update/Insert if we don't know if the last revision was a redirect or not
1297 // Delete if changing from redirect to non-redirect
1298 $isRedirect = !is_null( $redirectTitle );
1300 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1304 if ( $isRedirect ) {
1305 $this->insertRedirectEntry( $redirectTitle );
1307 // This is not a redirect, remove row from redirect table
1308 $where = [ 'rd_from' => $this->getId() ];
1309 $dbw->delete( 'redirect', $where, __METHOD__
);
1312 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1313 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1316 return ( $dbw->affectedRows() != 0 );
1320 * If the given revision is newer than the currently set page_latest,
1321 * update the page record. Otherwise, do nothing.
1323 * @deprecated since 1.24, use updateRevisionOn instead
1325 * @param IDatabase $dbw
1326 * @param Revision $revision
1329 public function updateIfNewerOn( $dbw, $revision ) {
1331 $row = $dbw->selectRow(
1332 [ 'revision', 'page' ],
1333 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1335 'page_id' => $this->getId(),
1336 'page_latest=rev_id' ],
1340 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1343 $prev = $row->rev_id
;
1344 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1346 // No or missing previous revision; mark the page as new
1348 $lastRevIsRedirect = null;
1351 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1357 * Get the content that needs to be saved in order to undo all revisions
1358 * between $undo and $undoafter. Revisions must belong to the same page,
1359 * must exist and must not be deleted
1360 * @param Revision $undo
1361 * @param Revision $undoafter Must be an earlier revision than $undo
1362 * @return Content|bool Content on success, false on failure
1364 * Before we had the Content object, this was done in getUndoText
1366 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1367 $handler = $undo->getContentHandler();
1368 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1372 * Returns true if this page's content model supports sections.
1376 * @todo The skin should check this and not offer section functionality if
1377 * sections are not supported.
1378 * @todo The EditPage should check this and not offer section functionality
1379 * if sections are not supported.
1381 public function supportsSections() {
1382 return $this->getContentHandler()->supportsSections();
1386 * @param string|int|null|bool $sectionId Section identifier as a number or string
1387 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1388 * or 'new' for a new section.
1389 * @param Content $sectionContent New content of the section.
1390 * @param string $sectionTitle New section's subject, only if $section is "new".
1391 * @param string $edittime Revision timestamp or null to use the current revision.
1393 * @throws MWException
1394 * @return Content|null New complete article content, or null if error.
1397 * @deprecated since 1.24, use replaceSectionAtRev instead
1399 public function replaceSectionContent(
1400 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1404 if ( $edittime && $sectionId !== 'new' ) {
1405 $dbr = wfGetDB( DB_REPLICA
);
1406 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1407 // Try the master if this thread may have just added it.
1408 // This could be abstracted into a Revision method, but we don't want
1409 // to encourage loading of revisions by timestamp.
1411 && wfGetLB()->getServerCount() > 1
1412 && wfGetLB()->hasOrMadeRecentMasterChanges()
1414 $dbw = wfGetDB( DB_MASTER
);
1415 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1418 $baseRevId = $rev->getId();
1422 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1426 * @param string|int|null|bool $sectionId Section identifier as a number or string
1427 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1428 * or 'new' for a new section.
1429 * @param Content $sectionContent New content of the section.
1430 * @param string $sectionTitle New section's subject, only if $section is "new".
1431 * @param int|null $baseRevId
1433 * @throws MWException
1434 * @return Content|null New complete article content, or null if error.
1438 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1439 $sectionTitle = '', $baseRevId = null
1442 if ( strval( $sectionId ) === '' ) {
1443 // Whole-page edit; let the whole text through
1444 $newContent = $sectionContent;
1446 if ( !$this->supportsSections() ) {
1447 throw new MWException( "sections not supported for content model " .
1448 $this->getContentHandler()->getModelID() );
1451 // T32711: always use current version when adding a new section
1452 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1453 $oldContent = $this->getContent();
1455 $rev = Revision
::newFromId( $baseRevId );
1457 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1458 $this->getId() . "; section: $sectionId)\n" );
1462 $oldContent = $rev->getContent();
1465 if ( !$oldContent ) {
1466 wfDebug( __METHOD__
. ": no page text\n" );
1470 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1477 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1479 * @return int Updated $flags
1481 public function checkFlags( $flags ) {
1482 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1483 if ( $this->exists() ) {
1484 $flags |
= EDIT_UPDATE
;
1494 * Change an existing article or create a new article. Updates RC and all necessary caches,
1495 * optionally via the deferred update array.
1497 * @param Content $content New content
1498 * @param string $summary Edit summary
1499 * @param int $flags Bitfield:
1501 * Article is known or assumed to be non-existent, create a new one
1503 * Article is known or assumed to be pre-existing, update it
1505 * Mark this edit minor, if the user is allowed to do so
1507 * Do not log the change in recentchanges
1509 * Mark the edit a "bot" edit regardless of user rights
1511 * Fill in blank summaries with generated text where possible
1513 * Signal that the page retrieve/save cycle happened entirely in this request.
1515 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1516 * article will be detected. If EDIT_UPDATE is specified and the article
1517 * doesn't exist, the function will return an edit-gone-missing error. If
1518 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1519 * error will be returned. These two conditions are also possible with
1520 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1522 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1523 * This is not the parent revision ID, rather the revision ID for older
1524 * content used as the source for a rollback, for example.
1525 * @param User $user The user doing the edit
1526 * @param string $serialFormat Format for storing the content in the
1528 * @param array|null $tags Change tags to apply to this edit
1529 * Callers are responsible for permission checks
1530 * (with ChangeTags::canAddTagsAccompanyingChange)
1531 * @param Int $undidRevId Id of revision that was undone or 0
1533 * @throws MWException
1534 * @return Status Possible errors:
1535 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1536 * set the fatal flag of $status.
1537 * edit-gone-missing: In update mode, but the article didn't exist.
1538 * edit-conflict: In update mode, the article changed unexpectedly.
1539 * edit-no-change: Warning that the text was the same as before.
1540 * edit-already-exists: In creation mode, but the article already exists.
1542 * Extensions may define additional errors.
1544 * $return->value will contain an associative array with members as follows:
1545 * new: Boolean indicating if the function attempted to create a new article.
1546 * revision: The revision object for the inserted revision, or null.
1549 * @throws MWException
1551 public function doEditContent(
1552 Content
$content, $summary, $flags = 0, $baseRevId = false,
1553 User
$user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1555 global $wgUser, $wgUseAutomaticEditSummaries;
1557 // Old default parameter for $tags was null
1558 if ( $tags === null ) {
1562 // Low-level sanity check
1563 if ( $this->mTitle
->getText() === '' ) {
1564 throw new MWException( 'Something is trying to edit an article with an empty title' );
1566 // Make sure the given content type is allowed for this page
1567 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1568 return Status
::newFatal( 'content-not-allowed-here',
1569 ContentHandler
::getLocalizedName( $content->getModel() ),
1570 $this->mTitle
->getPrefixedText()
1574 // Load the data from the master database if needed.
1575 // The caller may already loaded it from the master or even loaded it using
1576 // SELECT FOR UPDATE, so do not override that using clear().
1577 $this->loadPageData( 'fromdbmaster' );
1579 $user = $user ?
: $wgUser;
1580 $flags = $this->checkFlags( $flags );
1582 // Avoid PHP 7.1 warning of passing $this by reference
1585 // Trigger pre-save hook (using provided edit summary)
1586 $hookStatus = Status
::newGood( [] );
1587 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1588 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1589 // Check if the hook rejected the attempted save
1590 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
1591 if ( $hookStatus->isOK() ) {
1592 // Hook returned false but didn't call fatal(); use generic message
1593 $hookStatus->fatal( 'edit-hook-aborted' );
1599 $old_revision = $this->getRevision(); // current revision
1600 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1602 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1603 $tags[] = 'mw-contentmodelchange';
1606 // Provide autosummaries if one is not provided and autosummaries are enabled
1607 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1608 $handler = $content->getContentHandler();
1609 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1612 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1613 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1619 // Get the pre-save transform content and final parser output
1620 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1621 $pstContent = $editInfo->pstContent
; // Content object
1623 'bot' => ( $flags & EDIT_FORCE_BOT
),
1624 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1625 'serialized' => $editInfo->pst
,
1626 'serialFormat' => $serialFormat,
1627 'baseRevId' => $baseRevId,
1628 'oldRevision' => $old_revision,
1629 'oldContent' => $old_content,
1630 'oldId' => $this->getLatest(),
1631 'oldIsRedirect' => $this->isRedirect(),
1632 'oldCountable' => $this->isCountable(),
1633 'tags' => ( $tags !== null ) ?
(array)$tags : [],
1634 'undidRevId' => $undidRevId
1637 // Actually create the revision and create/update the page
1638 if ( $flags & EDIT_UPDATE
) {
1639 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1641 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1644 // Promote user to any groups they meet the criteria for
1645 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1646 $user->addAutopromoteOnceGroups( 'onEdit' );
1647 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1654 * @param Content $content Pre-save transform content
1655 * @param integer $flags
1657 * @param string $summary
1658 * @param array $meta
1660 * @throws DBUnexpectedError
1662 * @throws FatalError
1663 * @throws MWException
1665 private function doModify(
1666 Content
$content, $flags, User
$user, $summary, array $meta
1668 global $wgUseRCPatrol;
1670 // Update article, but only if changed.
1671 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1673 // Convenience variables
1674 $now = wfTimestampNow();
1675 $oldid = $meta['oldId'];
1676 /** @var $oldContent Content|null */
1677 $oldContent = $meta['oldContent'];
1678 $newsize = $content->getSize();
1681 // Article gone missing
1682 $status->fatal( 'edit-gone-missing' );
1685 } elseif ( !$oldContent ) {
1686 // Sanity check for T39225
1687 throw new MWException( "Could not find text for current revision {$oldid}." );
1690 // @TODO: pass content object?!
1691 $revision = new Revision( [
1692 'page' => $this->getId(),
1693 'title' => $this->mTitle
, // for determining the default content model
1694 'comment' => $summary,
1695 'minor_edit' => $meta['minor'],
1696 'text' => $meta['serialized'],
1698 'parent_id' => $oldid,
1699 'user' => $user->getId(),
1700 'user_text' => $user->getName(),
1701 'timestamp' => $now,
1702 'content_model' => $content->getModel(),
1703 'content_format' => $meta['serialFormat'],
1706 $changed = !$content->equals( $oldContent );
1708 $dbw = wfGetDB( DB_MASTER
);
1711 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1712 $status->merge( $prepStatus );
1713 if ( !$status->isOK() ) {
1717 $dbw->startAtomic( __METHOD__
);
1718 // Get the latest page_latest value while locking it.
1719 // Do a CAS style check to see if it's the same as when this method
1720 // started. If it changed then bail out before touching the DB.
1721 $latestNow = $this->lockAndGetLatest();
1722 if ( $latestNow != $oldid ) {
1723 $dbw->endAtomic( __METHOD__
);
1724 // Page updated or deleted in the mean time
1725 $status->fatal( 'edit-conflict' );
1730 // At this point we are now comitted to returning an OK
1731 // status unless some DB query error or other exception comes up.
1732 // This way callers don't have to call rollback() if $status is bad
1733 // unless they actually try to catch exceptions (which is rare).
1735 // Save the revision text
1736 $revisionId = $revision->insertOn( $dbw );
1737 // Update page_latest and friends to reflect the new revision
1738 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1739 throw new MWException( "Failed to update page row to use new revision." );
1742 Hooks
::run( 'NewRevisionFromEditComplete',
1743 [ $this, $revision, $meta['baseRevId'], $user ] );
1745 // Update recentchanges
1746 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1747 // Mark as patrolled if the user can do so
1748 $patrolled = $wgUseRCPatrol && !count(
1749 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1750 // Add RC row to the DB
1751 RecentChange
::notifyEdit(
1754 $revision->isMinor(),
1758 $this->getTimestamp(),
1761 $oldContent ?
$oldContent->getSize() : 0,
1769 $user->incEditCount();
1771 $dbw->endAtomic( __METHOD__
);
1772 $this->mTimestamp
= $now;
1774 // T34948: revision ID must be set to page {{REVISIONID}} and
1775 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1776 $revision->setId( $this->getLatest() );
1777 $revision->setUserIdAndName(
1778 $this->getUser( Revision
::RAW
),
1779 $this->getUserText( Revision
::RAW
)
1784 // Return the new revision to the caller
1785 $status->value
['revision'] = $revision;
1787 $status->warning( 'edit-no-change' );
1788 // Update page_touched as updateRevisionOn() was not called.
1789 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1790 $this->mTitle
->invalidateCache( $now );
1793 // Do secondary updates once the main changes have been committed...
1794 DeferredUpdates
::addUpdate(
1795 new AtomicSectionUpdate(
1799 $revision, &$user, $content, $summary, &$flags,
1800 $changed, $meta, &$status
1802 // Update links tables, site stats, etc.
1803 $this->doEditUpdates(
1807 'changed' => $changed,
1808 'oldcountable' => $meta['oldCountable'],
1809 'oldrevision' => $meta['oldRevision']
1812 // Avoid PHP 7.1 warning of passing $this by reference
1814 // Trigger post-save hook
1815 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR
,
1816 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1817 $meta['undidRevId'] ];
1818 Hooks
::run( 'PageContentSaveComplete', $params );
1821 DeferredUpdates
::PRESEND
1828 * @param Content $content Pre-save transform content
1829 * @param integer $flags
1831 * @param string $summary
1832 * @param array $meta
1834 * @throws DBUnexpectedError
1836 * @throws FatalError
1837 * @throws MWException
1839 private function doCreate(
1840 Content
$content, $flags, User
$user, $summary, array $meta
1842 global $wgUseRCPatrol, $wgUseNPPatrol;
1844 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1846 $now = wfTimestampNow();
1847 $newsize = $content->getSize();
1848 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1849 $status->merge( $prepStatus );
1850 if ( !$status->isOK() ) {
1854 $dbw = wfGetDB( DB_MASTER
);
1855 $dbw->startAtomic( __METHOD__
);
1857 // Add the page record unless one already exists for the title
1858 $newid = $this->insertOn( $dbw );
1859 if ( $newid === false ) {
1860 $dbw->endAtomic( __METHOD__
); // nothing inserted
1861 $status->fatal( 'edit-already-exists' );
1863 return $status; // nothing done
1866 // At this point we are now comitted to returning an OK
1867 // status unless some DB query error or other exception comes up.
1868 // This way callers don't have to call rollback() if $status is bad
1869 // unless they actually try to catch exceptions (which is rare).
1871 // @TODO: pass content object?!
1872 $revision = new Revision( [
1874 'title' => $this->mTitle
, // for determining the default content model
1875 'comment' => $summary,
1876 'minor_edit' => $meta['minor'],
1877 'text' => $meta['serialized'],
1879 'user' => $user->getId(),
1880 'user_text' => $user->getName(),
1881 'timestamp' => $now,
1882 'content_model' => $content->getModel(),
1883 'content_format' => $meta['serialFormat'],
1886 // Save the revision text...
1887 $revisionId = $revision->insertOn( $dbw );
1888 // Update the page record with revision data
1889 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1890 throw new MWException( "Failed to update page row to use new revision." );
1893 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1895 // Update recentchanges
1896 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1897 // Mark as patrolled if the user can do so
1898 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1899 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1900 // Add RC row to the DB
1901 RecentChange
::notifyNew(
1904 $revision->isMinor(),
1916 $user->incEditCount();
1918 $dbw->endAtomic( __METHOD__
);
1919 $this->mTimestamp
= $now;
1921 // Return the new revision to the caller
1922 $status->value
['revision'] = $revision;
1924 // Do secondary updates once the main changes have been committed...
1925 DeferredUpdates
::addUpdate(
1926 new AtomicSectionUpdate(
1930 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1932 // Update links, etc.
1933 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1934 // Avoid PHP 7.1 warning of passing $this by reference
1936 // Trigger post-create hook
1937 $params = [ &$wikiPage, &$user, $content, $summary,
1938 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1939 Hooks
::run( 'PageContentInsertComplete', $params );
1940 // Trigger post-save hook
1941 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1942 Hooks
::run( 'PageContentSaveComplete', $params );
1945 DeferredUpdates
::PRESEND
1952 * Get parser options suitable for rendering the primary article wikitext
1954 * @see ContentHandler::makeParserOptions
1956 * @param IContextSource|User|string $context One of the following:
1957 * - IContextSource: Use the User and the Language of the provided
1959 * - User: Use the provided User object and $wgLang for the language,
1960 * so use an IContextSource object if possible.
1961 * - 'canonical': Canonical options (anonymous user with default
1962 * preferences and content language).
1963 * @return ParserOptions
1965 public function makeParserOptions( $context ) {
1966 $options = $this->getContentHandler()->makeParserOptions( $context );
1968 if ( $this->getTitle()->isConversionTable() ) {
1969 // @todo ConversionTable should become a separate content model, so
1970 // we don't need special cases like this one.
1971 $options->disableContentConversion();
1978 * Prepare content which is about to be saved.
1979 * Returns a stdClass with source, pst and output members
1981 * @param Content $content
1982 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
1983 * revision ID is also accepted, but this is deprecated.
1984 * @param User|null $user
1985 * @param string|null $serialFormat
1986 * @param bool $useCache Check shared prepared edit cache
1992 public function prepareContentForEdit(
1993 Content
$content, $revision = null, User
$user = null,
1994 $serialFormat = null, $useCache = true
1996 global $wgContLang, $wgUser, $wgAjaxEditStash;
1998 if ( is_object( $revision ) ) {
1999 $revid = $revision->getId();
2002 // This code path is deprecated, and nothing is known to
2003 // use it, so performance here shouldn't be a worry.
2004 if ( $revid !== null ) {
2005 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2011 $user = is_null( $user ) ?
$wgUser : $user;
2012 // XXX: check $user->getId() here???
2014 // Use a sane default for $serialFormat, see T59026
2015 if ( $serialFormat === null ) {
2016 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2019 if ( $this->mPreparedEdit
2020 && isset( $this->mPreparedEdit
->newContent
)
2021 && $this->mPreparedEdit
->newContent
->equals( $content )
2022 && $this->mPreparedEdit
->revid
== $revid
2023 && $this->mPreparedEdit
->format
== $serialFormat
2024 // XXX: also check $user here?
2027 return $this->mPreparedEdit
;
2030 // The edit may have already been prepared via api.php?action=stashedit
2031 $cachedEdit = $useCache && $wgAjaxEditStash
2032 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2035 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2036 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2039 if ( $cachedEdit ) {
2040 $edit->timestamp
= $cachedEdit->timestamp
;
2042 $edit->timestamp
= wfTimestampNow();
2044 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2045 $edit->revid
= $revid;
2047 if ( $cachedEdit ) {
2048 $edit->pstContent
= $cachedEdit->pstContent
;
2050 $edit->pstContent
= $content
2051 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2055 $edit->format
= $serialFormat;
2056 $edit->popts
= $this->makeParserOptions( 'canonical' );
2057 if ( $cachedEdit ) {
2058 $edit->output
= $cachedEdit->output
;
2061 // We get here if vary-revision is set. This means that this page references
2062 // itself (such as via self-transclusion). In this case, we need to make sure
2063 // that any such self-references refer to the newly-saved revision, and not
2064 // to the previous one, which could otherwise happen due to replica DB lag.
2065 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2066 $edit->popts
->setCurrentRevisionCallback(
2067 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2068 if ( $title->equals( $revision->getTitle() ) ) {
2071 return call_user_func( $oldCallback, $title, $parser );
2076 // Try to avoid a second parse if {{REVISIONID}} is used
2077 $dbIndex = ( $this->mDataLoadedFrom
& self
::READ_LATEST
) === self
::READ_LATEST
2078 ? DB_MASTER
// use the best possible guess
2079 : DB_REPLICA
; // T154554
2081 $edit->popts
->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2082 return 1 +
(int)wfGetDB( $dbIndex )->selectField(
2090 $edit->output
= $edit->pstContent
2091 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2095 $edit->newContent
= $content;
2096 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2098 // NOTE: B/C for hooks! don't use these fields!
2099 $edit->newText
= $edit->newContent
2100 ? ContentHandler
::getContentText( $edit->newContent
)
2102 $edit->oldText
= $edit->oldContent
2103 ? ContentHandler
::getContentText( $edit->oldContent
)
2105 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2107 if ( $edit->output
) {
2108 $edit->output
->setCacheTime( wfTimestampNow() );
2111 // Process cache the result
2112 $this->mPreparedEdit
= $edit;
2118 * Do standard deferred updates after page edit.
2119 * Update links tables, site stats, search index and message cache.
2120 * Purges pages that include this page if the text was changed here.
2121 * Every 100th edit, prune the recent changes table.
2123 * @param Revision $revision
2124 * @param User $user User object that did the revision
2125 * @param array $options Array of options, following indexes are used:
2126 * - changed: boolean, whether the revision changed the content (default true)
2127 * - created: boolean, whether the revision created the page (default false)
2128 * - moved: boolean, whether the page was moved (default false)
2129 * - restored: boolean, whether the page was undeleted (default false)
2130 * - oldrevision: Revision object for the pre-update revision (default null)
2131 * - oldcountable: boolean, null, or string 'no-change' (default null):
2132 * - boolean: whether the page was counted as an article before that
2133 * revision, only used in changed is true and created is false
2134 * - null: if created is false, don't update the article count; if created
2135 * is true, do update the article count
2136 * - 'no-change': don't update the article count, ever
2138 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2139 global $wgRCWatchCategoryMembership;
2145 'restored' => false,
2146 'oldrevision' => null,
2147 'oldcountable' => null
2149 $content = $revision->getContent();
2151 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2153 // See if the parser output before $revision was inserted is still valid
2155 if ( !$this->mPreparedEdit
) {
2156 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2157 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2158 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2159 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2160 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2162 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2163 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2164 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2166 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2167 $editInfo = $this->mPreparedEdit
;
2171 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2172 // $text is usually already pre-save transformed once. Avoid using the edit stash
2173 // as any prepared content from there or in doEditContent() was already rejected.
2174 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2177 // Save it to the parser cache.
2178 // Make sure the cache time matches page_touched to avoid double parsing.
2179 ParserCache
::singleton()->save(
2180 $editInfo->output
, $this, $editInfo->popts
,
2181 $revision->getTimestamp(), $editInfo->revid
2184 // Update the links tables and other secondary data
2186 $recursive = $options['changed']; // T52785
2187 $updates = $content->getSecondaryDataUpdates(
2188 $this->getTitle(), null, $recursive, $editInfo->output
2190 foreach ( $updates as $update ) {
2191 if ( $update instanceof LinksUpdate
) {
2192 $update->setRevision( $revision );
2193 $update->setTriggeringUser( $user );
2195 DeferredUpdates
::addUpdate( $update );
2197 if ( $wgRCWatchCategoryMembership
2198 && $this->getContentHandler()->supportsCategories() === true
2199 && ( $options['changed'] ||
$options['created'] )
2200 && !$options['restored']
2202 // Note: jobs are pushed after deferred updates, so the job should be able to see
2203 // the recent change entry (also done via deferred updates) and carry over any
2204 // bot/deletion/IP flags, ect.
2205 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2208 'pageId' => $this->getId(),
2209 'revTimestamp' => $revision->getTimestamp()
2215 // Avoid PHP 7.1 warning of passing $this by reference
2218 Hooks
::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2220 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2221 // Flush old entries from the `recentchanges` table
2222 if ( mt_rand( 0, 9 ) == 0 ) {
2223 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2227 if ( !$this->exists() ) {
2231 $id = $this->getId();
2232 $title = $this->mTitle
->getPrefixedDBkey();
2233 $shortTitle = $this->mTitle
->getDBkey();
2235 if ( $options['oldcountable'] === 'no-change' ||
2236 ( !$options['changed'] && !$options['moved'] )
2239 } elseif ( $options['created'] ) {
2240 $good = (int)$this->isCountable( $editInfo );
2241 } elseif ( $options['oldcountable'] !== null ) {
2242 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2246 $edits = $options['changed'] ?
1 : 0;
2247 $total = $options['created'] ?
1 : 0;
2249 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2250 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2252 // If this is another user's talk page, update newtalk.
2253 // Don't do this if $options['changed'] = false (null-edits) nor if
2254 // it's a minor edit and the user doesn't want notifications for those.
2255 if ( $options['changed']
2256 && $this->mTitle
->getNamespace() == NS_USER_TALK
2257 && $shortTitle != $user->getTitleKey()
2258 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2260 $recipient = User
::newFromName( $shortTitle, false );
2261 if ( !$recipient ) {
2262 wfDebug( __METHOD__
. ": invalid username\n" );
2264 // Avoid PHP 7.1 warning of passing $this by reference
2267 // Allow extensions to prevent user notification
2268 // when a new message is added to their talk page
2269 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2270 if ( User
::isIP( $shortTitle ) ) {
2271 // An anonymous user
2272 $recipient->setNewtalk( true, $revision );
2273 } elseif ( $recipient->isLoggedIn() ) {
2274 $recipient->setNewtalk( true, $revision );
2276 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2282 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2283 MessageCache
::singleton()->updateMessageOverride( $this->mTitle
, $content );
2286 if ( $options['created'] ) {
2287 self
::onArticleCreate( $this->mTitle
);
2288 } elseif ( $options['changed'] ) { // T52785
2289 self
::onArticleEdit( $this->mTitle
, $revision );
2292 ResourceLoaderWikiModule
::invalidateModuleCache(
2293 $this->mTitle
, $options['oldrevision'], $revision, wfWikiID()
2298 * Update the article's restriction field, and leave a log entry.
2299 * This works for protection both existing and non-existing pages.
2301 * @param array $limit Set of restriction keys
2302 * @param array $expiry Per restriction type expiration
2303 * @param int &$cascade Set to false if cascading protection isn't allowed.
2304 * @param string $reason
2305 * @param User $user The user updating the restrictions
2306 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2307 * ($user should be able to add the specified tags before this is called)
2308 * @return Status Status object; if action is taken, $status->value is the log_id of the
2309 * protection log entry.
2311 public function doUpdateRestrictions( array $limit, array $expiry,
2312 &$cascade, $reason, User
$user, $tags = null
2314 global $wgCascadingRestrictionLevels, $wgContLang;
2316 if ( wfReadOnly() ) {
2317 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2320 $this->loadPageData( 'fromdbmaster' );
2321 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2322 $id = $this->getId();
2328 // Take this opportunity to purge out expired restrictions
2329 Title
::purgeExpiredRestrictions();
2331 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2332 // we expect a single selection, but the schema allows otherwise.
2333 $isProtected = false;
2337 $dbw = wfGetDB( DB_MASTER
);
2339 foreach ( $restrictionTypes as $action ) {
2340 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2341 $expiry[$action] = 'infinity';
2343 if ( !isset( $limit[$action] ) ) {
2344 $limit[$action] = '';
2345 } elseif ( $limit[$action] != '' ) {
2349 // Get current restrictions on $action
2350 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2351 if ( $current != '' ) {
2352 $isProtected = true;
2355 if ( $limit[$action] != $current ) {
2357 } elseif ( $limit[$action] != '' ) {
2358 // Only check expiry change if the action is actually being
2359 // protected, since expiry does nothing on an not-protected
2361 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2367 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2371 // If nothing has changed, do nothing
2373 return Status
::newGood();
2376 if ( !$protect ) { // No protection at all means unprotection
2377 $revCommentMsg = 'unprotectedarticle-comment';
2378 $logAction = 'unprotect';
2379 } elseif ( $isProtected ) {
2380 $revCommentMsg = 'modifiedarticleprotection-comment';
2381 $logAction = 'modify';
2383 $revCommentMsg = 'protectedarticle-comment';
2384 $logAction = 'protect';
2387 // Truncate for whole multibyte characters
2388 $reason = $wgContLang->truncate( $reason, 255 );
2390 $logRelationsValues = [];
2391 $logRelationsField = null;
2392 $logParamsDetails = [];
2394 // Null revision (used for change tag insertion)
2395 $nullRevision = null;
2397 if ( $id ) { // Protection of existing page
2398 // Avoid PHP 7.1 warning of passing $this by reference
2401 if ( !Hooks
::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2402 return Status
::newGood();
2405 // Only certain restrictions can cascade...
2406 $editrestriction = isset( $limit['edit'] )
2407 ?
[ $limit['edit'] ]
2408 : $this->mTitle
->getRestrictions( 'edit' );
2409 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2410 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2412 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2413 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2416 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2417 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2418 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2420 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2421 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2424 // The schema allows multiple restrictions
2425 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2429 // insert null revision to identify the page protection change as edit summary
2430 $latest = $this->getLatest();
2431 $nullRevision = $this->insertProtectNullRevision(
2440 if ( $nullRevision === null ) {
2441 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2444 $logRelationsField = 'pr_id';
2446 // Update restrictions table
2447 foreach ( $limit as $action => $restrictions ) {
2449 'page_restrictions',
2452 'pr_type' => $action
2456 if ( $restrictions != '' ) {
2457 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2459 'page_restrictions',
2461 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2463 'pr_type' => $action,
2464 'pr_level' => $restrictions,
2465 'pr_cascade' => $cascadeValue,
2466 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2470 $logRelationsValues[] = $dbw->insertId();
2471 $logParamsDetails[] = [
2473 'level' => $restrictions,
2474 'expiry' => $expiry[$action],
2475 'cascade' => (bool)$cascadeValue,
2480 // Clear out legacy restriction fields
2483 [ 'page_restrictions' => '' ],
2484 [ 'page_id' => $id ],
2488 // Avoid PHP 7.1 warning of passing $this by reference
2491 Hooks
::run( 'NewRevisionFromEditComplete',
2492 [ $this, $nullRevision, $latest, $user ] );
2493 Hooks
::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2494 } else { // Protection of non-existing page (also known as "title protection")
2495 // Cascade protection is meaningless in this case
2498 if ( $limit['create'] != '' ) {
2499 $dbw->replace( 'protected_titles',
2500 [ [ 'pt_namespace', 'pt_title' ] ],
2502 'pt_namespace' => $this->mTitle
->getNamespace(),
2503 'pt_title' => $this->mTitle
->getDBkey(),
2504 'pt_create_perm' => $limit['create'],
2505 'pt_timestamp' => $dbw->timestamp(),
2506 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2507 'pt_user' => $user->getId(),
2508 'pt_reason' => $reason,
2511 $logParamsDetails[] = [
2513 'level' => $limit['create'],
2514 'expiry' => $expiry['create'],
2517 $dbw->delete( 'protected_titles',
2519 'pt_namespace' => $this->mTitle
->getNamespace(),
2520 'pt_title' => $this->mTitle
->getDBkey()
2526 $this->mTitle
->flushRestrictions();
2527 InfoAction
::invalidateCache( $this->mTitle
);
2529 if ( $logAction == 'unprotect' ) {
2532 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2534 '4::description' => $protectDescriptionLog, // parameter for IRC
2535 '5:bool:cascade' => $cascade,
2536 'details' => $logParamsDetails, // parameter for localize and api
2540 // Update the protection log
2541 $logEntry = new ManualLogEntry( 'protect', $logAction );
2542 $logEntry->setTarget( $this->mTitle
);
2543 $logEntry->setComment( $reason );
2544 $logEntry->setPerformer( $user );
2545 $logEntry->setParameters( $params );
2546 if ( !is_null( $nullRevision ) ) {
2547 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2549 $logEntry->setTags( $tags );
2550 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2551 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2553 $logId = $logEntry->insert();
2554 $logEntry->publish( $logId );
2556 return Status
::newGood( $logId );
2560 * Insert a new null revision for this page.
2562 * @param string $revCommentMsg Comment message key for the revision
2563 * @param array $limit Set of restriction keys
2564 * @param array $expiry Per restriction type expiration
2565 * @param int $cascade Set to false if cascading protection isn't allowed.
2566 * @param string $reason
2567 * @param User|null $user
2568 * @return Revision|null Null on error
2570 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2571 array $expiry, $cascade, $reason, $user = null
2573 $dbw = wfGetDB( DB_MASTER
);
2575 // Prepare a null revision to be added to the history
2576 $editComment = wfMessage(
2578 $this->mTitle
->getPrefixedText(),
2579 $user ?
$user->getName() : ''
2580 )->inContentLanguage()->text();
2582 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2584 $protectDescription = $this->protectDescription( $limit, $expiry );
2585 if ( $protectDescription ) {
2586 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2587 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2588 ->inContentLanguage()->text();
2591 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2592 $editComment .= wfMessage( 'brackets' )->params(
2593 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2594 )->inContentLanguage()->text();
2597 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2599 $nullRev->insertOn( $dbw );
2601 // Update page record and touch page
2602 $oldLatest = $nullRev->getParentId();
2603 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2610 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2613 protected function formatExpiry( $expiry ) {
2616 if ( $expiry != 'infinity' ) {
2619 $wgContLang->timeanddate( $expiry, false, false ),
2620 $wgContLang->date( $expiry, false, false ),
2621 $wgContLang->time( $expiry, false, false )
2622 )->inContentLanguage()->text();
2624 return wfMessage( 'protect-expiry-indefinite' )
2625 ->inContentLanguage()->text();
2630 * Builds the description to serve as comment for the edit.
2632 * @param array $limit Set of restriction keys
2633 * @param array $expiry Per restriction type expiration
2636 public function protectDescription( array $limit, array $expiry ) {
2637 $protectDescription = '';
2639 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2640 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2641 # All possible message keys are listed here for easier grepping:
2642 # * restriction-create
2643 # * restriction-edit
2644 # * restriction-move
2645 # * restriction-upload
2646 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2647 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2648 # with '' filtered out. All possible message keys are listed below:
2649 # * protect-level-autoconfirmed
2650 # * protect-level-sysop
2651 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2652 ->inContentLanguage()->text();
2654 $expiryText = $this->formatExpiry( $expiry[$action] );
2656 if ( $protectDescription !== '' ) {
2657 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2659 $protectDescription .= wfMessage( 'protect-summary-desc' )
2660 ->params( $actionText, $restrictionsText, $expiryText )
2661 ->inContentLanguage()->text();
2664 return $protectDescription;
2668 * Builds the description to serve as comment for the log entry.
2670 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2671 * protect description text. Keep them in old format to avoid breaking compatibility.
2672 * TODO: Fix protection log to store structured description and format it on-the-fly.
2674 * @param array $limit Set of restriction keys
2675 * @param array $expiry Per restriction type expiration
2678 public function protectDescriptionLog( array $limit, array $expiry ) {
2681 $protectDescriptionLog = '';
2683 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2684 $expiryText = $this->formatExpiry( $expiry[$action] );
2685 $protectDescriptionLog .= $wgContLang->getDirMark() .
2686 "[$action=$restrictions] ($expiryText)";
2689 return trim( $protectDescriptionLog );
2693 * Take an array of page restrictions and flatten it to a string
2694 * suitable for insertion into the page_restrictions field.
2696 * @param string[] $limit
2698 * @throws MWException
2701 protected static function flattenRestrictions( $limit ) {
2702 if ( !is_array( $limit ) ) {
2703 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2709 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2710 $bits[] = "$action=$restrictions";
2713 return implode( ':', $bits );
2717 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2718 * backwards compatibility, if you care about error reporting you should use
2719 * doDeleteArticleReal() instead.
2721 * Deletes the article with database consistency, writes logs, purges caches
2723 * @param string $reason Delete reason for deletion log
2724 * @param bool $suppress Suppress all revisions and log the deletion in
2725 * the suppression log instead of the deletion log
2726 * @param int $u1 Unused
2727 * @param bool $u2 Unused
2728 * @param array|string &$error Array of errors to append to
2729 * @param User $user The deleting user
2730 * @return bool True if successful
2732 public function doDeleteArticle(
2733 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2735 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2736 return $status->isGood();
2740 * Back-end article deletion
2741 * Deletes the article with database consistency, writes logs, purges caches
2745 * @param string $reason Delete reason for deletion log
2746 * @param bool $suppress Suppress all revisions and log the deletion in
2747 * the suppression log instead of the deletion log
2748 * @param int $u1 Unused
2749 * @param bool $u2 Unused
2750 * @param array|string &$error Array of errors to append to
2751 * @param User $user The deleting user
2752 * @param array $tags Tags to apply to the deletion action
2753 * @return Status Status object; if successful, $status->value is the log_id of the
2754 * deletion log entry. If the page couldn't be deleted because it wasn't
2755 * found, $status is a non-fatal 'cannotdelete' error
2757 public function doDeleteArticleReal(
2758 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null,
2759 $tags = [], $logsubtype = 'delete'
2761 global $wgUser, $wgContentHandlerUseDB;
2763 wfDebug( __METHOD__
. "\n" );
2765 $status = Status
::newGood();
2767 if ( $this->mTitle
->getDBkey() === '' ) {
2768 $status->error( 'cannotdelete',
2769 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2773 // Avoid PHP 7.1 warning of passing $this by reference
2776 $user = is_null( $user ) ?
$wgUser : $user;
2777 if ( !Hooks
::run( 'ArticleDelete',
2778 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2780 if ( $status->isOK() ) {
2781 // Hook aborted but didn't set a fatal status
2782 $status->fatal( 'delete-hook-aborted' );
2787 $dbw = wfGetDB( DB_MASTER
);
2788 $dbw->startAtomic( __METHOD__
);
2790 $this->loadPageData( self
::READ_LATEST
);
2791 $id = $this->getId();
2792 // T98706: lock the page from various other updates but avoid using
2793 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2794 // the revisions queries (which also JOIN on user). Only lock the page
2795 // row and CAS check on page_latest to see if the trx snapshot matches.
2796 $lockedLatest = $this->lockAndGetLatest();
2797 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2798 $dbw->endAtomic( __METHOD__
);
2799 // Page not there or trx snapshot is stale
2800 $status->error( 'cannotdelete',
2801 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2805 // Given the lock above, we can be confident in the title and page ID values
2806 $namespace = $this->getTitle()->getNamespace();
2807 $dbKey = $this->getTitle()->getDBkey();
2809 // At this point we are now comitted to returning an OK
2810 // status unless some DB query error or other exception comes up.
2811 // This way callers don't have to call rollback() if $status is bad
2812 // unless they actually try to catch exceptions (which is rare).
2814 // we need to remember the old content so we can use it to generate all deletion updates.
2815 $revision = $this->getRevision();
2817 $content = $this->getContent( Revision
::RAW
);
2818 } catch ( Exception
$ex ) {
2819 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2820 . $ex->getMessage() );
2825 $fields = Revision
::selectFields();
2828 // Bitfields to further suppress the content
2830 $bitfield = Revision
::SUPPRESSED_ALL
;
2831 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2834 // For now, shunt the revision data into the archive table.
2835 // Text is *not* removed from the text table; bulk storage
2836 // is left intact to avoid breaking block-compression or
2837 // immutable storage schemes.
2838 // In the future, we may keep revisions and mark them with
2839 // the rev_deleted field, which is reserved for this purpose.
2841 // Get all of the page revisions
2842 $res = $dbw->select(
2845 [ 'rev_page' => $id ],
2849 // Build their equivalent archive rows
2851 foreach ( $res as $row ) {
2853 'ar_namespace' => $namespace,
2854 'ar_title' => $dbKey,
2855 'ar_comment' => $row->rev_comment
,
2856 'ar_user' => $row->rev_user
,
2857 'ar_user_text' => $row->rev_user_text
,
2858 'ar_timestamp' => $row->rev_timestamp
,
2859 'ar_minor_edit' => $row->rev_minor_edit
,
2860 'ar_rev_id' => $row->rev_id
,
2861 'ar_parent_id' => $row->rev_parent_id
,
2862 'ar_text_id' => $row->rev_text_id
,
2865 'ar_len' => $row->rev_len
,
2866 'ar_page_id' => $id,
2867 'ar_deleted' => $suppress ?
$bitfield : $row->rev_deleted
,
2868 'ar_sha1' => $row->rev_sha1
,
2870 if ( $wgContentHandlerUseDB ) {
2871 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2872 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2874 $rowsInsert[] = $rowInsert;
2876 // Copy them into the archive table
2877 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2878 // Save this so we can pass it to the ArticleDeleteComplete hook.
2879 $archivedRevisionCount = $dbw->affectedRows();
2881 // Clone the title and wikiPage, so we have the information we need when
2882 // we log and run the ArticleDeleteComplete hook.
2883 $logTitle = clone $this->mTitle
;
2884 $wikiPageBeforeDelete = clone $this;
2886 // Now that it's safely backed up, delete it
2887 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2888 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2890 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2891 $logtype = $suppress ?
'suppress' : 'delete';
2893 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2894 $logEntry->setPerformer( $user );
2895 $logEntry->setTarget( $logTitle );
2896 $logEntry->setComment( $reason );
2897 $logEntry->setTags( $tags );
2898 $logid = $logEntry->insert();
2900 $dbw->onTransactionPreCommitOrIdle(
2901 function () use ( $dbw, $logEntry, $logid ) {
2902 // T58776: avoid deadlocks (especially from FileDeleteForm)
2903 $logEntry->publish( $logid );
2908 $dbw->endAtomic( __METHOD__
);
2910 $this->doDeleteUpdates( $id, $content, $revision );
2912 Hooks
::run( 'ArticleDeleteComplete', [
2913 &$wikiPageBeforeDelete,
2919 $archivedRevisionCount
2921 $status->value
= $logid;
2923 // Show log excerpt on 404 pages rather than just a link
2924 $cache = ObjectCache
::getMainStashInstance();
2925 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2926 $cache->set( $key, 1, $cache::TTL_DAY
);
2932 * Lock the page row for this title+id and return page_latest (or 0)
2934 * @return integer Returns 0 if no row was found with this title+id
2937 public function lockAndGetLatest() {
2938 return (int)wfGetDB( DB_MASTER
)->selectField(
2942 'page_id' => $this->getId(),
2943 // Typically page_id is enough, but some code might try to do
2944 // updates assuming the title is the same, so verify that
2945 'page_namespace' => $this->getTitle()->getNamespace(),
2946 'page_title' => $this->getTitle()->getDBkey()
2954 * Do some database updates after deletion
2956 * @param int $id The page_id value of the page being deleted
2957 * @param Content|null $content Optional page content to be used when determining
2958 * the required updates. This may be needed because $this->getContent()
2959 * may already return null when the page proper was deleted.
2960 * @param Revision|null $revision The latest page revision
2962 public function doDeleteUpdates( $id, Content
$content = null, Revision
$revision = null ) {
2964 $countable = $this->isCountable();
2965 } catch ( Exception
$ex ) {
2966 // fallback for deleting broken pages for which we cannot load the content for
2967 // some reason. Note that doDeleteArticleReal() already logged this problem.
2971 // Update site status
2972 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
2974 // Delete pagelinks, update secondary indexes, etc
2975 $updates = $this->getDeletionUpdates( $content );
2976 foreach ( $updates as $update ) {
2977 DeferredUpdates
::addUpdate( $update );
2980 // Reparse any pages transcluding this page
2981 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2983 // Reparse any pages including this image
2984 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2985 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2989 WikiPage
::onArticleDelete( $this->mTitle
);
2990 ResourceLoaderWikiModule
::invalidateModuleCache(
2991 $this->mTitle
, $revision, null, wfWikiID()
2994 // Reset this object and the Title object
2995 $this->loadFromRow( false, self
::READ_LATEST
);
2998 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3002 * Roll back the most recent consecutive set of edits to a page
3003 * from the same user; fails if there are no eligible edits to
3004 * roll back to, e.g. user is the sole contributor. This function
3005 * performs permissions checks on $user, then calls commitRollback()
3006 * to do the dirty work
3008 * @todo Separate the business/permission stuff out from backend code
3009 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3011 * @param string $fromP Name of the user whose edits to rollback.
3012 * @param string $summary Custom summary. Set to default summary if empty.
3013 * @param string $token Rollback token.
3014 * @param bool $bot If true, mark all reverted edits as bot.
3016 * @param array $resultDetails Array contains result-specific array of additional values
3017 * 'alreadyrolled' : 'current' (rev)
3018 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3020 * @param User $user The user performing the rollback
3021 * @param array|null $tags Change tags to apply to the rollback
3022 * Callers are responsible for permission checks
3023 * (with ChangeTags::canAddTagsAccompanyingChange)
3025 * @return array Array of errors, each error formatted as
3026 * array(messagekey, param1, param2, ...).
3027 * On success, the array is empty. This array can also be passed to
3028 * OutputPage::showPermissionsErrorPage().
3030 public function doRollback(
3031 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3033 $resultDetails = null;
3035 // Check permissions
3036 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3037 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3038 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3040 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3041 $errors[] = [ 'sessionfailure' ];
3044 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3045 $errors[] = [ 'actionthrottledtext' ];
3048 // If there were errors, bail out now
3049 if ( !empty( $errors ) ) {
3053 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3057 * Backend implementation of doRollback(), please refer there for parameter
3058 * and return value documentation
3060 * NOTE: This function does NOT check ANY permissions, it just commits the
3061 * rollback to the DB. Therefore, you should only call this function direct-
3062 * ly if you want to use custom permissions checks. If you don't, use
3063 * doRollback() instead.
3064 * @param string $fromP Name of the user whose edits to rollback.
3065 * @param string $summary Custom summary. Set to default summary if empty.
3066 * @param bool $bot If true, mark all reverted edits as bot.
3068 * @param array $resultDetails Contains result-specific array of additional values
3069 * @param User $guser The user performing the rollback
3070 * @param array|null $tags Change tags to apply to the rollback
3071 * Callers are responsible for permission checks
3072 * (with ChangeTags::canAddTagsAccompanyingChange)
3076 public function commitRollback( $fromP, $summary, $bot,
3077 &$resultDetails, User
$guser, $tags = null
3079 global $wgUseRCPatrol, $wgContLang;
3081 $dbw = wfGetDB( DB_MASTER
);
3083 if ( wfReadOnly() ) {
3084 return [ [ 'readonlytext' ] ];
3087 // Get the last editor
3088 $current = $this->getRevision();
3089 if ( is_null( $current ) ) {
3090 // Something wrong... no page?
3091 return [ [ 'notanarticle' ] ];
3094 $from = str_replace( '_', ' ', $fromP );
3095 // User name given should match up with the top revision.
3096 // If the user was deleted then $from should be empty.
3097 if ( $from != $current->getUserText() ) {
3098 $resultDetails = [ 'current' => $current ];
3099 return [ [ 'alreadyrolled',
3100 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3101 htmlspecialchars( $fromP ),
3102 htmlspecialchars( $current->getUserText() )
3106 // Get the last edit not by this person...
3107 // Note: these may not be public values
3108 $user = intval( $current->getUser( Revision
::RAW
) );
3109 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3110 $s = $dbw->selectRow( 'revision',
3111 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3112 [ 'rev_page' => $current->getPage(),
3113 "rev_user != {$user} OR rev_user_text != {$user_text}"
3115 [ 'USE INDEX' => 'page_timestamp',
3116 'ORDER BY' => 'rev_timestamp DESC' ]
3118 if ( $s === false ) {
3119 // No one else ever edited this page
3120 return [ [ 'cantrollback' ] ];
3121 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3122 ||
$s->rev_deleted
& Revision
::DELETED_USER
3124 // Only admins can see this text
3125 return [ [ 'notvisiblerev' ] ];
3128 // Generate the edit summary if necessary
3129 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3130 if ( empty( $summary ) ) {
3131 if ( $from == '' ) { // no public user name
3132 $summary = wfMessage( 'revertpage-nouser' );
3134 $summary = wfMessage( 'revertpage' );
3138 // Allow the custom summary to use the same args as the default message
3140 $target->getUserText(), $from, $s->rev_id
,
3141 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3142 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3144 if ( $summary instanceof Message
) {
3145 $summary = $summary->params( $args )->inContentLanguage()->text();
3147 $summary = wfMsgReplaceArgs( $summary, $args );
3150 // Trim spaces on user supplied text
3151 $summary = trim( $summary );
3153 // Truncate for whole multibyte characters.
3154 $summary = $wgContLang->truncate( $summary, 255 );
3157 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3159 if ( $guser->isAllowed( 'minoredit' ) ) {
3160 $flags |
= EDIT_MINOR
;
3163 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3164 $flags |
= EDIT_FORCE_BOT
;
3167 $targetContent = $target->getContent();
3168 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3170 // Actually store the edit
3171 $status = $this->doEditContent(
3181 // Set patrolling and bot flag on the edits, which gets rollbacked.
3182 // This is done even on edit failure to have patrolling in that case (T64157).
3184 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3185 // Mark all reverted edits as bot
3189 if ( $wgUseRCPatrol ) {
3190 // Mark all reverted edits as patrolled
3191 $set['rc_patrolled'] = 1;
3194 if ( count( $set ) ) {
3195 $dbw->update( 'recentchanges', $set,
3197 'rc_cur_id' => $current->getPage(),
3198 'rc_user_text' => $current->getUserText(),
3199 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3205 if ( !$status->isOK() ) {
3206 return $status->getErrorsArray();
3209 // raise error, when the edit is an edit without a new version
3210 $statusRev = isset( $status->value
['revision'] )
3211 ?
$status->value
['revision']
3213 if ( !( $statusRev instanceof Revision
) ) {
3214 $resultDetails = [ 'current' => $current ];
3215 return [ [ 'alreadyrolled',
3216 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3217 htmlspecialchars( $fromP ),
3218 htmlspecialchars( $current->getUserText() )
3222 if ( $changingContentModel ) {
3223 // If the content model changed during the rollback,
3224 // make sure it gets logged to Special:Log/contentmodel
3225 $log = new ManualLogEntry( 'contentmodel', 'change' );
3226 $log->setPerformer( $guser );
3227 $log->setTarget( $this->mTitle
);
3228 $log->setComment( $summary );
3229 $log->setParameters( [
3230 '4::oldmodel' => $current->getContentModel(),
3231 '5::newmodel' => $targetContent->getModel(),
3234 $logId = $log->insert( $dbw );
3235 $log->publish( $logId );
3238 $revId = $statusRev->getId();
3240 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3243 'summary' => $summary,
3244 'current' => $current,
3245 'target' => $target,
3253 * The onArticle*() functions are supposed to be a kind of hooks
3254 * which should be called whenever any of the specified actions
3257 * This is a good place to put code to clear caches, for instance.
3259 * This is called on page move and undelete, as well as edit
3261 * @param Title $title
3263 public static function onArticleCreate( Title
$title ) {
3264 // Update existence markers on article/talk tabs...
3265 $other = $title->getOtherPage();
3267 $other->purgeSquid();
3269 $title->touchLinks();
3270 $title->purgeSquid();
3271 $title->deleteTitleProtection();
3273 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3275 if ( $title->getNamespace() == NS_CATEGORY
) {
3276 // Load the Category object, which will schedule a job to create
3277 // the category table row if necessary. Checking a replica DB is ok
3278 // here, in the worst case it'll run an unnecessary recount job on
3279 // a category that probably doesn't have many members.
3280 Category
::newFromTitle( $title )->getID();
3285 * Clears caches when article is deleted
3287 * @param Title $title
3289 public static function onArticleDelete( Title
$title ) {
3290 // Update existence markers on article/talk tabs...
3291 $other = $title->getOtherPage();
3293 $other->purgeSquid();
3295 $title->touchLinks();
3296 $title->purgeSquid();
3298 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3301 HTMLFileCache
::clearFileCache( $title );
3302 InfoAction
::invalidateCache( $title );
3305 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3306 MessageCache
::singleton()->updateMessageOverride( $title, null );
3310 if ( $title->getNamespace() == NS_FILE
) {
3311 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3315 if ( $title->getNamespace() == NS_USER_TALK
) {
3316 $user = User
::newFromName( $title->getText(), false );
3318 $user->setNewtalk( false );
3323 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3327 * Purge caches on page update etc
3329 * @param Title $title
3330 * @param Revision|null $revision Revision that was just saved, may be null
3332 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3333 // Invalidate caches of articles which include this page
3334 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3336 // Invalidate the caches of all pages which redirect here
3337 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3339 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3341 // Purge CDN for this page only
3342 $title->purgeSquid();
3343 // Clear file cache for this page only
3344 HTMLFileCache
::clearFileCache( $title );
3346 $revid = $revision ?
$revision->getId() : null;
3347 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3348 InfoAction
::invalidateCache( $title, $revid );
3355 * Returns a list of categories this page is a member of.
3356 * Results will include hidden categories
3358 * @return TitleArray
3360 public function getCategories() {
3361 $id = $this->getId();
3363 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3366 $dbr = wfGetDB( DB_REPLICA
);
3367 $res = $dbr->select( 'categorylinks',
3368 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3369 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3370 // as not being aliases, and NS_CATEGORY is numeric
3371 [ 'cl_from' => $id ],
3374 return TitleArray
::newFromResult( $res );
3378 * Returns a list of hidden categories this page is a member of.
3379 * Uses the page_props and categorylinks tables.
3381 * @return array Array of Title objects
3383 public function getHiddenCategories() {
3385 $id = $this->getId();
3391 $dbr = wfGetDB( DB_REPLICA
);
3392 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3394 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3395 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3398 if ( $res !== false ) {
3399 foreach ( $res as $row ) {
3400 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3408 * Auto-generates a deletion reason
3410 * @param bool &$hasHistory Whether the page has a history
3411 * @return string|bool String containing deletion reason or empty string, or boolean false
3412 * if no revision occurred
3414 public function getAutoDeleteReason( &$hasHistory ) {
3415 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3419 * Update all the appropriate counts in the category table, given that
3420 * we've added the categories $added and deleted the categories $deleted.
3422 * This should only be called from deferred updates or jobs to avoid contention.
3424 * @param array $added The names of categories that were added
3425 * @param array $deleted The names of categories that were deleted
3426 * @param integer $id Page ID (this should be the original deleted page ID)
3428 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3429 $id = $id ?
: $this->getId();
3430 $ns = $this->getTitle()->getNamespace();
3432 $addFields = [ 'cat_pages = cat_pages + 1' ];
3433 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3434 if ( $ns == NS_CATEGORY
) {
3435 $addFields[] = 'cat_subcats = cat_subcats + 1';
3436 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3437 } elseif ( $ns == NS_FILE
) {
3438 $addFields[] = 'cat_files = cat_files + 1';
3439 $removeFields[] = 'cat_files = cat_files - 1';
3442 $dbw = wfGetDB( DB_MASTER
);
3444 if ( count( $added ) ) {
3445 $existingAdded = $dbw->selectFieldValues(
3448 [ 'cat_title' => $added ],
3452 // For category rows that already exist, do a plain
3453 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3454 // to avoid creating gaps in the cat_id sequence.
3455 if ( count( $existingAdded ) ) {
3459 [ 'cat_title' => $existingAdded ],
3464 $missingAdded = array_diff( $added, $existingAdded );
3465 if ( count( $missingAdded ) ) {
3467 foreach ( $missingAdded as $cat ) {
3469 'cat_title' => $cat,
3471 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3472 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3485 if ( count( $deleted ) ) {
3489 [ 'cat_title' => $deleted ],
3494 foreach ( $added as $catName ) {
3495 $cat = Category
::newFromName( $catName );
3496 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3499 foreach ( $deleted as $catName ) {
3500 $cat = Category
::newFromName( $catName );
3501 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3504 // Refresh counts on categories that should be empty now, to
3505 // trigger possible deletion. Check master for the most
3506 // up-to-date cat_pages.
3507 if ( count( $deleted ) ) {
3508 $rows = $dbw->select(
3510 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3511 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3514 foreach ( $rows as $row ) {
3515 $cat = Category
::newFromRow( $row );
3516 $cat->refreshCounts();
3522 * Opportunistically enqueue link update jobs given fresh parser output if useful
3524 * @param ParserOutput $parserOutput Current version page output
3527 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3528 if ( wfReadOnly() ) {
3532 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3533 [ $this, $this->mTitle
, $parserOutput ]
3538 $config = RequestContext
::getMain()->getConfig();
3541 'isOpportunistic' => true,
3542 'rootJobTimestamp' => $parserOutput->getCacheTime()
3545 if ( $this->mTitle
->areRestrictionsCascading() ) {
3546 // If the page is cascade protecting, the links should really be up-to-date
3547 JobQueueGroup
::singleton()->lazyPush(
3548 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3550 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3551 // Assume the output contains "dynamic" time/random based magic words.
3552 // Only update pages that expired due to dynamic content and NOT due to edits
3553 // to referenced templates/files. When the cache expires due to dynamic content,
3554 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3555 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3556 // template/file edit already triggered recursive RefreshLinksJob jobs.
3557 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3558 // If a page is uncacheable, do not keep spamming a job for it.
3559 // Although it would be de-duplicated, it would still waste I/O.
3560 $cache = ObjectCache
::getLocalClusterInstance();
3561 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3562 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3563 if ( $cache->add( $key, time(), $ttl ) ) {
3564 JobQueueGroup
::singleton()->lazyPush(
3565 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3573 * Returns a list of updates to be performed when this page is deleted. The
3574 * updates should remove any information about this page from secondary data
3575 * stores such as links tables.
3577 * @param Content|null $content Optional Content object for determining the
3578 * necessary updates.
3579 * @return DeferrableUpdate[]
3581 public function getDeletionUpdates( Content
$content = null ) {
3583 // load content object, which may be used to determine the necessary updates.
3584 // XXX: the content may not be needed to determine the updates.
3586 $content = $this->getContent( Revision
::RAW
);
3587 } catch ( Exception
$ex ) {
3588 // If we can't load the content, something is wrong. Perhaps that's why
3589 // the user is trying to delete the page, so let's not fail in that case.
3590 // Note that doDeleteArticleReal() will already have logged an issue with
3591 // loading the content.
3598 $updates = $content->getDeletionUpdates( $this );
3601 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3606 * Whether this content displayed on this page
3607 * comes from the local database
3612 public function isLocal() {
3617 * The display name for the site this content
3618 * come from. If a subclass overrides isLocal(),
3619 * this could return something other than the
3625 public function getWikiDisplayName() {
3631 * Get the source URL for the content on this page,
3632 * typically the canonical URL, but may be a remote
3633 * link if the content comes from another site
3638 public function getSourceURL() {
3639 return $this->getTitle()->getCanonicalURL();
3643 * @param WANObjectCache $cache
3647 public function getMutableCacheKeys( WANObjectCache
$cache ) {
3648 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3650 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle()->getTitleValue() );