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
;
27 * Class representing a MediaWiki article and history.
29 * Some fields are public only for backwards-compatibility. Use accessors.
30 * In the past, this class was part of Article.php and everything was public.
32 class WikiPage
implements Page
, IDBAccessObject
{
33 // Constants for $mDataLoadedFrom and related
38 public $mTitle = null;
43 public $mDataLoaded = false; // !< Boolean
44 public $mIsRedirect = false; // !< Boolean
45 public $mLatest = false; // !< Integer (false means "not loaded")
48 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
49 public $mPreparedEdit = false;
54 protected $mId = null;
57 * @var int One of the READ_* constants
59 protected $mDataLoadedFrom = self
::READ_NONE
;
64 protected $mRedirectTarget = null;
69 protected $mLastRevision = null;
72 * @var string Timestamp of the current revision or empty string if not loaded
74 protected $mTimestamp = '';
79 protected $mTouched = '19700101000000';
84 protected $mLinksUpdated = '19700101000000';
86 const PURGE_CDN_CACHE
= 1; // purge CDN cache for page variant URLs
87 const PURGE_CLUSTER_PCACHE
= 2; // purge parser cache in the local datacenter
88 const PURGE_GLOBAL_PCACHE
= 4; // set page_touched to clear parser cache in all datacenters
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title
$title ) {
96 $this->mTitle
= $title;
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
103 public function __clone() {
104 $this->mTitle
= clone $this->mTitle
;
108 * Create a WikiPage object of the appropriate class for the given title.
110 * @param Title $title
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
115 public static function factory( Title
$title ) {
116 $ns = $title->getNamespace();
118 if ( $ns == NS_MEDIA
) {
119 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
120 } elseif ( $ns < 0 ) {
121 throw new MWException( "Invalid or virtual namespace $ns given." );
126 $page = new WikiFilePage( $title );
129 $page = new WikiCategoryPage( $title );
132 $page = new WikiPage( $title );
139 * Constructor from a page id
141 * @param int $id Article ID to load
142 * @param string|int $from One of the following values:
143 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
144 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
146 * @return WikiPage|null
148 public static function newFromID( $id, $from = 'fromdb' ) {
149 // page id's are never 0 or negative, see bug 61166
154 $from = self
::convertSelectType( $from );
155 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
156 $row = $db->selectRow(
157 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
161 return self
::newFromRow( $row, $from );
165 * Constructor from a database row
168 * @param object $row Database row containing at least fields returned by selectFields().
169 * @param string|int $from Source of $data:
170 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
171 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
172 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
175 public static function newFromRow( $row, $from = 'fromdb' ) {
176 $page = self
::factory( Title
::newFromRow( $row ) );
177 $page->loadFromRow( $row, $from );
182 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
184 * @param object|string|int $type
187 private static function convertSelectType( $type ) {
190 return self
::READ_NORMAL
;
192 return self
::READ_LATEST
;
194 return self
::READ_LOCKING
;
196 // It may already be an integer or whatever else
202 * @todo Move this UI stuff somewhere else
204 * @see ContentHandler::getActionOverrides
206 public function getActionOverrides() {
207 return $this->getContentHandler()->getActionOverrides();
211 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
213 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
215 * @return ContentHandler
219 public function getContentHandler() {
220 return ContentHandler
::getForModelID( $this->getContentModel() );
224 * Get the title object of the article
225 * @return Title Title object of this page
227 public function getTitle() {
228 return $this->mTitle
;
235 public function clear() {
236 $this->mDataLoaded
= false;
237 $this->mDataLoadedFrom
= self
::READ_NONE
;
239 $this->clearCacheFields();
243 * Clear the object cache fields
246 protected function clearCacheFields() {
248 $this->mRedirectTarget
= null; // Title object if set
249 $this->mLastRevision
= null; // Latest revision
250 $this->mTouched
= '19700101000000';
251 $this->mLinksUpdated
= '19700101000000';
252 $this->mTimestamp
= '';
253 $this->mIsRedirect
= false;
254 $this->mLatest
= false;
255 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
256 // the requested rev ID and content against the cached one for equality. For most
257 // content types, the output should not change during the lifetime of this cache.
258 // Clearing it can cause extra parses on edit for no reason.
262 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
266 public function clearPreparedEdit() {
267 $this->mPreparedEdit
= false;
271 * Return the list of revision fields that should be selected to create
276 public static function selectFields() {
277 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
288 'page_links_updated',
293 if ( $wgContentHandlerUseDB ) {
294 $fields[] = 'page_content_model';
297 if ( $wgPageLanguageUseDB ) {
298 $fields[] = 'page_lang';
305 * Fetch a page record with the given conditions
306 * @param IDatabase $dbr
307 * @param array $conditions
308 * @param array $options
309 * @return object|bool Database result resource, or false on failure
311 protected function pageData( $dbr, $conditions, $options = [] ) {
312 $fields = self
::selectFields();
314 Hooks
::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
318 Hooks
::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
327 * @param IDatabase $dbr
328 * @param Title $title
329 * @param array $options
330 * @return object|bool Database result resource, or false on failure
332 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
333 return $this->pageData( $dbr, [
334 'page_namespace' => $title->getNamespace(),
335 'page_title' => $title->getDBkey() ], $options );
339 * Fetch a page record matching the requested ID
341 * @param IDatabase $dbr
343 * @param array $options
344 * @return object|bool Database result resource, or false on failure
346 public function pageDataFromId( $dbr, $id, $options = [] ) {
347 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
351 * Load the object from a given source by title
353 * @param object|string|int $from One of the following:
354 * - A DB query result object.
355 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
356 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
357 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
358 * using SELECT FOR UPDATE.
362 public function loadPageData( $from = 'fromdb' ) {
363 $from = self
::convertSelectType( $from );
364 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
365 // We already have the data from the correct location, no need to load it twice.
369 if ( is_int( $from ) ) {
370 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
371 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
374 && $index == DB_REPLICA
375 && wfGetLB()->getServerCount() > 1
376 && wfGetLB()->hasOrMadeRecentMasterChanges()
378 $from = self
::READ_LATEST
;
379 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
380 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
383 // No idea from where the caller got this data, assume replica DB.
385 $from = self
::READ_NORMAL
;
388 $this->loadFromRow( $data, $from );
392 * Load the object from a database row
395 * @param object|bool $data DB row containing fields returned by selectFields() or false
396 * @param string|int $from One of the following:
397 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
398 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
399 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
400 * the master DB using SELECT FOR UPDATE
402 public function loadFromRow( $data, $from ) {
403 $lc = LinkCache
::singleton();
404 $lc->clearLink( $this->mTitle
);
407 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
409 $this->mTitle
->loadFromRow( $data );
411 // Old-fashioned restrictions
412 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
414 $this->mId
= intval( $data->page_id
);
415 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
416 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
417 $this->mIsRedirect
= intval( $data->page_is_redirect
);
418 $this->mLatest
= intval( $data->page_latest
);
419 // Bug 37225: $latest may no longer match the cached latest Revision object.
420 // Double-check the ID of any cached latest Revision object for consistency.
421 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
422 $this->mLastRevision
= null;
423 $this->mTimestamp
= '';
426 $lc->addBadLinkObj( $this->mTitle
);
428 $this->mTitle
->loadFromRow( false );
430 $this->clearCacheFields();
435 $this->mDataLoaded
= true;
436 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
440 * @return int Page ID
442 public function getId() {
443 if ( !$this->mDataLoaded
) {
444 $this->loadPageData();
450 * @return bool Whether or not the page exists in the database
452 public function exists() {
453 if ( !$this->mDataLoaded
) {
454 $this->loadPageData();
456 return $this->mId
> 0;
460 * Check if this page is something we're going to be showing
461 * some sort of sensible content for. If we return false, page
462 * views (plain action=view) will return an HTTP 404 response,
463 * so spiders and robots can know they're following a bad link.
467 public function hasViewableContent() {
468 return $this->mTitle
->isKnown();
472 * Tests if the article content represents a redirect
476 public function isRedirect() {
477 if ( !$this->mDataLoaded
) {
478 $this->loadPageData();
481 return (bool)$this->mIsRedirect
;
485 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
487 * Will use the revisions actual content model if the page exists,
488 * and the page's default if the page doesn't exist yet.
494 public function getContentModel() {
495 if ( $this->exists() ) {
496 // look at the revision's actual content model
497 $rev = $this->getRevision();
499 if ( $rev !== null ) {
500 return $rev->getContentModel();
502 $title = $this->mTitle
->getPrefixedDBkey();
503 wfWarn( "Page $title exists but has no (visible) revisions!" );
507 // use the default model for this page
508 return $this->mTitle
->getContentModel();
512 * Loads page_touched and returns a value indicating if it should be used
513 * @return bool True if this page exists and is not a redirect
515 public function checkTouched() {
516 if ( !$this->mDataLoaded
) {
517 $this->loadPageData();
519 return ( $this->mId
&& !$this->mIsRedirect
);
523 * Get the page_touched field
524 * @return string Containing GMT timestamp
526 public function getTouched() {
527 if ( !$this->mDataLoaded
) {
528 $this->loadPageData();
530 return $this->mTouched
;
534 * Get the page_links_updated field
535 * @return string|null Containing GMT timestamp
537 public function getLinksTimestamp() {
538 if ( !$this->mDataLoaded
) {
539 $this->loadPageData();
541 return $this->mLinksUpdated
;
545 * Get the page_latest field
546 * @return int The rev_id of current revision
548 public function getLatest() {
549 if ( !$this->mDataLoaded
) {
550 $this->loadPageData();
552 return (int)$this->mLatest
;
556 * Get the Revision object of the oldest revision
557 * @return Revision|null
559 public function getOldestRevision() {
561 // Try using the replica DB first, then try the master
563 $db = wfGetDB( DB_REPLICA
);
564 $revSelectFields = Revision
::selectFields();
567 while ( $continue ) {
568 $row = $db->selectRow(
569 [ 'page', 'revision' ],
572 'page_namespace' => $this->mTitle
->getNamespace(),
573 'page_title' => $this->mTitle
->getDBkey(),
578 'ORDER BY' => 'rev_timestamp ASC'
585 $db = wfGetDB( DB_MASTER
);
590 return $row ? Revision
::newFromRow( $row ) : null;
594 * Loads everything except the text
595 * This isn't necessary for all uses, so it's only done if needed.
597 protected function loadLastEdit() {
598 if ( $this->mLastRevision
!== null ) {
599 return; // already loaded
602 $latest = $this->getLatest();
604 return; // page doesn't exist or is missing page_latest info
607 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
608 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
609 // includes the latest changes committed. This is true even within REPEATABLE-READ
610 // transactions, where S1 normally only sees changes committed before the first S1
611 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
612 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
613 // happened after the first S1 SELECT.
614 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
615 $flags = Revision
::READ_LOCKING
;
616 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
617 // Bug T93976: if page_latest was loaded from the master, fetch the
618 // revision from there as well, as it may not exist yet on a replica DB.
619 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
620 $flags = Revision
::READ_LATEST
;
624 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
625 if ( $revision ) { // sanity
626 $this->setLastEdit( $revision );
631 * Set the latest revision
632 * @param Revision $revision
634 protected function setLastEdit( Revision
$revision ) {
635 $this->mLastRevision
= $revision;
636 $this->mTimestamp
= $revision->getTimestamp();
640 * Get the latest revision
641 * @return Revision|null
643 public function getRevision() {
644 $this->loadLastEdit();
645 if ( $this->mLastRevision
) {
646 return $this->mLastRevision
;
652 * Get the content of the current revision. No side-effects...
654 * @param int $audience One of:
655 * Revision::FOR_PUBLIC to be displayed to all users
656 * Revision::FOR_THIS_USER to be displayed to $wgUser
657 * Revision::RAW get the text regardless of permissions
658 * @param User $user User object to check for, only if FOR_THIS_USER is passed
659 * to the $audience parameter
660 * @return Content|null The content of the current revision
664 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
665 $this->loadLastEdit();
666 if ( $this->mLastRevision
) {
667 return $this->mLastRevision
->getContent( $audience, $user );
673 * Get the text of the current revision. No side-effects...
675 * @param int $audience One of:
676 * Revision::FOR_PUBLIC to be displayed to all users
677 * Revision::FOR_THIS_USER to be displayed to the given user
678 * Revision::RAW get the text regardless of permissions
679 * @param User $user User object to check for, only if FOR_THIS_USER is passed
680 * to the $audience parameter
681 * @return string|bool The text of the current revision
682 * @deprecated since 1.21, getContent() should be used instead.
684 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
685 ContentHandler
::deprecated( __METHOD__
, '1.21' );
687 $this->loadLastEdit();
688 if ( $this->mLastRevision
) {
689 return $this->mLastRevision
->getText( $audience, $user );
695 * @return string MW timestamp of last article revision
697 public function getTimestamp() {
698 // Check if the field has been filled by WikiPage::setTimestamp()
699 if ( !$this->mTimestamp
) {
700 $this->loadLastEdit();
703 return wfTimestamp( TS_MW
, $this->mTimestamp
);
707 * Set the page timestamp (use only to avoid DB queries)
708 * @param string $ts MW timestamp of last article revision
711 public function setTimestamp( $ts ) {
712 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
716 * @param int $audience One of:
717 * Revision::FOR_PUBLIC to be displayed to all users
718 * Revision::FOR_THIS_USER to be displayed to the given user
719 * Revision::RAW get the text regardless of permissions
720 * @param User $user User object to check for, only if FOR_THIS_USER is passed
721 * to the $audience parameter
722 * @return int User ID for the user that made the last article revision
724 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
725 $this->loadLastEdit();
726 if ( $this->mLastRevision
) {
727 return $this->mLastRevision
->getUser( $audience, $user );
734 * Get the User object of the user who created the page
735 * @param int $audience One of:
736 * Revision::FOR_PUBLIC to be displayed to all users
737 * Revision::FOR_THIS_USER to be displayed to the given user
738 * Revision::RAW get the text regardless of permissions
739 * @param User $user User object to check for, only if FOR_THIS_USER is passed
740 * to the $audience parameter
743 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
744 $revision = $this->getOldestRevision();
746 $userName = $revision->getUserText( $audience, $user );
747 return User
::newFromName( $userName, false );
754 * @param int $audience One of:
755 * Revision::FOR_PUBLIC to be displayed to all users
756 * Revision::FOR_THIS_USER to be displayed to the given user
757 * Revision::RAW get the text regardless of permissions
758 * @param User $user User object to check for, only if FOR_THIS_USER is passed
759 * to the $audience parameter
760 * @return string Username of the user that made the last article revision
762 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
763 $this->loadLastEdit();
764 if ( $this->mLastRevision
) {
765 return $this->mLastRevision
->getUserText( $audience, $user );
772 * @param int $audience One of:
773 * Revision::FOR_PUBLIC to be displayed to all users
774 * Revision::FOR_THIS_USER to be displayed to the given user
775 * Revision::RAW get the text regardless of permissions
776 * @param User $user User object to check for, only if FOR_THIS_USER is passed
777 * to the $audience parameter
778 * @return string Comment stored for the last article revision
780 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
781 $this->loadLastEdit();
782 if ( $this->mLastRevision
) {
783 return $this->mLastRevision
->getComment( $audience, $user );
790 * Returns true if last revision was marked as "minor edit"
792 * @return bool Minor edit indicator for the last article revision.
794 public function getMinorEdit() {
795 $this->loadLastEdit();
796 if ( $this->mLastRevision
) {
797 return $this->mLastRevision
->isMinor();
804 * Determine whether a page would be suitable for being counted as an
805 * article in the site_stats table based on the title & its content
807 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
808 * if false, the current database state will be used
811 public function isCountable( $editInfo = false ) {
812 global $wgArticleCountMethod;
814 if ( !$this->mTitle
->isContentPage() ) {
819 $content = $editInfo->pstContent
;
821 $content = $this->getContent();
824 if ( !$content ||
$content->isRedirect() ) {
830 if ( $wgArticleCountMethod === 'link' ) {
831 // nasty special case to avoid re-parsing to detect links
834 // ParserOutput::getLinks() is a 2D array of page links, so
835 // to be really correct we would need to recurse in the array
836 // but the main array should only have items in it if there are
838 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
840 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
841 [ 'pl_from' => $this->getId() ], __METHOD__
);
845 return $content->isCountable( $hasLinks );
849 * If this page is a redirect, get its target
851 * The target will be fetched from the redirect table if possible.
852 * If this page doesn't have an entry there, call insertRedirect()
853 * @return Title|null Title object, or null if this page is not a redirect
855 public function getRedirectTarget() {
856 if ( !$this->mTitle
->isRedirect() ) {
860 if ( $this->mRedirectTarget
!== null ) {
861 return $this->mRedirectTarget
;
864 // Query the redirect table
865 $dbr = wfGetDB( DB_REPLICA
);
866 $row = $dbr->selectRow( 'redirect',
867 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
868 [ 'rd_from' => $this->getId() ],
872 // rd_fragment and rd_interwiki were added later, populate them if empty
873 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
874 $this->mRedirectTarget
= Title
::makeTitle(
875 $row->rd_namespace
, $row->rd_title
,
876 $row->rd_fragment
, $row->rd_interwiki
878 return $this->mRedirectTarget
;
881 // This page doesn't have an entry in the redirect table
882 $this->mRedirectTarget
= $this->insertRedirect();
883 return $this->mRedirectTarget
;
887 * Insert an entry for this page into the redirect table if the content is a redirect
889 * The database update will be deferred via DeferredUpdates
891 * Don't call this function directly unless you know what you're doing.
892 * @return Title|null Title object or null if not a redirect
894 public function insertRedirect() {
895 $content = $this->getContent();
896 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
901 // Update the DB post-send if the page has not cached since now
903 $latest = $this->getLatest();
904 DeferredUpdates
::addCallableUpdate(
905 function () use ( $that, $retval, $latest ) {
906 $that->insertRedirectEntry( $retval, $latest );
908 DeferredUpdates
::POSTSEND
,
916 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
917 * @param Title $rt Redirect target
918 * @param int|null $oldLatest Prior page_latest for check and set
920 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
921 $dbw = wfGetDB( DB_MASTER
);
922 $dbw->startAtomic( __METHOD__
);
924 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
925 $dbw->replace( 'redirect',
928 'rd_from' => $this->getId(),
929 'rd_namespace' => $rt->getNamespace(),
930 'rd_title' => $rt->getDBkey(),
931 'rd_fragment' => $rt->getFragment(),
932 'rd_interwiki' => $rt->getInterwiki(),
938 $dbw->endAtomic( __METHOD__
);
942 * Get the Title object or URL this page redirects to
944 * @return bool|Title|string False, Title of in-wiki target, or string with URL
946 public function followRedirect() {
947 return $this->getRedirectURL( $this->getRedirectTarget() );
951 * Get the Title object or URL to use for a redirect. We use Title
952 * objects for same-wiki, non-special redirects and URLs for everything
954 * @param Title $rt Redirect target
955 * @return bool|Title|string False, Title object of local target, or string with URL
957 public function getRedirectURL( $rt ) {
962 if ( $rt->isExternal() ) {
963 if ( $rt->isLocal() ) {
964 // Offsite wikis need an HTTP redirect.
965 // This can be hard to reverse and may produce loops,
966 // so they may be disabled in the site configuration.
967 $source = $this->mTitle
->getFullURL( 'redirect=no' );
968 return $rt->getFullURL( [ 'rdfrom' => $source ] );
970 // External pages without "local" bit set are not valid
976 if ( $rt->isSpecialPage() ) {
977 // Gotta handle redirects to special pages differently:
978 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
979 // Some pages are not valid targets.
980 if ( $rt->isValidRedirectTarget() ) {
981 return $rt->getFullURL();
991 * Get a list of users who have edited this article, not including the user who made
992 * the most recent revision, which you can get from $article->getUser() if you want it
993 * @return UserArrayFromResult
995 public function getContributors() {
996 // @todo FIXME: This is expensive; cache this info somewhere.
998 $dbr = wfGetDB( DB_REPLICA
);
1000 if ( $dbr->implicitGroupby() ) {
1001 $realNameField = 'user_real_name';
1003 $realNameField = 'MIN(user_real_name) AS user_real_name';
1006 $tables = [ 'revision', 'user' ];
1009 'user_id' => 'rev_user',
1010 'user_name' => 'rev_user_text',
1012 'timestamp' => 'MAX(rev_timestamp)',
1015 $conds = [ 'rev_page' => $this->getId() ];
1017 // The user who made the top revision gets credited as "this page was last edited by
1018 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1019 $user = $this->getUser();
1021 $conds[] = "rev_user != $user";
1023 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1027 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1030 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1034 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1035 'ORDER BY' => 'timestamp DESC',
1038 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1039 return new UserArrayFromResult( $res );
1043 * Should the parser cache be used?
1045 * @param ParserOptions $parserOptions ParserOptions to check
1049 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1050 return $parserOptions->getStubThreshold() == 0
1052 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1053 && $this->getContentHandler()->isParserCacheSupported();
1057 * Get a ParserOutput for the given ParserOptions and revision ID.
1059 * The parser cache will be used if possible. Cache misses that result
1060 * in parser runs are debounced with PoolCounter.
1063 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1064 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1065 * get the current revision (default value)
1066 * @param bool $forceParse Force reindexing, regardless of cache settings
1067 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1069 public function getParserOutput(
1070 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1073 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1074 wfDebug( __METHOD__
.
1075 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1076 if ( $parserOptions->getStubThreshold() ) {
1077 wfIncrStats( 'pcache.miss.stub' );
1080 if ( $useParserCache ) {
1081 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1082 if ( $parserOutput !== false ) {
1083 return $parserOutput;
1087 if ( $oldid === null ||
$oldid === 0 ) {
1088 $oldid = $this->getLatest();
1091 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1094 return $pool->getParserOutput();
1098 * Do standard deferred updates after page view (existing or missing page)
1099 * @param User $user The relevant user
1100 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1102 public function doViewUpdates( User
$user, $oldid = 0 ) {
1103 if ( wfReadOnly() ) {
1107 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1108 // Update newtalk / watchlist notification status
1110 $user->clearNotification( $this->mTitle
, $oldid );
1111 } catch ( DBError
$e ) {
1112 // Avoid outage if the master is not reachable
1113 MWExceptionHandler
::logException( $e );
1118 * Perform the actions of a page purging
1119 * @param integer $flags Bitfield of WikiPage::PURGE_* constants
1122 public function doPurge( $flags = self
::PURGE_ALL
) {
1123 if ( !Hooks
::run( 'ArticlePurge', [ &$this ] ) ) {
1127 if ( ( $flags & self
::PURGE_GLOBAL_PCACHE
) == self
::PURGE_GLOBAL_PCACHE
) {
1128 // Set page_touched in the database to invalidate all DC caches
1129 $this->mTitle
->invalidateCache();
1130 } elseif ( ( $flags & self
::PURGE_CLUSTER_PCACHE
) == self
::PURGE_CLUSTER_PCACHE
) {
1131 // Delete the parser options key in the local cluster to invalidate the DC cache
1132 ParserCache
::singleton()->deleteOptionsKey( $this );
1133 // Avoid sending HTTP 304s in ViewAction to the client who just issued the purge
1134 $cache = ObjectCache
::getLocalClusterInstance();
1136 $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ),
1137 wfTimestamp( TS_MW
),
1142 if ( ( $flags & self
::PURGE_CDN_CACHE
) == self
::PURGE_CDN_CACHE
) {
1143 // Clear any HTML file cache
1144 HTMLFileCache
::clearFileCache( $this->getTitle() );
1145 // Send purge after any page_touched above update was committed
1146 DeferredUpdates
::addUpdate(
1147 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1148 DeferredUpdates
::PRESEND
1152 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1153 // @todo move this logic to MessageCache
1154 if ( $this->exists() ) {
1155 // NOTE: use transclusion text for messages.
1156 // This is consistent with MessageCache::getMsgFromNamespace()
1158 $content = $this->getContent();
1159 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1161 if ( $text === null ) {
1168 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1175 * Get the last time a user explicitly purged the page via action=purge
1177 * @return string|bool TS_MW timestamp or false
1180 public function getLastPurgeTimestamp() {
1181 $cache = ObjectCache
::getLocalClusterInstance();
1183 return $cache->get( $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ) );
1187 * Insert a new empty page record for this article.
1188 * This *must* be followed up by creating a revision
1189 * and running $this->updateRevisionOn( ... );
1190 * or else the record will be left in a funky state.
1191 * Best if all done inside a transaction.
1193 * @param IDatabase $dbw
1194 * @param int|null $pageId Custom page ID that will be used for the insert statement
1196 * @return bool|int The newly created page_id key; false if the row was not
1197 * inserted, e.g. because the title already existed or because the specified
1198 * page ID is already in use.
1200 public function insertOn( $dbw, $pageId = null ) {
1201 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1205 'page_id' => $pageIdForInsert,
1206 'page_namespace' => $this->mTitle
->getNamespace(),
1207 'page_title' => $this->mTitle
->getDBkey(),
1208 'page_restrictions' => '',
1209 'page_is_redirect' => 0, // Will set this shortly...
1211 'page_random' => wfRandom(),
1212 'page_touched' => $dbw->timestamp(),
1213 'page_latest' => 0, // Fill this in shortly...
1214 'page_len' => 0, // Fill this in shortly...
1220 if ( $dbw->affectedRows() > 0 ) {
1221 $newid = $pageId ?
: $dbw->insertId();
1222 $this->mId
= $newid;
1223 $this->mTitle
->resetArticleID( $newid );
1227 return false; // nothing changed
1232 * Update the page record to point to a newly saved revision.
1234 * @param IDatabase $dbw
1235 * @param Revision $revision For ID number, and text used to set
1236 * length and redirect status fields
1237 * @param int $lastRevision If given, will not overwrite the page field
1238 * when different from the currently set value.
1239 * Giving 0 indicates the new page flag should be set on.
1240 * @param bool $lastRevIsRedirect If given, will optimize adding and
1241 * removing rows in redirect table.
1242 * @return bool Success; false if the page row was missing or page_latest changed
1244 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1245 $lastRevIsRedirect = null
1247 global $wgContentHandlerUseDB;
1249 // Assertion to try to catch T92046
1250 if ( (int)$revision->getId() === 0 ) {
1251 throw new InvalidArgumentException(
1252 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1256 $content = $revision->getContent();
1257 $len = $content ?
$content->getSize() : 0;
1258 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1260 $conditions = [ 'page_id' => $this->getId() ];
1262 if ( !is_null( $lastRevision ) ) {
1263 // An extra check against threads stepping on each other
1264 $conditions['page_latest'] = $lastRevision;
1268 'page_latest' => $revision->getId(),
1269 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1270 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1271 'page_is_redirect' => $rt !== null ?
1 : 0,
1275 if ( $wgContentHandlerUseDB ) {
1276 $row['page_content_model'] = $revision->getContentModel();
1279 $dbw->update( 'page',
1284 $result = $dbw->affectedRows() > 0;
1286 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1287 $this->setLastEdit( $revision );
1288 $this->mLatest
= $revision->getId();
1289 $this->mIsRedirect
= (bool)$rt;
1290 // Update the LinkCache.
1291 LinkCache
::singleton()->addGoodLinkObj(
1297 $revision->getContentModel()
1305 * Add row to the redirect table if this is a redirect, remove otherwise.
1307 * @param IDatabase $dbw
1308 * @param Title $redirectTitle Title object pointing to the redirect target,
1309 * or NULL if this is not a redirect
1310 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1311 * removing rows in redirect table.
1312 * @return bool True on success, false on failure
1315 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1316 // Always update redirects (target link might have changed)
1317 // Update/Insert if we don't know if the last revision was a redirect or not
1318 // Delete if changing from redirect to non-redirect
1319 $isRedirect = !is_null( $redirectTitle );
1321 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1325 if ( $isRedirect ) {
1326 $this->insertRedirectEntry( $redirectTitle );
1328 // This is not a redirect, remove row from redirect table
1329 $where = [ 'rd_from' => $this->getId() ];
1330 $dbw->delete( 'redirect', $where, __METHOD__
);
1333 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1334 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1337 return ( $dbw->affectedRows() != 0 );
1341 * If the given revision is newer than the currently set page_latest,
1342 * update the page record. Otherwise, do nothing.
1344 * @deprecated since 1.24, use updateRevisionOn instead
1346 * @param IDatabase $dbw
1347 * @param Revision $revision
1350 public function updateIfNewerOn( $dbw, $revision ) {
1352 $row = $dbw->selectRow(
1353 [ 'revision', 'page' ],
1354 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1356 'page_id' => $this->getId(),
1357 'page_latest=rev_id' ],
1361 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1364 $prev = $row->rev_id
;
1365 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1367 // No or missing previous revision; mark the page as new
1369 $lastRevIsRedirect = null;
1372 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1378 * Get the content that needs to be saved in order to undo all revisions
1379 * between $undo and $undoafter. Revisions must belong to the same page,
1380 * must exist and must not be deleted
1381 * @param Revision $undo
1382 * @param Revision $undoafter Must be an earlier revision than $undo
1383 * @return Content|bool Content on success, false on failure
1385 * Before we had the Content object, this was done in getUndoText
1387 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1388 $handler = $undo->getContentHandler();
1389 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1393 * Returns true if this page's content model supports sections.
1397 * @todo The skin should check this and not offer section functionality if
1398 * sections are not supported.
1399 * @todo The EditPage should check this and not offer section functionality
1400 * if sections are not supported.
1402 public function supportsSections() {
1403 return $this->getContentHandler()->supportsSections();
1407 * @param string|number|null|bool $sectionId Section identifier as a number or string
1408 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1409 * or 'new' for a new section.
1410 * @param Content $sectionContent New content of the section.
1411 * @param string $sectionTitle New section's subject, only if $section is "new".
1412 * @param string $edittime Revision timestamp or null to use the current revision.
1414 * @throws MWException
1415 * @return Content|null New complete article content, or null if error.
1418 * @deprecated since 1.24, use replaceSectionAtRev instead
1420 public function replaceSectionContent(
1421 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1425 if ( $edittime && $sectionId !== 'new' ) {
1426 $dbr = wfGetDB( DB_REPLICA
);
1427 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1428 // Try the master if this thread may have just added it.
1429 // This could be abstracted into a Revision method, but we don't want
1430 // to encourage loading of revisions by timestamp.
1432 && wfGetLB()->getServerCount() > 1
1433 && wfGetLB()->hasOrMadeRecentMasterChanges()
1435 $dbw = wfGetDB( DB_MASTER
);
1436 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1439 $baseRevId = $rev->getId();
1443 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1447 * @param string|number|null|bool $sectionId Section identifier as a number or string
1448 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1449 * or 'new' for a new section.
1450 * @param Content $sectionContent New content of the section.
1451 * @param string $sectionTitle New section's subject, only if $section is "new".
1452 * @param int|null $baseRevId
1454 * @throws MWException
1455 * @return Content|null New complete article content, or null if error.
1459 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1460 $sectionTitle = '', $baseRevId = null
1463 if ( strval( $sectionId ) === '' ) {
1464 // Whole-page edit; let the whole text through
1465 $newContent = $sectionContent;
1467 if ( !$this->supportsSections() ) {
1468 throw new MWException( "sections not supported for content model " .
1469 $this->getContentHandler()->getModelID() );
1472 // Bug 30711: always use current version when adding a new section
1473 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1474 $oldContent = $this->getContent();
1476 $rev = Revision
::newFromId( $baseRevId );
1478 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1479 $this->getId() . "; section: $sectionId)\n" );
1483 $oldContent = $rev->getContent();
1486 if ( !$oldContent ) {
1487 wfDebug( __METHOD__
. ": no page text\n" );
1491 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1498 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1500 * @return int Updated $flags
1502 public function checkFlags( $flags ) {
1503 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1504 if ( $this->exists() ) {
1505 $flags |
= EDIT_UPDATE
;
1515 * Change an existing article or create a new article. Updates RC and all necessary caches,
1516 * optionally via the deferred update array.
1518 * @param string $text New text
1519 * @param string $summary Edit summary
1520 * @param int $flags Bitfield:
1522 * Article is known or assumed to be non-existent, create a new one
1524 * Article is known or assumed to be pre-existing, update it
1526 * Mark this edit minor, if the user is allowed to do so
1528 * Do not log the change in recentchanges
1530 * Mark the edit a "bot" edit regardless of user rights
1532 * Fill in blank summaries with generated text where possible
1534 * Signal that the page retrieve/save cycle happened entirely in this request.
1536 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1537 * article will be detected. If EDIT_UPDATE is specified and the article
1538 * doesn't exist, the function will return an edit-gone-missing error. If
1539 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1540 * error will be returned. These two conditions are also possible with
1541 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1543 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1544 * This is not the parent revision ID, rather the revision ID for older
1545 * content used as the source for a rollback, for example.
1546 * @param User $user The user doing the edit
1548 * @throws MWException
1549 * @return Status Possible errors:
1550 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1551 * set the fatal flag of $status
1552 * edit-gone-missing: In update mode, but the article didn't exist.
1553 * edit-conflict: In update mode, the article changed unexpectedly.
1554 * edit-no-change: Warning that the text was the same as before.
1555 * edit-already-exists: In creation mode, but the article already exists.
1557 * Extensions may define additional errors.
1559 * $return->value will contain an associative array with members as follows:
1560 * new: Boolean indicating if the function attempted to create a new article.
1561 * revision: The revision object for the inserted revision, or null.
1563 * Compatibility note: this function previously returned a boolean value
1564 * indicating success/failure
1566 * @deprecated since 1.21: use doEditContent() instead.
1568 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1569 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1571 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1573 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1577 * Change an existing article or create a new article. Updates RC and all necessary caches,
1578 * optionally via the deferred update array.
1580 * @param Content $content New content
1581 * @param string $summary Edit summary
1582 * @param int $flags Bitfield:
1584 * Article is known or assumed to be non-existent, create a new one
1586 * Article is known or assumed to be pre-existing, update it
1588 * Mark this edit minor, if the user is allowed to do so
1590 * Do not log the change in recentchanges
1592 * Mark the edit a "bot" edit regardless of user rights
1594 * Fill in blank summaries with generated text where possible
1596 * Signal that the page retrieve/save cycle happened entirely in this request.
1598 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1599 * article will be detected. If EDIT_UPDATE is specified and the article
1600 * doesn't exist, the function will return an edit-gone-missing error. If
1601 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1602 * error will be returned. These two conditions are also possible with
1603 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1605 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1606 * This is not the parent revision ID, rather the revision ID for older
1607 * content used as the source for a rollback, for example.
1608 * @param User $user The user doing the edit
1609 * @param string $serialFormat Format for storing the content in the
1611 * @param array|null $tags Change tags to apply to this edit
1612 * Callers are responsible for permission checks
1613 * (with ChangeTags::canAddTagsAccompanyingChange)
1615 * @throws MWException
1616 * @return Status Possible errors:
1617 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1618 * set the fatal flag of $status.
1619 * edit-gone-missing: In update mode, but the article didn't exist.
1620 * edit-conflict: In update mode, the article changed unexpectedly.
1621 * edit-no-change: Warning that the text was the same as before.
1622 * edit-already-exists: In creation mode, but the article already exists.
1624 * Extensions may define additional errors.
1626 * $return->value will contain an associative array with members as follows:
1627 * new: Boolean indicating if the function attempted to create a new article.
1628 * revision: The revision object for the inserted revision, or null.
1631 * @throws MWException
1633 public function doEditContent(
1634 Content
$content, $summary, $flags = 0, $baseRevId = false,
1635 User
$user = null, $serialFormat = null, $tags = null
1637 global $wgUser, $wgUseAutomaticEditSummaries;
1639 // Low-level sanity check
1640 if ( $this->mTitle
->getText() === '' ) {
1641 throw new MWException( 'Something is trying to edit an article with an empty title' );
1643 // Make sure the given content type is allowed for this page
1644 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1645 return Status
::newFatal( 'content-not-allowed-here',
1646 ContentHandler
::getLocalizedName( $content->getModel() ),
1647 $this->mTitle
->getPrefixedText()
1651 // Load the data from the master database if needed.
1652 // The caller may already loaded it from the master or even loaded it using
1653 // SELECT FOR UPDATE, so do not override that using clear().
1654 $this->loadPageData( 'fromdbmaster' );
1656 $user = $user ?
: $wgUser;
1657 $flags = $this->checkFlags( $flags );
1659 // Trigger pre-save hook (using provided edit summary)
1660 $hookStatus = Status
::newGood( [] );
1661 $hook_args = [ &$this, &$user, &$content, &$summary,
1662 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1663 // Check if the hook rejected the attempted save
1664 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1665 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args )
1667 if ( $hookStatus->isOK() ) {
1668 // Hook returned false but didn't call fatal(); use generic message
1669 $hookStatus->fatal( 'edit-hook-aborted' );
1675 $old_revision = $this->getRevision(); // current revision
1676 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1678 // Provide autosummaries if one is not provided and autosummaries are enabled
1679 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1680 $handler = $content->getContentHandler();
1681 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1684 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1685 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1691 // Get the pre-save transform content and final parser output
1692 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1693 $pstContent = $editInfo->pstContent
; // Content object
1695 'bot' => ( $flags & EDIT_FORCE_BOT
),
1696 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1697 'serialized' => $editInfo->pst
,
1698 'serialFormat' => $serialFormat,
1699 'baseRevId' => $baseRevId,
1700 'oldRevision' => $old_revision,
1701 'oldContent' => $old_content,
1702 'oldId' => $this->getLatest(),
1703 'oldIsRedirect' => $this->isRedirect(),
1704 'oldCountable' => $this->isCountable(),
1705 'tags' => ( $tags !== null ) ?
(array)$tags : []
1708 // Actually create the revision and create/update the page
1709 if ( $flags & EDIT_UPDATE
) {
1710 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1712 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1715 // Promote user to any groups they meet the criteria for
1716 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1717 $user->addAutopromoteOnceGroups( 'onEdit' );
1718 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1725 * @param Content $content Pre-save transform content
1726 * @param integer $flags
1728 * @param string $summary
1729 * @param array $meta
1731 * @throws DBUnexpectedError
1733 * @throws FatalError
1734 * @throws MWException
1736 private function doModify(
1737 Content
$content, $flags, User
$user, $summary, array $meta
1739 global $wgUseRCPatrol;
1741 // Update article, but only if changed.
1742 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1744 // Convenience variables
1745 $now = wfTimestampNow();
1746 $oldid = $meta['oldId'];
1747 /** @var $oldContent Content|null */
1748 $oldContent = $meta['oldContent'];
1749 $newsize = $content->getSize();
1752 // Article gone missing
1753 $status->fatal( 'edit-gone-missing' );
1756 } elseif ( !$oldContent ) {
1757 // Sanity check for bug 37225
1758 throw new MWException( "Could not find text for current revision {$oldid}." );
1761 // @TODO: pass content object?!
1762 $revision = new Revision( [
1763 'page' => $this->getId(),
1764 'title' => $this->mTitle
, // for determining the default content model
1765 'comment' => $summary,
1766 'minor_edit' => $meta['minor'],
1767 'text' => $meta['serialized'],
1769 'parent_id' => $oldid,
1770 'user' => $user->getId(),
1771 'user_text' => $user->getName(),
1772 'timestamp' => $now,
1773 'content_model' => $content->getModel(),
1774 'content_format' => $meta['serialFormat'],
1777 $changed = !$content->equals( $oldContent );
1779 $dbw = wfGetDB( DB_MASTER
);
1782 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1783 $status->merge( $prepStatus );
1784 if ( !$status->isOK() ) {
1788 $dbw->startAtomic( __METHOD__
);
1789 // Get the latest page_latest value while locking it.
1790 // Do a CAS style check to see if it's the same as when this method
1791 // started. If it changed then bail out before touching the DB.
1792 $latestNow = $this->lockAndGetLatest();
1793 if ( $latestNow != $oldid ) {
1794 $dbw->endAtomic( __METHOD__
);
1795 // Page updated or deleted in the mean time
1796 $status->fatal( 'edit-conflict' );
1801 // At this point we are now comitted to returning an OK
1802 // status unless some DB query error or other exception comes up.
1803 // This way callers don't have to call rollback() if $status is bad
1804 // unless they actually try to catch exceptions (which is rare).
1806 // Save the revision text
1807 $revisionId = $revision->insertOn( $dbw );
1808 // Update page_latest and friends to reflect the new revision
1809 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1810 throw new MWException( "Failed to update page row to use new revision." );
1813 Hooks
::run( 'NewRevisionFromEditComplete',
1814 [ $this, $revision, $meta['baseRevId'], $user ] );
1816 // Update recentchanges
1817 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1818 // Mark as patrolled if the user can do so
1819 $patrolled = $wgUseRCPatrol && !count(
1820 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1821 // Add RC row to the DB
1822 RecentChange
::notifyEdit(
1825 $revision->isMinor(),
1829 $this->getTimestamp(),
1832 $oldContent ?
$oldContent->getSize() : 0,
1840 $user->incEditCount();
1842 $dbw->endAtomic( __METHOD__
);
1843 $this->mTimestamp
= $now;
1845 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1846 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1847 $revision->setId( $this->getLatest() );
1848 $revision->setUserIdAndName(
1849 $this->getUser( Revision
::RAW
),
1850 $this->getUserText( Revision
::RAW
)
1855 // Return the new revision to the caller
1856 $status->value
['revision'] = $revision;
1858 $status->warning( 'edit-no-change' );
1859 // Update page_touched as updateRevisionOn() was not called.
1860 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1861 $this->mTitle
->invalidateCache( $now );
1864 // Do secondary updates once the main changes have been committed...
1865 DeferredUpdates
::addUpdate(
1866 new AtomicSectionUpdate(
1870 $revision, &$user, $content, $summary, &$flags,
1871 $changed, $meta, &$status
1873 // Update links tables, site stats, etc.
1874 $this->doEditUpdates(
1878 'changed' => $changed,
1879 'oldcountable' => $meta['oldCountable'],
1880 'oldrevision' => $meta['oldRevision']
1883 // Trigger post-save hook
1884 $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR
,
1885 null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1886 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
1887 Hooks
::run( 'PageContentSaveComplete', $params );
1890 DeferredUpdates
::PRESEND
1897 * @param Content $content Pre-save transform content
1898 * @param integer $flags
1900 * @param string $summary
1901 * @param array $meta
1903 * @throws DBUnexpectedError
1905 * @throws FatalError
1906 * @throws MWException
1908 private function doCreate(
1909 Content
$content, $flags, User
$user, $summary, array $meta
1911 global $wgUseRCPatrol, $wgUseNPPatrol;
1913 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1915 $now = wfTimestampNow();
1916 $newsize = $content->getSize();
1917 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1918 $status->merge( $prepStatus );
1919 if ( !$status->isOK() ) {
1923 $dbw = wfGetDB( DB_MASTER
);
1924 $dbw->startAtomic( __METHOD__
);
1926 // Add the page record unless one already exists for the title
1927 $newid = $this->insertOn( $dbw );
1928 if ( $newid === false ) {
1929 $dbw->endAtomic( __METHOD__
); // nothing inserted
1930 $status->fatal( 'edit-already-exists' );
1932 return $status; // nothing done
1935 // At this point we are now comitted to returning an OK
1936 // status unless some DB query error or other exception comes up.
1937 // This way callers don't have to call rollback() if $status is bad
1938 // unless they actually try to catch exceptions (which is rare).
1940 // @TODO: pass content object?!
1941 $revision = new Revision( [
1943 'title' => $this->mTitle
, // for determining the default content model
1944 'comment' => $summary,
1945 'minor_edit' => $meta['minor'],
1946 'text' => $meta['serialized'],
1948 'user' => $user->getId(),
1949 'user_text' => $user->getName(),
1950 'timestamp' => $now,
1951 'content_model' => $content->getModel(),
1952 'content_format' => $meta['serialFormat'],
1955 // Save the revision text...
1956 $revisionId = $revision->insertOn( $dbw );
1957 // Update the page record with revision data
1958 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1959 throw new MWException( "Failed to update page row to use new revision." );
1962 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1964 // Update recentchanges
1965 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1966 // Mark as patrolled if the user can do so
1967 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1968 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1969 // Add RC row to the DB
1970 RecentChange
::notifyNew(
1973 $revision->isMinor(),
1985 $user->incEditCount();
1987 $dbw->endAtomic( __METHOD__
);
1988 $this->mTimestamp
= $now;
1990 // Return the new revision to the caller
1991 $status->value
['revision'] = $revision;
1993 // Do secondary updates once the main changes have been committed...
1994 DeferredUpdates
::addUpdate(
1995 new AtomicSectionUpdate(
1999 $revision, &$user, $content, $summary, &$flags, $meta, &$status
2001 // Update links, etc.
2002 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
2003 // Trigger post-create hook
2004 $params = [ &$this, &$user, $content, $summary,
2005 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
2006 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $params );
2007 Hooks
::run( 'PageContentInsertComplete', $params );
2008 // Trigger post-save hook
2009 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
2010 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
2011 Hooks
::run( 'PageContentSaveComplete', $params );
2015 DeferredUpdates
::PRESEND
2022 * Get parser options suitable for rendering the primary article wikitext
2024 * @see ContentHandler::makeParserOptions
2026 * @param IContextSource|User|string $context One of the following:
2027 * - IContextSource: Use the User and the Language of the provided
2029 * - User: Use the provided User object and $wgLang for the language,
2030 * so use an IContextSource object if possible.
2031 * - 'canonical': Canonical options (anonymous user with default
2032 * preferences and content language).
2033 * @return ParserOptions
2035 public function makeParserOptions( $context ) {
2036 $options = $this->getContentHandler()->makeParserOptions( $context );
2038 if ( $this->getTitle()->isConversionTable() ) {
2039 // @todo ConversionTable should become a separate content model, so
2040 // we don't need special cases like this one.
2041 $options->disableContentConversion();
2048 * Prepare text which is about to be saved.
2049 * Returns a stdClass with source, pst and output members
2051 * @param string $text
2052 * @param int|null $revid
2053 * @param User|null $user
2054 * @deprecated since 1.21: use prepareContentForEdit instead.
2057 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2058 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2059 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2060 return $this->prepareContentForEdit( $content, $revid, $user );
2064 * Prepare content which is about to be saved.
2065 * Returns a stdClass with source, pst and output members
2067 * @param Content $content
2068 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2069 * revision ID is also accepted, but this is deprecated.
2070 * @param User|null $user
2071 * @param string|null $serialFormat
2072 * @param bool $useCache Check shared prepared edit cache
2078 public function prepareContentForEdit(
2079 Content
$content, $revision = null, User
$user = null,
2080 $serialFormat = null, $useCache = true
2082 global $wgContLang, $wgUser, $wgAjaxEditStash;
2084 if ( is_object( $revision ) ) {
2085 $revid = $revision->getId();
2088 // This code path is deprecated, and nothing is known to
2089 // use it, so performance here shouldn't be a worry.
2090 if ( $revid !== null ) {
2091 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2097 $user = is_null( $user ) ?
$wgUser : $user;
2098 // XXX: check $user->getId() here???
2100 // Use a sane default for $serialFormat, see bug 57026
2101 if ( $serialFormat === null ) {
2102 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2105 if ( $this->mPreparedEdit
2106 && isset( $this->mPreparedEdit
->newContent
)
2107 && $this->mPreparedEdit
->newContent
->equals( $content )
2108 && $this->mPreparedEdit
->revid
== $revid
2109 && $this->mPreparedEdit
->format
== $serialFormat
2110 // XXX: also check $user here?
2113 return $this->mPreparedEdit
;
2116 // The edit may have already been prepared via api.php?action=stashedit
2117 $cachedEdit = $useCache && $wgAjaxEditStash
2118 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2121 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2122 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2125 if ( $cachedEdit ) {
2126 $edit->timestamp
= $cachedEdit->timestamp
;
2128 $edit->timestamp
= wfTimestampNow();
2130 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2131 $edit->revid
= $revid;
2133 if ( $cachedEdit ) {
2134 $edit->pstContent
= $cachedEdit->pstContent
;
2136 $edit->pstContent
= $content
2137 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2141 $edit->format
= $serialFormat;
2142 $edit->popts
= $this->makeParserOptions( 'canonical' );
2143 if ( $cachedEdit ) {
2144 $edit->output
= $cachedEdit->output
;
2147 // We get here if vary-revision is set. This means that this page references
2148 // itself (such as via self-transclusion). In this case, we need to make sure
2149 // that any such self-references refer to the newly-saved revision, and not
2150 // to the previous one, which could otherwise happen due to replica DB lag.
2151 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2152 $edit->popts
->setCurrentRevisionCallback(
2153 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2154 if ( $title->equals( $revision->getTitle() ) ) {
2157 return call_user_func( $oldCallback, $title, $parser );
2162 // Try to avoid a second parse if {{REVISIONID}} is used
2163 $edit->popts
->setSpeculativeRevIdCallback( function () {
2164 return 1 +
(int)wfGetDB( DB_MASTER
)->selectField(
2172 $edit->output
= $edit->pstContent
2173 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2177 $edit->newContent
= $content;
2178 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2180 // NOTE: B/C for hooks! don't use these fields!
2181 $edit->newText
= $edit->newContent
2182 ? ContentHandler
::getContentText( $edit->newContent
)
2184 $edit->oldText
= $edit->oldContent
2185 ? ContentHandler
::getContentText( $edit->oldContent
)
2187 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2189 if ( $edit->output
) {
2190 $edit->output
->setCacheTime( wfTimestampNow() );
2193 // Process cache the result
2194 $this->mPreparedEdit
= $edit;
2200 * Do standard deferred updates after page edit.
2201 * Update links tables, site stats, search index and message cache.
2202 * Purges pages that include this page if the text was changed here.
2203 * Every 100th edit, prune the recent changes table.
2205 * @param Revision $revision
2206 * @param User $user User object that did the revision
2207 * @param array $options Array of options, following indexes are used:
2208 * - changed: boolean, whether the revision changed the content (default true)
2209 * - created: boolean, whether the revision created the page (default false)
2210 * - moved: boolean, whether the page was moved (default false)
2211 * - restored: boolean, whether the page was undeleted (default false)
2212 * - oldrevision: Revision object for the pre-update revision (default null)
2213 * - oldcountable: boolean, null, or string 'no-change' (default null):
2214 * - boolean: whether the page was counted as an article before that
2215 * revision, only used in changed is true and created is false
2216 * - null: if created is false, don't update the article count; if created
2217 * is true, do update the article count
2218 * - 'no-change': don't update the article count, ever
2220 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2221 global $wgRCWatchCategoryMembership, $wgContLang;
2227 'restored' => false,
2228 'oldrevision' => null,
2229 'oldcountable' => null
2231 $content = $revision->getContent();
2233 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2235 // See if the parser output before $revision was inserted is still valid
2237 if ( !$this->mPreparedEdit
) {
2238 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2239 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2240 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2241 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2242 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2244 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2245 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2246 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2248 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2249 $editInfo = $this->mPreparedEdit
;
2253 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2254 // $text is usually already pre-save transformed once. Avoid using the edit stash
2255 // as any prepared content from there or in doEditContent() was already rejected.
2256 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2259 // Save it to the parser cache.
2260 // Make sure the cache time matches page_touched to avoid double parsing.
2261 ParserCache
::singleton()->save(
2262 $editInfo->output
, $this, $editInfo->popts
,
2263 $revision->getTimestamp(), $editInfo->revid
2266 // Update the links tables and other secondary data
2268 $recursive = $options['changed']; // bug 50785
2269 $updates = $content->getSecondaryDataUpdates(
2270 $this->getTitle(), null, $recursive, $editInfo->output
2272 foreach ( $updates as $update ) {
2273 if ( $update instanceof LinksUpdate
) {
2274 $update->setRevision( $revision );
2275 $update->setTriggeringUser( $user );
2277 DeferredUpdates
::addUpdate( $update );
2279 if ( $wgRCWatchCategoryMembership
2280 && $this->getContentHandler()->supportsCategories() === true
2281 && ( $options['changed'] ||
$options['created'] )
2282 && !$options['restored']
2284 // Note: jobs are pushed after deferred updates, so the job should be able to see
2285 // the recent change entry (also done via deferred updates) and carry over any
2286 // bot/deletion/IP flags, ect.
2287 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2290 'pageId' => $this->getId(),
2291 'revTimestamp' => $revision->getTimestamp()
2297 Hooks
::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2299 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2300 // Flush old entries from the `recentchanges` table
2301 if ( mt_rand( 0, 9 ) == 0 ) {
2302 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2306 if ( !$this->exists() ) {
2310 $id = $this->getId();
2311 $title = $this->mTitle
->getPrefixedDBkey();
2312 $shortTitle = $this->mTitle
->getDBkey();
2314 if ( $options['oldcountable'] === 'no-change' ||
2315 ( !$options['changed'] && !$options['moved'] )
2318 } elseif ( $options['created'] ) {
2319 $good = (int)$this->isCountable( $editInfo );
2320 } elseif ( $options['oldcountable'] !== null ) {
2321 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2325 $edits = $options['changed'] ?
1 : 0;
2326 $total = $options['created'] ?
1 : 0;
2328 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2329 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2331 // If this is another user's talk page, update newtalk.
2332 // Don't do this if $options['changed'] = false (null-edits) nor if
2333 // it's a minor edit and the user doesn't want notifications for those.
2334 if ( $options['changed']
2335 && $this->mTitle
->getNamespace() == NS_USER_TALK
2336 && $shortTitle != $user->getTitleKey()
2337 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2339 $recipient = User
::newFromName( $shortTitle, false );
2340 if ( !$recipient ) {
2341 wfDebug( __METHOD__
. ": invalid username\n" );
2343 // Allow extensions to prevent user notification
2344 // when a new message is added to their talk page
2345 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2346 if ( User
::isIP( $shortTitle ) ) {
2347 // An anonymous user
2348 $recipient->setNewtalk( true, $revision );
2349 } elseif ( $recipient->isLoggedIn() ) {
2350 $recipient->setNewtalk( true, $revision );
2352 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2358 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2359 // XXX: could skip pseudo-messages like js/css here, based on content model.
2360 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2361 if ( $msgtext === false ||
$msgtext === null ) {
2365 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2367 if ( $wgContLang->hasVariants() ) {
2368 $wgContLang->updateConversionTable( $this->mTitle
);
2372 if ( $options['created'] ) {
2373 self
::onArticleCreate( $this->mTitle
);
2374 } elseif ( $options['changed'] ) { // bug 50785
2375 self
::onArticleEdit( $this->mTitle
, $revision );
2380 * Edit an article without doing all that other stuff
2381 * The article must already exist; link tables etc
2382 * are not updated, caches are not flushed.
2384 * @param Content $content Content submitted
2385 * @param User $user The relevant user
2386 * @param string $comment Comment submitted
2387 * @param bool $minor Whereas it's a minor modification
2388 * @param string $serialFormat Format for storing the content in the database
2390 public function doQuickEditContent(
2391 Content
$content, User
$user, $comment = '', $minor = false, $serialFormat = null
2394 $serialized = $content->serialize( $serialFormat );
2396 $dbw = wfGetDB( DB_MASTER
);
2397 $revision = new Revision( [
2398 'title' => $this->getTitle(), // for determining the default content model
2399 'page' => $this->getId(),
2400 'user_text' => $user->getName(),
2401 'user' => $user->getId(),
2402 'text' => $serialized,
2403 'length' => $content->getSize(),
2404 'comment' => $comment,
2405 'minor_edit' => $minor ?
1 : 0,
2406 ] ); // XXX: set the content object?
2407 $revision->insertOn( $dbw );
2408 $this->updateRevisionOn( $dbw, $revision );
2410 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2415 * Update the article's restriction field, and leave a log entry.
2416 * This works for protection both existing and non-existing pages.
2418 * @param array $limit Set of restriction keys
2419 * @param array $expiry Per restriction type expiration
2420 * @param int &$cascade Set to false if cascading protection isn't allowed.
2421 * @param string $reason
2422 * @param User $user The user updating the restrictions
2423 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2424 * ($user should be able to add the specified tags before this is called)
2425 * @return Status Status object; if action is taken, $status->value is the log_id of the
2426 * protection log entry.
2428 public function doUpdateRestrictions( array $limit, array $expiry,
2429 &$cascade, $reason, User
$user, $tags = null
2431 global $wgCascadingRestrictionLevels, $wgContLang;
2433 if ( wfReadOnly() ) {
2434 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2437 $this->loadPageData( 'fromdbmaster' );
2438 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2439 $id = $this->getId();
2445 // Take this opportunity to purge out expired restrictions
2446 Title
::purgeExpiredRestrictions();
2448 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2449 // we expect a single selection, but the schema allows otherwise.
2450 $isProtected = false;
2454 $dbw = wfGetDB( DB_MASTER
);
2456 foreach ( $restrictionTypes as $action ) {
2457 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2458 $expiry[$action] = 'infinity';
2460 if ( !isset( $limit[$action] ) ) {
2461 $limit[$action] = '';
2462 } elseif ( $limit[$action] != '' ) {
2466 // Get current restrictions on $action
2467 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2468 if ( $current != '' ) {
2469 $isProtected = true;
2472 if ( $limit[$action] != $current ) {
2474 } elseif ( $limit[$action] != '' ) {
2475 // Only check expiry change if the action is actually being
2476 // protected, since expiry does nothing on an not-protected
2478 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2484 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2488 // If nothing has changed, do nothing
2490 return Status
::newGood();
2493 if ( !$protect ) { // No protection at all means unprotection
2494 $revCommentMsg = 'unprotectedarticle';
2495 $logAction = 'unprotect';
2496 } elseif ( $isProtected ) {
2497 $revCommentMsg = 'modifiedarticleprotection';
2498 $logAction = 'modify';
2500 $revCommentMsg = 'protectedarticle';
2501 $logAction = 'protect';
2504 // Truncate for whole multibyte characters
2505 $reason = $wgContLang->truncate( $reason, 255 );
2507 $logRelationsValues = [];
2508 $logRelationsField = null;
2509 $logParamsDetails = [];
2511 // Null revision (used for change tag insertion)
2512 $nullRevision = null;
2514 if ( $id ) { // Protection of existing page
2515 if ( !Hooks
::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2516 return Status
::newGood();
2519 // Only certain restrictions can cascade...
2520 $editrestriction = isset( $limit['edit'] )
2521 ?
[ $limit['edit'] ]
2522 : $this->mTitle
->getRestrictions( 'edit' );
2523 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2524 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2526 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2527 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2530 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2531 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2532 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2534 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2535 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2538 // The schema allows multiple restrictions
2539 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2543 // insert null revision to identify the page protection change as edit summary
2544 $latest = $this->getLatest();
2545 $nullRevision = $this->insertProtectNullRevision(
2554 if ( $nullRevision === null ) {
2555 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2558 $logRelationsField = 'pr_id';
2560 // Update restrictions table
2561 foreach ( $limit as $action => $restrictions ) {
2563 'page_restrictions',
2566 'pr_type' => $action
2570 if ( $restrictions != '' ) {
2571 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2573 'page_restrictions',
2575 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2577 'pr_type' => $action,
2578 'pr_level' => $restrictions,
2579 'pr_cascade' => $cascadeValue,
2580 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2584 $logRelationsValues[] = $dbw->insertId();
2585 $logParamsDetails[] = [
2587 'level' => $restrictions,
2588 'expiry' => $expiry[$action],
2589 'cascade' => (bool)$cascadeValue,
2594 // Clear out legacy restriction fields
2597 [ 'page_restrictions' => '' ],
2598 [ 'page_id' => $id ],
2602 Hooks
::run( 'NewRevisionFromEditComplete',
2603 [ $this, $nullRevision, $latest, $user ] );
2604 Hooks
::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2605 } else { // Protection of non-existing page (also known as "title protection")
2606 // Cascade protection is meaningless in this case
2609 if ( $limit['create'] != '' ) {
2610 $dbw->replace( 'protected_titles',
2611 [ [ 'pt_namespace', 'pt_title' ] ],
2613 'pt_namespace' => $this->mTitle
->getNamespace(),
2614 'pt_title' => $this->mTitle
->getDBkey(),
2615 'pt_create_perm' => $limit['create'],
2616 'pt_timestamp' => $dbw->timestamp(),
2617 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2618 'pt_user' => $user->getId(),
2619 'pt_reason' => $reason,
2622 $logParamsDetails[] = [
2624 'level' => $limit['create'],
2625 'expiry' => $expiry['create'],
2628 $dbw->delete( 'protected_titles',
2630 'pt_namespace' => $this->mTitle
->getNamespace(),
2631 'pt_title' => $this->mTitle
->getDBkey()
2637 $this->mTitle
->flushRestrictions();
2638 InfoAction
::invalidateCache( $this->mTitle
);
2640 if ( $logAction == 'unprotect' ) {
2643 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2645 '4::description' => $protectDescriptionLog, // parameter for IRC
2646 '5:bool:cascade' => $cascade,
2647 'details' => $logParamsDetails, // parameter for localize and api
2651 // Update the protection log
2652 $logEntry = new ManualLogEntry( 'protect', $logAction );
2653 $logEntry->setTarget( $this->mTitle
);
2654 $logEntry->setComment( $reason );
2655 $logEntry->setPerformer( $user );
2656 $logEntry->setParameters( $params );
2657 if ( !is_null( $nullRevision ) ) {
2658 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2660 $logEntry->setTags( $tags );
2661 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2662 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2664 $logId = $logEntry->insert();
2665 $logEntry->publish( $logId );
2667 return Status
::newGood( $logId );
2671 * Insert a new null revision for this page.
2673 * @param string $revCommentMsg Comment message key for the revision
2674 * @param array $limit Set of restriction keys
2675 * @param array $expiry Per restriction type expiration
2676 * @param int $cascade Set to false if cascading protection isn't allowed.
2677 * @param string $reason
2678 * @param User|null $user
2679 * @return Revision|null Null on error
2681 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2682 array $expiry, $cascade, $reason, $user = null
2685 $dbw = wfGetDB( DB_MASTER
);
2687 // Prepare a null revision to be added to the history
2688 $editComment = $wgContLang->ucfirst(
2691 $this->mTitle
->getPrefixedText()
2692 )->inContentLanguage()->text()
2695 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2697 $protectDescription = $this->protectDescription( $limit, $expiry );
2698 if ( $protectDescription ) {
2699 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2700 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2701 ->inContentLanguage()->text();
2704 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2705 $editComment .= wfMessage( 'brackets' )->params(
2706 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2707 )->inContentLanguage()->text();
2710 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2712 $nullRev->insertOn( $dbw );
2714 // Update page record and touch page
2715 $oldLatest = $nullRev->getParentId();
2716 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2723 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2726 protected function formatExpiry( $expiry ) {
2729 if ( $expiry != 'infinity' ) {
2732 $wgContLang->timeanddate( $expiry, false, false ),
2733 $wgContLang->date( $expiry, false, false ),
2734 $wgContLang->time( $expiry, false, false )
2735 )->inContentLanguage()->text();
2737 return wfMessage( 'protect-expiry-indefinite' )
2738 ->inContentLanguage()->text();
2743 * Builds the description to serve as comment for the edit.
2745 * @param array $limit Set of restriction keys
2746 * @param array $expiry Per restriction type expiration
2749 public function protectDescription( array $limit, array $expiry ) {
2750 $protectDescription = '';
2752 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2753 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2754 # All possible message keys are listed here for easier grepping:
2755 # * restriction-create
2756 # * restriction-edit
2757 # * restriction-move
2758 # * restriction-upload
2759 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2760 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2761 # with '' filtered out. All possible message keys are listed below:
2762 # * protect-level-autoconfirmed
2763 # * protect-level-sysop
2764 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2765 ->inContentLanguage()->text();
2767 $expiryText = $this->formatExpiry( $expiry[$action] );
2769 if ( $protectDescription !== '' ) {
2770 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2772 $protectDescription .= wfMessage( 'protect-summary-desc' )
2773 ->params( $actionText, $restrictionsText, $expiryText )
2774 ->inContentLanguage()->text();
2777 return $protectDescription;
2781 * Builds the description to serve as comment for the log entry.
2783 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2784 * protect description text. Keep them in old format to avoid breaking compatibility.
2785 * TODO: Fix protection log to store structured description and format it on-the-fly.
2787 * @param array $limit Set of restriction keys
2788 * @param array $expiry Per restriction type expiration
2791 public function protectDescriptionLog( array $limit, array $expiry ) {
2794 $protectDescriptionLog = '';
2796 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2797 $expiryText = $this->formatExpiry( $expiry[$action] );
2798 $protectDescriptionLog .= $wgContLang->getDirMark() .
2799 "[$action=$restrictions] ($expiryText)";
2802 return trim( $protectDescriptionLog );
2806 * Take an array of page restrictions and flatten it to a string
2807 * suitable for insertion into the page_restrictions field.
2809 * @param string[] $limit
2811 * @throws MWException
2814 protected static function flattenRestrictions( $limit ) {
2815 if ( !is_array( $limit ) ) {
2816 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2822 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2823 $bits[] = "$action=$restrictions";
2826 return implode( ':', $bits );
2830 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2831 * backwards compatibility, if you care about error reporting you should use
2832 * doDeleteArticleReal() instead.
2834 * Deletes the article with database consistency, writes logs, purges caches
2836 * @param string $reason Delete reason for deletion log
2837 * @param bool $suppress Suppress all revisions and log the deletion in
2838 * the suppression log instead of the deletion log
2839 * @param int $u1 Unused
2840 * @param bool $u2 Unused
2841 * @param array|string &$error Array of errors to append to
2842 * @param User $user The deleting user
2843 * @return bool True if successful
2845 public function doDeleteArticle(
2846 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2848 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2849 return $status->isGood();
2853 * Back-end article deletion
2854 * Deletes the article with database consistency, writes logs, purges caches
2858 * @param string $reason Delete reason for deletion log
2859 * @param bool $suppress Suppress all revisions and log the deletion in
2860 * the suppression log instead of the deletion log
2861 * @param int $u1 Unused
2862 * @param bool $u2 Unused
2863 * @param array|string &$error Array of errors to append to
2864 * @param User $user The deleting user
2865 * @return Status Status object; if successful, $status->value is the log_id of the
2866 * deletion log entry. If the page couldn't be deleted because it wasn't
2867 * found, $status is a non-fatal 'cannotdelete' error
2869 public function doDeleteArticleReal(
2870 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2872 global $wgUser, $wgContentHandlerUseDB;
2874 wfDebug( __METHOD__
. "\n" );
2876 $status = Status
::newGood();
2878 if ( $this->mTitle
->getDBkey() === '' ) {
2879 $status->error( 'cannotdelete',
2880 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2884 $user = is_null( $user ) ?
$wgUser : $user;
2885 if ( !Hooks
::run( 'ArticleDelete',
2886 [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2888 if ( $status->isOK() ) {
2889 // Hook aborted but didn't set a fatal status
2890 $status->fatal( 'delete-hook-aborted' );
2895 $dbw = wfGetDB( DB_MASTER
);
2896 $dbw->startAtomic( __METHOD__
);
2898 $this->loadPageData( self
::READ_LATEST
);
2899 $id = $this->getId();
2900 // T98706: lock the page from various other updates but avoid using
2901 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2902 // the revisions queries (which also JOIN on user). Only lock the page
2903 // row and CAS check on page_latest to see if the trx snapshot matches.
2904 $lockedLatest = $this->lockAndGetLatest();
2905 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2906 $dbw->endAtomic( __METHOD__
);
2907 // Page not there or trx snapshot is stale
2908 $status->error( 'cannotdelete',
2909 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2913 // Given the lock above, we can be confident in the title and page ID values
2914 $namespace = $this->getTitle()->getNamespace();
2915 $dbKey = $this->getTitle()->getDBkey();
2917 // At this point we are now comitted to returning an OK
2918 // status unless some DB query error or other exception comes up.
2919 // This way callers don't have to call rollback() if $status is bad
2920 // unless they actually try to catch exceptions (which is rare).
2922 // we need to remember the old content so we can use it to generate all deletion updates.
2924 $content = $this->getContent( Revision
::RAW
);
2925 } catch ( Exception
$ex ) {
2926 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2927 . $ex->getMessage() );
2932 // Bitfields to further suppress the content
2935 // This should be 15...
2936 $bitfield |
= Revision
::DELETED_TEXT
;
2937 $bitfield |
= Revision
::DELETED_COMMENT
;
2938 $bitfield |
= Revision
::DELETED_USER
;
2939 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2940 $deletionFields = [ $dbw->addQuotes( $bitfield ) . ' AS deleted' ];
2942 $deletionFields = [ 'rev_deleted AS deleted' ];
2945 // For now, shunt the revision data into the archive table.
2946 // Text is *not* removed from the text table; bulk storage
2947 // is left intact to avoid breaking block-compression or
2948 // immutable storage schemes.
2949 // In the future, we may keep revisions and mark them with
2950 // the rev_deleted field, which is reserved for this purpose.
2952 // Get all of the page revisions
2953 $fields = array_diff( Revision
::selectFields(), [ 'rev_deleted' ] );
2954 $res = $dbw->select(
2956 array_merge( $fields, $deletionFields ),
2957 [ 'rev_page' => $id ],
2961 // Build their equivalent archive rows
2963 foreach ( $res as $row ) {
2965 'ar_namespace' => $namespace,
2966 'ar_title' => $dbKey,
2967 'ar_comment' => $row->rev_comment
,
2968 'ar_user' => $row->rev_user
,
2969 'ar_user_text' => $row->rev_user_text
,
2970 'ar_timestamp' => $row->rev_timestamp
,
2971 'ar_minor_edit' => $row->rev_minor_edit
,
2972 'ar_rev_id' => $row->rev_id
,
2973 'ar_parent_id' => $row->rev_parent_id
,
2974 'ar_text_id' => $row->rev_text_id
,
2977 'ar_len' => $row->rev_len
,
2978 'ar_page_id' => $id,
2979 'ar_deleted' => $row->deleted
,
2980 'ar_sha1' => $row->rev_sha1
,
2982 if ( $wgContentHandlerUseDB ) {
2983 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2984 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2986 $rowsInsert[] = $rowInsert;
2988 // Copy them into the archive table
2989 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2990 // Save this so we can pass it to the ArticleDeleteComplete hook.
2991 $archivedRevisionCount = $dbw->affectedRows();
2993 // Clone the title and wikiPage, so we have the information we need when
2994 // we log and run the ArticleDeleteComplete hook.
2995 $logTitle = clone $this->mTitle
;
2996 $wikiPageBeforeDelete = clone $this;
2998 // Now that it's safely backed up, delete it
2999 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
3001 if ( !$dbw->cascadingDeletes() ) {
3002 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
3005 // Log the deletion, if the page was suppressed, put it in the suppression log instead
3006 $logtype = $suppress ?
'suppress' : 'delete';
3008 $logEntry = new ManualLogEntry( $logtype, 'delete' );
3009 $logEntry->setPerformer( $user );
3010 $logEntry->setTarget( $logTitle );
3011 $logEntry->setComment( $reason );
3012 $logid = $logEntry->insert();
3014 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
3015 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
3016 $logEntry->publish( $logid );
3019 $dbw->endAtomic( __METHOD__
);
3021 $this->doDeleteUpdates( $id, $content );
3023 Hooks
::run( 'ArticleDeleteComplete', [
3024 &$wikiPageBeforeDelete,
3030 $archivedRevisionCount
3032 $status->value
= $logid;
3034 // Show log excerpt on 404 pages rather than just a link
3035 $cache = ObjectCache
::getMainStashInstance();
3036 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
3037 $cache->set( $key, 1, $cache::TTL_DAY
);
3043 * Lock the page row for this title+id and return page_latest (or 0)
3045 * @return integer Returns 0 if no row was found with this title+id
3048 public function lockAndGetLatest() {
3049 return (int)wfGetDB( DB_MASTER
)->selectField(
3053 'page_id' => $this->getId(),
3054 // Typically page_id is enough, but some code might try to do
3055 // updates assuming the title is the same, so verify that
3056 'page_namespace' => $this->getTitle()->getNamespace(),
3057 'page_title' => $this->getTitle()->getDBkey()
3065 * Do some database updates after deletion
3067 * @param int $id The page_id value of the page being deleted
3068 * @param Content $content Optional page content to be used when determining
3069 * the required updates. This may be needed because $this->getContent()
3070 * may already return null when the page proper was deleted.
3072 public function doDeleteUpdates( $id, Content
$content = null ) {
3074 $countable = $this->isCountable();
3075 } catch ( Exception
$ex ) {
3076 // fallback for deleting broken pages for which we cannot load the content for
3077 // some reason. Note that doDeleteArticleReal() already logged this problem.
3081 // Update site status
3082 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3084 // Delete pagelinks, update secondary indexes, etc
3085 $updates = $this->getDeletionUpdates( $content );
3086 foreach ( $updates as $update ) {
3087 DeferredUpdates
::addUpdate( $update );
3090 // Reparse any pages transcluding this page
3091 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
3093 // Reparse any pages including this image
3094 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3095 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
3099 WikiPage
::onArticleDelete( $this->mTitle
);
3101 // Reset this object and the Title object
3102 $this->loadFromRow( false, self
::READ_LATEST
);
3105 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3109 * Roll back the most recent consecutive set of edits to a page
3110 * from the same user; fails if there are no eligible edits to
3111 * roll back to, e.g. user is the sole contributor. This function
3112 * performs permissions checks on $user, then calls commitRollback()
3113 * to do the dirty work
3115 * @todo Separate the business/permission stuff out from backend code
3116 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3118 * @param string $fromP Name of the user whose edits to rollback.
3119 * @param string $summary Custom summary. Set to default summary if empty.
3120 * @param string $token Rollback token.
3121 * @param bool $bot If true, mark all reverted edits as bot.
3123 * @param array $resultDetails Array contains result-specific array of additional values
3124 * 'alreadyrolled' : 'current' (rev)
3125 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3127 * @param User $user The user performing the rollback
3128 * @param array|null $tags Change tags to apply to the rollback
3129 * Callers are responsible for permission checks
3130 * (with ChangeTags::canAddTagsAccompanyingChange)
3132 * @return array Array of errors, each error formatted as
3133 * array(messagekey, param1, param2, ...).
3134 * On success, the array is empty. This array can also be passed to
3135 * OutputPage::showPermissionsErrorPage().
3137 public function doRollback(
3138 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3140 $resultDetails = null;
3142 // Check permissions
3143 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3144 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3145 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3147 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3148 $errors[] = [ 'sessionfailure' ];
3151 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3152 $errors[] = [ 'actionthrottledtext' ];
3155 // If there were errors, bail out now
3156 if ( !empty( $errors ) ) {
3160 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3164 * Backend implementation of doRollback(), please refer there for parameter
3165 * and return value documentation
3167 * NOTE: This function does NOT check ANY permissions, it just commits the
3168 * rollback to the DB. Therefore, you should only call this function direct-
3169 * ly if you want to use custom permissions checks. If you don't, use
3170 * doRollback() instead.
3171 * @param string $fromP Name of the user whose edits to rollback.
3172 * @param string $summary Custom summary. Set to default summary if empty.
3173 * @param bool $bot If true, mark all reverted edits as bot.
3175 * @param array $resultDetails Contains result-specific array of additional values
3176 * @param User $guser The user performing the rollback
3177 * @param array|null $tags Change tags to apply to the rollback
3178 * Callers are responsible for permission checks
3179 * (with ChangeTags::canAddTagsAccompanyingChange)
3183 public function commitRollback( $fromP, $summary, $bot,
3184 &$resultDetails, User
$guser, $tags = null
3186 global $wgUseRCPatrol, $wgContLang;
3188 $dbw = wfGetDB( DB_MASTER
);
3190 if ( wfReadOnly() ) {
3191 return [ [ 'readonlytext' ] ];
3194 // Get the last editor
3195 $current = $this->getRevision();
3196 if ( is_null( $current ) ) {
3197 // Something wrong... no page?
3198 return [ [ 'notanarticle' ] ];
3201 $from = str_replace( '_', ' ', $fromP );
3202 // User name given should match up with the top revision.
3203 // If the user was deleted then $from should be empty.
3204 if ( $from != $current->getUserText() ) {
3205 $resultDetails = [ 'current' => $current ];
3206 return [ [ 'alreadyrolled',
3207 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3208 htmlspecialchars( $fromP ),
3209 htmlspecialchars( $current->getUserText() )
3213 // Get the last edit not by this person...
3214 // Note: these may not be public values
3215 $user = intval( $current->getUser( Revision
::RAW
) );
3216 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3217 $s = $dbw->selectRow( 'revision',
3218 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3219 [ 'rev_page' => $current->getPage(),
3220 "rev_user != {$user} OR rev_user_text != {$user_text}"
3222 [ 'USE INDEX' => 'page_timestamp',
3223 'ORDER BY' => 'rev_timestamp DESC' ]
3225 if ( $s === false ) {
3226 // No one else ever edited this page
3227 return [ [ 'cantrollback' ] ];
3228 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3229 ||
$s->rev_deleted
& Revision
::DELETED_USER
3231 // Only admins can see this text
3232 return [ [ 'notvisiblerev' ] ];
3235 // Generate the edit summary if necessary
3236 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3237 if ( empty( $summary ) ) {
3238 if ( $from == '' ) { // no public user name
3239 $summary = wfMessage( 'revertpage-nouser' );
3241 $summary = wfMessage( 'revertpage' );
3245 // Allow the custom summary to use the same args as the default message
3247 $target->getUserText(), $from, $s->rev_id
,
3248 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3249 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3251 if ( $summary instanceof Message
) {
3252 $summary = $summary->params( $args )->inContentLanguage()->text();
3254 $summary = wfMsgReplaceArgs( $summary, $args );
3257 // Trim spaces on user supplied text
3258 $summary = trim( $summary );
3260 // Truncate for whole multibyte characters.
3261 $summary = $wgContLang->truncate( $summary, 255 );
3264 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3266 if ( $guser->isAllowed( 'minoredit' ) ) {
3267 $flags |
= EDIT_MINOR
;
3270 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3271 $flags |
= EDIT_FORCE_BOT
;
3274 $targetContent = $target->getContent();
3275 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3277 // Actually store the edit
3278 $status = $this->doEditContent(
3288 // Set patrolling and bot flag on the edits, which gets rollbacked.
3289 // This is done even on edit failure to have patrolling in that case (bug 62157).
3291 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3292 // Mark all reverted edits as bot
3296 if ( $wgUseRCPatrol ) {
3297 // Mark all reverted edits as patrolled
3298 $set['rc_patrolled'] = 1;
3301 if ( count( $set ) ) {
3302 $dbw->update( 'recentchanges', $set,
3304 'rc_cur_id' => $current->getPage(),
3305 'rc_user_text' => $current->getUserText(),
3306 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3312 if ( !$status->isOK() ) {
3313 return $status->getErrorsArray();
3316 // raise error, when the edit is an edit without a new version
3317 $statusRev = isset( $status->value
['revision'] )
3318 ?
$status->value
['revision']
3320 if ( !( $statusRev instanceof Revision
) ) {
3321 $resultDetails = [ 'current' => $current ];
3322 return [ [ 'alreadyrolled',
3323 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3324 htmlspecialchars( $fromP ),
3325 htmlspecialchars( $current->getUserText() )
3329 if ( $changingContentModel ) {
3330 // If the content model changed during the rollback,
3331 // make sure it gets logged to Special:Log/contentmodel
3332 $log = new ManualLogEntry( 'contentmodel', 'change' );
3333 $log->setPerformer( $guser );
3334 $log->setTarget( $this->mTitle
);
3335 $log->setComment( $summary );
3336 $log->setParameters( [
3337 '4::oldmodel' => $current->getContentModel(),
3338 '5::newmodel' => $targetContent->getModel(),
3341 $logId = $log->insert( $dbw );
3342 $log->publish( $logId );
3345 $revId = $statusRev->getId();
3347 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3350 'summary' => $summary,
3351 'current' => $current,
3352 'target' => $target,
3360 * The onArticle*() functions are supposed to be a kind of hooks
3361 * which should be called whenever any of the specified actions
3364 * This is a good place to put code to clear caches, for instance.
3366 * This is called on page move and undelete, as well as edit
3368 * @param Title $title
3370 public static function onArticleCreate( Title
$title ) {
3371 // Update existence markers on article/talk tabs...
3372 $other = $title->getOtherPage();
3374 $other->purgeSquid();
3376 $title->touchLinks();
3377 $title->purgeSquid();
3378 $title->deleteTitleProtection();
3380 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3382 if ( $title->getNamespace() == NS_CATEGORY
) {
3383 // Load the Category object, which will schedule a job to create
3384 // the category table row if necessary. Checking a replica DB is ok
3385 // here, in the worst case it'll run an unnecessary recount job on
3386 // a category that probably doesn't have many members.
3387 Category
::newFromTitle( $title )->getID();
3392 * Clears caches when article is deleted
3394 * @param Title $title
3396 public static function onArticleDelete( Title
$title ) {
3399 // Update existence markers on article/talk tabs...
3400 $other = $title->getOtherPage();
3402 $other->purgeSquid();
3404 $title->touchLinks();
3405 $title->purgeSquid();
3407 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3410 HTMLFileCache
::clearFileCache( $title );
3411 InfoAction
::invalidateCache( $title );
3414 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3415 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3417 if ( $wgContLang->hasVariants() ) {
3418 $wgContLang->updateConversionTable( $title );
3423 if ( $title->getNamespace() == NS_FILE
) {
3424 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3428 if ( $title->getNamespace() == NS_USER_TALK
) {
3429 $user = User
::newFromName( $title->getText(), false );
3431 $user->setNewtalk( false );
3436 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3440 * Purge caches on page update etc
3442 * @param Title $title
3443 * @param Revision|null $revision Revision that was just saved, may be null
3445 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3446 // Invalidate caches of articles which include this page
3447 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3449 // Invalidate the caches of all pages which redirect here
3450 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3452 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3454 // Purge CDN for this page only
3455 $title->purgeSquid();
3456 // Clear file cache for this page only
3457 HTMLFileCache
::clearFileCache( $title );
3459 $revid = $revision ?
$revision->getId() : null;
3460 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3461 InfoAction
::invalidateCache( $title, $revid );
3468 * Returns a list of categories this page is a member of.
3469 * Results will include hidden categories
3471 * @return TitleArray
3473 public function getCategories() {
3474 $id = $this->getId();
3476 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3479 $dbr = wfGetDB( DB_REPLICA
);
3480 $res = $dbr->select( 'categorylinks',
3481 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3482 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3483 // as not being aliases, and NS_CATEGORY is numeric
3484 [ 'cl_from' => $id ],
3487 return TitleArray
::newFromResult( $res );
3491 * Returns a list of hidden categories this page is a member of.
3492 * Uses the page_props and categorylinks tables.
3494 * @return array Array of Title objects
3496 public function getHiddenCategories() {
3498 $id = $this->getId();
3504 $dbr = wfGetDB( DB_REPLICA
);
3505 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3507 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3508 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3511 if ( $res !== false ) {
3512 foreach ( $res as $row ) {
3513 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3521 * Return an applicable autosummary if one exists for the given edit.
3522 * @param string|null $oldtext The previous text of the page.
3523 * @param string|null $newtext The submitted text of the page.
3524 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3525 * @return string An appropriate autosummary, or an empty string.
3527 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3529 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3530 // NOTE: stub for backwards-compatibility. assumes the given text is
3531 // wikitext. will break horribly if it isn't.
3533 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3535 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3536 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3537 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3539 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3543 * Auto-generates a deletion reason
3545 * @param bool &$hasHistory Whether the page has a history
3546 * @return string|bool String containing deletion reason or empty string, or boolean false
3547 * if no revision occurred
3549 public function getAutoDeleteReason( &$hasHistory ) {
3550 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3554 * Update all the appropriate counts in the category table, given that
3555 * we've added the categories $added and deleted the categories $deleted.
3557 * @param array $added The names of categories that were added
3558 * @param array $deleted The names of categories that were deleted
3559 * @param integer $id Page ID (this should be the original deleted page ID)
3561 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3562 $id = $id ?
: $this->getId();
3563 $dbw = wfGetDB( DB_MASTER
);
3564 $method = __METHOD__
;
3565 // Do this at the end of the commit to reduce lock wait timeouts
3566 $dbw->onTransactionPreCommitOrIdle(
3567 function () use ( $dbw, $added, $deleted, $id, $method ) {
3568 $ns = $this->getTitle()->getNamespace();
3570 $addFields = [ 'cat_pages = cat_pages + 1' ];
3571 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3572 if ( $ns == NS_CATEGORY
) {
3573 $addFields[] = 'cat_subcats = cat_subcats + 1';
3574 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3575 } elseif ( $ns == NS_FILE
) {
3576 $addFields[] = 'cat_files = cat_files + 1';
3577 $removeFields[] = 'cat_files = cat_files - 1';
3580 if ( count( $added ) ) {
3581 $existingAdded = $dbw->selectFieldValues(
3584 [ 'cat_title' => $added ],
3588 // For category rows that already exist, do a plain
3589 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3590 // to avoid creating gaps in the cat_id sequence.
3591 if ( count( $existingAdded ) ) {
3595 [ 'cat_title' => $existingAdded ],
3600 $missingAdded = array_diff( $added, $existingAdded );
3601 if ( count( $missingAdded ) ) {
3603 foreach ( $missingAdded as $cat ) {
3605 'cat_title' => $cat,
3607 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3608 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3621 if ( count( $deleted ) ) {
3625 [ 'cat_title' => $deleted ],
3630 foreach ( $added as $catName ) {
3631 $cat = Category
::newFromName( $catName );
3632 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3635 foreach ( $deleted as $catName ) {
3636 $cat = Category
::newFromName( $catName );
3637 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3640 // Refresh counts on categories that should be empty now, to
3641 // trigger possible deletion. Check master for the most
3642 // up-to-date cat_pages.
3643 if ( count( $deleted ) ) {
3644 $rows = $dbw->select(
3646 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3647 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3650 foreach ( $rows as $row ) {
3651 $cat = Category
::newFromRow( $row );
3652 $cat->refreshCounts();
3660 * Opportunistically enqueue link update jobs given fresh parser output if useful
3662 * @param ParserOutput $parserOutput Current version page output
3665 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3666 if ( wfReadOnly() ) {
3670 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3671 [ $this, $this->mTitle
, $parserOutput ]
3676 $config = RequestContext
::getMain()->getConfig();
3679 'isOpportunistic' => true,
3680 'rootJobTimestamp' => $parserOutput->getCacheTime()
3683 if ( $this->mTitle
->areRestrictionsCascading() ) {
3684 // If the page is cascade protecting, the links should really be up-to-date
3685 JobQueueGroup
::singleton()->lazyPush(
3686 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3688 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3689 // Assume the output contains "dynamic" time/random based magic words.
3690 // Only update pages that expired due to dynamic content and NOT due to edits
3691 // to referenced templates/files. When the cache expires due to dynamic content,
3692 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3693 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3694 // template/file edit already triggered recursive RefreshLinksJob jobs.
3695 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3696 // If a page is uncacheable, do not keep spamming a job for it.
3697 // Although it would be de-duplicated, it would still waste I/O.
3698 $cache = ObjectCache
::getLocalClusterInstance();
3699 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3700 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3701 if ( $cache->add( $key, time(), $ttl ) ) {
3702 JobQueueGroup
::singleton()->lazyPush(
3703 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3711 * Returns a list of updates to be performed when this page is deleted. The
3712 * updates should remove any information about this page from secondary data
3713 * stores such as links tables.
3715 * @param Content|null $content Optional Content object for determining the
3716 * necessary updates.
3717 * @return DataUpdate[]
3719 public function getDeletionUpdates( Content
$content = null ) {
3721 // load content object, which may be used to determine the necessary updates.
3722 // XXX: the content may not be needed to determine the updates.
3724 $content = $this->getContent( Revision
::RAW
);
3725 } catch ( Exception
$ex ) {
3726 // If we can't load the content, something is wrong. Perhaps that's why
3727 // the user is trying to delete the page, so let's not fail in that case.
3728 // Note that doDeleteArticleReal() will already have logged an issue with
3729 // loading the content.
3736 $updates = $content->getDeletionUpdates( $this );
3739 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3744 * Whether this content displayed on this page
3745 * comes from the local database
3750 public function isLocal() {