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';
87 * Constructor and clear the article
88 * @param Title $title Reference to a Title object.
90 public function __construct( Title
$title ) {
91 $this->mTitle
= $title;
95 * Makes sure that the mTitle object is cloned
96 * to the newly cloned WikiPage.
98 public function __clone() {
99 $this->mTitle
= clone $this->mTitle
;
103 * Create a WikiPage object of the appropriate class for the given title.
105 * @param Title $title
107 * @throws MWException
108 * @return WikiPage|WikiCategoryPage|WikiFilePage
110 public static function factory( Title
$title ) {
111 $ns = $title->getNamespace();
113 if ( $ns == NS_MEDIA
) {
114 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
115 } elseif ( $ns < 0 ) {
116 throw new MWException( "Invalid or virtual namespace $ns given." );
121 $page = new WikiFilePage( $title );
124 $page = new WikiCategoryPage( $title );
127 $page = new WikiPage( $title );
134 * Constructor from a page id
136 * @param int $id Article ID to load
137 * @param string|int $from One of the following values:
138 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
139 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
141 * @return WikiPage|null
143 public static function newFromID( $id, $from = 'fromdb' ) {
144 // page id's are never 0 or negative, see bug 61166
149 $from = self
::convertSelectType( $from );
150 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_REPLICA
);
151 $row = $db->selectRow(
152 'page', self
::selectFields(), [ 'page_id' => $id ], __METHOD__
);
156 return self
::newFromRow( $row, $from );
160 * Constructor from a database row
163 * @param object $row Database row containing at least fields returned by selectFields().
164 * @param string|int $from Source of $data:
165 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
166 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
167 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
170 public static function newFromRow( $row, $from = 'fromdb' ) {
171 $page = self
::factory( Title
::newFromRow( $row ) );
172 $page->loadFromRow( $row, $from );
177 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
179 * @param object|string|int $type
182 private static function convertSelectType( $type ) {
185 return self
::READ_NORMAL
;
187 return self
::READ_LATEST
;
189 return self
::READ_LOCKING
;
191 // It may already be an integer or whatever else
197 * @todo Move this UI stuff somewhere else
199 * @see ContentHandler::getActionOverrides
201 public function getActionOverrides() {
202 return $this->getContentHandler()->getActionOverrides();
206 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
208 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
210 * @return ContentHandler
214 public function getContentHandler() {
215 return ContentHandler
::getForModelID( $this->getContentModel() );
219 * Get the title object of the article
220 * @return Title Title object of this page
222 public function getTitle() {
223 return $this->mTitle
;
230 public function clear() {
231 $this->mDataLoaded
= false;
232 $this->mDataLoadedFrom
= self
::READ_NONE
;
234 $this->clearCacheFields();
238 * Clear the object cache fields
241 protected function clearCacheFields() {
243 $this->mRedirectTarget
= null; // Title object if set
244 $this->mLastRevision
= null; // Latest revision
245 $this->mTouched
= '19700101000000';
246 $this->mLinksUpdated
= '19700101000000';
247 $this->mTimestamp
= '';
248 $this->mIsRedirect
= false;
249 $this->mLatest
= false;
250 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
251 // the requested rev ID and content against the cached one for equality. For most
252 // content types, the output should not change during the lifetime of this cache.
253 // Clearing it can cause extra parses on edit for no reason.
257 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
261 public function clearPreparedEdit() {
262 $this->mPreparedEdit
= false;
266 * Return the list of revision fields that should be selected to create
271 public static function selectFields() {
272 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
283 'page_links_updated',
288 if ( $wgContentHandlerUseDB ) {
289 $fields[] = 'page_content_model';
292 if ( $wgPageLanguageUseDB ) {
293 $fields[] = 'page_lang';
300 * Fetch a page record with the given conditions
301 * @param IDatabase $dbr
302 * @param array $conditions
303 * @param array $options
304 * @return object|bool Database result resource, or false on failure
306 protected function pageData( $dbr, $conditions, $options = [] ) {
307 $fields = self
::selectFields();
309 Hooks
::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
311 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
313 Hooks
::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
319 * Fetch a page record matching the Title object's namespace and title
320 * using a sanitized title string
322 * @param IDatabase $dbr
323 * @param Title $title
324 * @param array $options
325 * @return object|bool Database result resource, or false on failure
327 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
328 return $this->pageData( $dbr, [
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ], $options );
334 * Fetch a page record matching the requested ID
336 * @param IDatabase $dbr
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
341 public function pageDataFromId( $dbr, $id, $options = [] ) {
342 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
346 * Load the object from a given source by title
348 * @param object|string|int $from One of the following:
349 * - A DB query result object.
350 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
351 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
352 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
353 * using SELECT FOR UPDATE.
357 public function loadPageData( $from = 'fromdb' ) {
358 $from = self
::convertSelectType( $from );
359 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
360 // We already have the data from the correct location, no need to load it twice.
364 if ( is_int( $from ) ) {
365 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
366 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
369 && $index == DB_REPLICA
370 && wfGetLB()->getServerCount() > 1
371 && wfGetLB()->hasOrMadeRecentMasterChanges()
373 $from = self
::READ_LATEST
;
374 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
375 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
378 // No idea from where the caller got this data, assume replica DB.
380 $from = self
::READ_NORMAL
;
383 $this->loadFromRow( $data, $from );
387 * Load the object from a database row
390 * @param object|bool $data DB row containing fields returned by selectFields() or false
391 * @param string|int $from One of the following:
392 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
393 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
394 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
395 * the master DB using SELECT FOR UPDATE
397 public function loadFromRow( $data, $from ) {
398 $lc = LinkCache
::singleton();
399 $lc->clearLink( $this->mTitle
);
402 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
404 $this->mTitle
->loadFromRow( $data );
406 // Old-fashioned restrictions
407 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
409 $this->mId
= intval( $data->page_id
);
410 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
411 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
412 $this->mIsRedirect
= intval( $data->page_is_redirect
);
413 $this->mLatest
= intval( $data->page_latest
);
414 // Bug 37225: $latest may no longer match the cached latest Revision object.
415 // Double-check the ID of any cached latest Revision object for consistency.
416 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
417 $this->mLastRevision
= null;
418 $this->mTimestamp
= '';
421 $lc->addBadLinkObj( $this->mTitle
);
423 $this->mTitle
->loadFromRow( false );
425 $this->clearCacheFields();
430 $this->mDataLoaded
= true;
431 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
435 * @return int Page ID
437 public function getId() {
438 if ( !$this->mDataLoaded
) {
439 $this->loadPageData();
445 * @return bool Whether or not the page exists in the database
447 public function exists() {
448 if ( !$this->mDataLoaded
) {
449 $this->loadPageData();
451 return $this->mId
> 0;
455 * Check if this page is something we're going to be showing
456 * some sort of sensible content for. If we return false, page
457 * views (plain action=view) will return an HTTP 404 response,
458 * so spiders and robots can know they're following a bad link.
462 public function hasViewableContent() {
463 return $this->mTitle
->isKnown();
467 * Tests if the article content represents a redirect
471 public function isRedirect() {
472 if ( !$this->mDataLoaded
) {
473 $this->loadPageData();
476 return (bool)$this->mIsRedirect
;
480 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
482 * Will use the revisions actual content model if the page exists,
483 * and the page's default if the page doesn't exist yet.
489 public function getContentModel() {
490 if ( $this->exists() ) {
491 // look at the revision's actual content model
492 $rev = $this->getRevision();
494 if ( $rev !== null ) {
495 return $rev->getContentModel();
497 $title = $this->mTitle
->getPrefixedDBkey();
498 wfWarn( "Page $title exists but has no (visible) revisions!" );
502 // use the default model for this page
503 return $this->mTitle
->getContentModel();
507 * Loads page_touched and returns a value indicating if it should be used
508 * @return bool True if this page exists and is not a redirect
510 public function checkTouched() {
511 if ( !$this->mDataLoaded
) {
512 $this->loadPageData();
514 return ( $this->mId
&& !$this->mIsRedirect
);
518 * Get the page_touched field
519 * @return string Containing GMT timestamp
521 public function getTouched() {
522 if ( !$this->mDataLoaded
) {
523 $this->loadPageData();
525 return $this->mTouched
;
529 * Get the page_links_updated field
530 * @return string|null Containing GMT timestamp
532 public function getLinksTimestamp() {
533 if ( !$this->mDataLoaded
) {
534 $this->loadPageData();
536 return $this->mLinksUpdated
;
540 * Get the page_latest field
541 * @return int The rev_id of current revision
543 public function getLatest() {
544 if ( !$this->mDataLoaded
) {
545 $this->loadPageData();
547 return (int)$this->mLatest
;
551 * Get the Revision object of the oldest revision
552 * @return Revision|null
554 public function getOldestRevision() {
556 // Try using the replica DB first, then try the master
558 $db = wfGetDB( DB_REPLICA
);
559 $revSelectFields = Revision
::selectFields();
562 while ( $continue ) {
563 $row = $db->selectRow(
564 [ 'page', 'revision' ],
567 'page_namespace' => $this->mTitle
->getNamespace(),
568 'page_title' => $this->mTitle
->getDBkey(),
573 'ORDER BY' => 'rev_timestamp ASC'
580 $db = wfGetDB( DB_MASTER
);
585 return $row ? Revision
::newFromRow( $row ) : null;
589 * Loads everything except the text
590 * This isn't necessary for all uses, so it's only done if needed.
592 protected function loadLastEdit() {
593 if ( $this->mLastRevision
!== null ) {
594 return; // already loaded
597 $latest = $this->getLatest();
599 return; // page doesn't exist or is missing page_latest info
602 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
603 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
604 // includes the latest changes committed. This is true even within REPEATABLE-READ
605 // transactions, where S1 normally only sees changes committed before the first S1
606 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
607 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
608 // happened after the first S1 SELECT.
609 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
610 $flags = Revision
::READ_LOCKING
;
611 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
612 // Bug T93976: if page_latest was loaded from the master, fetch the
613 // revision from there as well, as it may not exist yet on a replica DB.
614 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
615 $flags = Revision
::READ_LATEST
;
619 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
620 if ( $revision ) { // sanity
621 $this->setLastEdit( $revision );
626 * Set the latest revision
627 * @param Revision $revision
629 protected function setLastEdit( Revision
$revision ) {
630 $this->mLastRevision
= $revision;
631 $this->mTimestamp
= $revision->getTimestamp();
635 * Get the latest revision
636 * @return Revision|null
638 public function getRevision() {
639 $this->loadLastEdit();
640 if ( $this->mLastRevision
) {
641 return $this->mLastRevision
;
647 * Get the content of the current revision. No side-effects...
649 * @param int $audience One of:
650 * Revision::FOR_PUBLIC to be displayed to all users
651 * Revision::FOR_THIS_USER to be displayed to $wgUser
652 * Revision::RAW get the text regardless of permissions
653 * @param User $user User object to check for, only if FOR_THIS_USER is passed
654 * to the $audience parameter
655 * @return Content|null The content of the current revision
659 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
660 $this->loadLastEdit();
661 if ( $this->mLastRevision
) {
662 return $this->mLastRevision
->getContent( $audience, $user );
668 * Get the text of the current revision. No side-effects...
670 * @param int $audience One of:
671 * Revision::FOR_PUBLIC to be displayed to all users
672 * Revision::FOR_THIS_USER to be displayed to the given user
673 * Revision::RAW get the text regardless of permissions
674 * @param User $user User object to check for, only if FOR_THIS_USER is passed
675 * to the $audience parameter
676 * @return string|bool The text of the current revision
677 * @deprecated since 1.21, getContent() should be used instead.
679 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
680 ContentHandler
::deprecated( __METHOD__
, '1.21' );
682 $this->loadLastEdit();
683 if ( $this->mLastRevision
) {
684 return $this->mLastRevision
->getText( $audience, $user );
690 * @return string MW timestamp of last article revision
692 public function getTimestamp() {
693 // Check if the field has been filled by WikiPage::setTimestamp()
694 if ( !$this->mTimestamp
) {
695 $this->loadLastEdit();
698 return wfTimestamp( TS_MW
, $this->mTimestamp
);
702 * Set the page timestamp (use only to avoid DB queries)
703 * @param string $ts MW timestamp of last article revision
706 public function setTimestamp( $ts ) {
707 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
711 * @param int $audience One of:
712 * Revision::FOR_PUBLIC to be displayed to all users
713 * Revision::FOR_THIS_USER to be displayed to the given user
714 * Revision::RAW get the text regardless of permissions
715 * @param User $user User object to check for, only if FOR_THIS_USER is passed
716 * to the $audience parameter
717 * @return int User ID for the user that made the last article revision
719 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
720 $this->loadLastEdit();
721 if ( $this->mLastRevision
) {
722 return $this->mLastRevision
->getUser( $audience, $user );
729 * Get the User object of the user who created the page
730 * @param int $audience One of:
731 * Revision::FOR_PUBLIC to be displayed to all users
732 * Revision::FOR_THIS_USER to be displayed to the given user
733 * Revision::RAW get the text regardless of permissions
734 * @param User $user User object to check for, only if FOR_THIS_USER is passed
735 * to the $audience parameter
738 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
739 $revision = $this->getOldestRevision();
741 $userName = $revision->getUserText( $audience, $user );
742 return User
::newFromName( $userName, false );
749 * @param int $audience One of:
750 * Revision::FOR_PUBLIC to be displayed to all users
751 * Revision::FOR_THIS_USER to be displayed to the given user
752 * Revision::RAW get the text regardless of permissions
753 * @param User $user User object to check for, only if FOR_THIS_USER is passed
754 * to the $audience parameter
755 * @return string Username of the user that made the last article revision
757 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
758 $this->loadLastEdit();
759 if ( $this->mLastRevision
) {
760 return $this->mLastRevision
->getUserText( $audience, $user );
767 * @param int $audience One of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to the given user
770 * Revision::RAW get the text regardless of permissions
771 * @param User $user User object to check for, only if FOR_THIS_USER is passed
772 * to the $audience parameter
773 * @return string Comment stored for the last article revision
775 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
776 $this->loadLastEdit();
777 if ( $this->mLastRevision
) {
778 return $this->mLastRevision
->getComment( $audience, $user );
785 * Returns true if last revision was marked as "minor edit"
787 * @return bool Minor edit indicator for the last article revision.
789 public function getMinorEdit() {
790 $this->loadLastEdit();
791 if ( $this->mLastRevision
) {
792 return $this->mLastRevision
->isMinor();
799 * Determine whether a page would be suitable for being counted as an
800 * article in the site_stats table based on the title & its content
802 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
803 * if false, the current database state will be used
806 public function isCountable( $editInfo = false ) {
807 global $wgArticleCountMethod;
809 if ( !$this->mTitle
->isContentPage() ) {
814 $content = $editInfo->pstContent
;
816 $content = $this->getContent();
819 if ( !$content ||
$content->isRedirect() ) {
825 if ( $wgArticleCountMethod === 'link' ) {
826 // nasty special case to avoid re-parsing to detect links
829 // ParserOutput::getLinks() is a 2D array of page links, so
830 // to be really correct we would need to recurse in the array
831 // but the main array should only have items in it if there are
833 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
835 $hasLinks = (bool)wfGetDB( DB_REPLICA
)->selectField( 'pagelinks', 1,
836 [ 'pl_from' => $this->getId() ], __METHOD__
);
840 return $content->isCountable( $hasLinks );
844 * If this page is a redirect, get its target
846 * The target will be fetched from the redirect table if possible.
847 * If this page doesn't have an entry there, call insertRedirect()
848 * @return Title|null Title object, or null if this page is not a redirect
850 public function getRedirectTarget() {
851 if ( !$this->mTitle
->isRedirect() ) {
855 if ( $this->mRedirectTarget
!== null ) {
856 return $this->mRedirectTarget
;
859 // Query the redirect table
860 $dbr = wfGetDB( DB_REPLICA
);
861 $row = $dbr->selectRow( 'redirect',
862 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
863 [ 'rd_from' => $this->getId() ],
867 // rd_fragment and rd_interwiki were added later, populate them if empty
868 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
869 $this->mRedirectTarget
= Title
::makeTitle(
870 $row->rd_namespace
, $row->rd_title
,
871 $row->rd_fragment
, $row->rd_interwiki
873 return $this->mRedirectTarget
;
876 // This page doesn't have an entry in the redirect table
877 $this->mRedirectTarget
= $this->insertRedirect();
878 return $this->mRedirectTarget
;
882 * Insert an entry for this page into the redirect table if the content is a redirect
884 * The database update will be deferred via DeferredUpdates
886 * Don't call this function directly unless you know what you're doing.
887 * @return Title|null Title object or null if not a redirect
889 public function insertRedirect() {
890 $content = $this->getContent();
891 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
896 // Update the DB post-send if the page has not cached since now
898 $latest = $this->getLatest();
899 DeferredUpdates
::addCallableUpdate(
900 function () use ( $that, $retval, $latest ) {
901 $that->insertRedirectEntry( $retval, $latest );
903 DeferredUpdates
::POSTSEND
,
911 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
912 * @param Title $rt Redirect target
913 * @param int|null $oldLatest Prior page_latest for check and set
915 public function insertRedirectEntry( Title
$rt, $oldLatest = null ) {
916 $dbw = wfGetDB( DB_MASTER
);
917 $dbw->startAtomic( __METHOD__
);
919 if ( !$oldLatest ||
$oldLatest == $this->lockAndGetLatest() ) {
920 $dbw->replace( 'redirect',
923 'rd_from' => $this->getId(),
924 'rd_namespace' => $rt->getNamespace(),
925 'rd_title' => $rt->getDBkey(),
926 'rd_fragment' => $rt->getFragment(),
927 'rd_interwiki' => $rt->getInterwiki(),
933 $dbw->endAtomic( __METHOD__
);
937 * Get the Title object or URL this page redirects to
939 * @return bool|Title|string False, Title of in-wiki target, or string with URL
941 public function followRedirect() {
942 return $this->getRedirectURL( $this->getRedirectTarget() );
946 * Get the Title object or URL to use for a redirect. We use Title
947 * objects for same-wiki, non-special redirects and URLs for everything
949 * @param Title $rt Redirect target
950 * @return bool|Title|string False, Title object of local target, or string with URL
952 public function getRedirectURL( $rt ) {
957 if ( $rt->isExternal() ) {
958 if ( $rt->isLocal() ) {
959 // Offsite wikis need an HTTP redirect.
960 // This can be hard to reverse and may produce loops,
961 // so they may be disabled in the site configuration.
962 $source = $this->mTitle
->getFullURL( 'redirect=no' );
963 return $rt->getFullURL( [ 'rdfrom' => $source ] );
965 // External pages without "local" bit set are not valid
971 if ( $rt->isSpecialPage() ) {
972 // Gotta handle redirects to special pages differently:
973 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
974 // Some pages are not valid targets.
975 if ( $rt->isValidRedirectTarget() ) {
976 return $rt->getFullURL();
986 * Get a list of users who have edited this article, not including the user who made
987 * the most recent revision, which you can get from $article->getUser() if you want it
988 * @return UserArrayFromResult
990 public function getContributors() {
991 // @todo FIXME: This is expensive; cache this info somewhere.
993 $dbr = wfGetDB( DB_REPLICA
);
995 if ( $dbr->implicitGroupby() ) {
996 $realNameField = 'user_real_name';
998 $realNameField = 'MIN(user_real_name) AS user_real_name';
1001 $tables = [ 'revision', 'user' ];
1004 'user_id' => 'rev_user',
1005 'user_name' => 'rev_user_text',
1007 'timestamp' => 'MAX(rev_timestamp)',
1010 $conds = [ 'rev_page' => $this->getId() ];
1012 // The user who made the top revision gets credited as "this page was last edited by
1013 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1014 $user = $this->getUser();
1016 $conds[] = "rev_user != $user";
1018 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1022 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1025 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1029 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1030 'ORDER BY' => 'timestamp DESC',
1033 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1034 return new UserArrayFromResult( $res );
1038 * Should the parser cache be used?
1040 * @param ParserOptions $parserOptions ParserOptions to check
1044 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1045 return $parserOptions->getStubThreshold() == 0
1047 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1048 && $this->getContentHandler()->isParserCacheSupported();
1052 * Get a ParserOutput for the given ParserOptions and revision ID.
1054 * The parser cache will be used if possible. Cache misses that result
1055 * in parser runs are debounced with PoolCounter.
1058 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1059 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1060 * get the current revision (default value)
1061 * @param bool $forceParse Force reindexing, regardless of cache settings
1062 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1064 public function getParserOutput(
1065 ParserOptions
$parserOptions, $oldid = null, $forceParse = false
1068 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1069 wfDebug( __METHOD__
.
1070 ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1071 if ( $parserOptions->getStubThreshold() ) {
1072 wfIncrStats( 'pcache.miss.stub' );
1075 if ( $useParserCache ) {
1076 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1077 if ( $parserOutput !== false ) {
1078 return $parserOutput;
1082 if ( $oldid === null ||
$oldid === 0 ) {
1083 $oldid = $this->getLatest();
1086 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1089 return $pool->getParserOutput();
1093 * Do standard deferred updates after page view (existing or missing page)
1094 * @param User $user The relevant user
1095 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1097 public function doViewUpdates( User
$user, $oldid = 0 ) {
1098 if ( wfReadOnly() ) {
1102 Hooks
::run( 'PageViewUpdates', [ $this, $user ] );
1103 // Update newtalk / watchlist notification status
1105 $user->clearNotification( $this->mTitle
, $oldid );
1106 } catch ( DBError
$e ) {
1107 // Avoid outage if the master is not reachable
1108 MWExceptionHandler
::logException( $e );
1113 * Perform the actions of a page purging
1116 public function doPurge() {
1117 if ( !Hooks
::run( 'ArticlePurge', [ &$this ] ) ) {
1121 $this->mTitle
->invalidateCache();
1124 HTMLFileCache
::clearFileCache( $this->getTitle() );
1125 // Send purge after above page_touched update was committed
1126 DeferredUpdates
::addUpdate(
1127 new CdnCacheUpdate( $this->mTitle
->getCdnUrls() ),
1128 DeferredUpdates
::PRESEND
1131 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1132 // @todo move this logic to MessageCache
1133 if ( $this->exists() ) {
1134 // NOTE: use transclusion text for messages.
1135 // This is consistent with MessageCache::getMsgFromNamespace()
1137 $content = $this->getContent();
1138 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1140 if ( $text === null ) {
1147 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1154 * Insert a new empty page record for this article.
1155 * This *must* be followed up by creating a revision
1156 * and running $this->updateRevisionOn( ... );
1157 * or else the record will be left in a funky state.
1158 * Best if all done inside a transaction.
1160 * @param IDatabase $dbw
1161 * @param int|null $pageId Custom page ID that will be used for the insert statement
1163 * @return bool|int The newly created page_id key; false if the row was not
1164 * inserted, e.g. because the title already existed or because the specified
1165 * page ID is already in use.
1167 public function insertOn( $dbw, $pageId = null ) {
1168 $pageIdForInsert = $pageId ?
: $dbw->nextSequenceValue( 'page_page_id_seq' );
1172 'page_id' => $pageIdForInsert,
1173 'page_namespace' => $this->mTitle
->getNamespace(),
1174 'page_title' => $this->mTitle
->getDBkey(),
1175 'page_restrictions' => '',
1176 'page_is_redirect' => 0, // Will set this shortly...
1178 'page_random' => wfRandom(),
1179 'page_touched' => $dbw->timestamp(),
1180 'page_latest' => 0, // Fill this in shortly...
1181 'page_len' => 0, // Fill this in shortly...
1187 if ( $dbw->affectedRows() > 0 ) {
1188 $newid = $pageId ?
: $dbw->insertId();
1189 $this->mId
= $newid;
1190 $this->mTitle
->resetArticleID( $newid );
1194 return false; // nothing changed
1199 * Update the page record to point to a newly saved revision.
1201 * @param IDatabase $dbw
1202 * @param Revision $revision For ID number, and text used to set
1203 * length and redirect status fields
1204 * @param int $lastRevision If given, will not overwrite the page field
1205 * when different from the currently set value.
1206 * Giving 0 indicates the new page flag should be set on.
1207 * @param bool $lastRevIsRedirect If given, will optimize adding and
1208 * removing rows in redirect table.
1209 * @return bool Success; false if the page row was missing or page_latest changed
1211 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1212 $lastRevIsRedirect = null
1214 global $wgContentHandlerUseDB;
1216 // Assertion to try to catch T92046
1217 if ( (int)$revision->getId() === 0 ) {
1218 throw new InvalidArgumentException(
1219 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1223 $content = $revision->getContent();
1224 $len = $content ?
$content->getSize() : 0;
1225 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1227 $conditions = [ 'page_id' => $this->getId() ];
1229 if ( !is_null( $lastRevision ) ) {
1230 // An extra check against threads stepping on each other
1231 $conditions['page_latest'] = $lastRevision;
1235 'page_latest' => $revision->getId(),
1236 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1237 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1238 'page_is_redirect' => $rt !== null ?
1 : 0,
1242 if ( $wgContentHandlerUseDB ) {
1243 $row['page_content_model'] = $revision->getContentModel();
1246 $dbw->update( 'page',
1251 $result = $dbw->affectedRows() > 0;
1253 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1254 $this->setLastEdit( $revision );
1255 $this->mLatest
= $revision->getId();
1256 $this->mIsRedirect
= (bool)$rt;
1257 // Update the LinkCache.
1258 LinkCache
::singleton()->addGoodLinkObj(
1264 $revision->getContentModel()
1272 * Add row to the redirect table if this is a redirect, remove otherwise.
1274 * @param IDatabase $dbw
1275 * @param Title $redirectTitle Title object pointing to the redirect target,
1276 * or NULL if this is not a redirect
1277 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1278 * removing rows in redirect table.
1279 * @return bool True on success, false on failure
1282 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1283 // Always update redirects (target link might have changed)
1284 // Update/Insert if we don't know if the last revision was a redirect or not
1285 // Delete if changing from redirect to non-redirect
1286 $isRedirect = !is_null( $redirectTitle );
1288 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1292 if ( $isRedirect ) {
1293 $this->insertRedirectEntry( $redirectTitle );
1295 // This is not a redirect, remove row from redirect table
1296 $where = [ 'rd_from' => $this->getId() ];
1297 $dbw->delete( 'redirect', $where, __METHOD__
);
1300 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1301 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1304 return ( $dbw->affectedRows() != 0 );
1308 * If the given revision is newer than the currently set page_latest,
1309 * update the page record. Otherwise, do nothing.
1311 * @deprecated since 1.24, use updateRevisionOn instead
1313 * @param IDatabase $dbw
1314 * @param Revision $revision
1317 public function updateIfNewerOn( $dbw, $revision ) {
1319 $row = $dbw->selectRow(
1320 [ 'revision', 'page' ],
1321 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1323 'page_id' => $this->getId(),
1324 'page_latest=rev_id' ],
1328 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1331 $prev = $row->rev_id
;
1332 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1334 // No or missing previous revision; mark the page as new
1336 $lastRevIsRedirect = null;
1339 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1345 * Get the content that needs to be saved in order to undo all revisions
1346 * between $undo and $undoafter. Revisions must belong to the same page,
1347 * must exist and must not be deleted
1348 * @param Revision $undo
1349 * @param Revision $undoafter Must be an earlier revision than $undo
1350 * @return Content|bool Content on success, false on failure
1352 * Before we had the Content object, this was done in getUndoText
1354 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1355 $handler = $undo->getContentHandler();
1356 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1360 * Returns true if this page's content model supports sections.
1364 * @todo The skin should check this and not offer section functionality if
1365 * sections are not supported.
1366 * @todo The EditPage should check this and not offer section functionality
1367 * if sections are not supported.
1369 public function supportsSections() {
1370 return $this->getContentHandler()->supportsSections();
1374 * @param string|number|null|bool $sectionId Section identifier as a number or string
1375 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1376 * or 'new' for a new section.
1377 * @param Content $sectionContent New content of the section.
1378 * @param string $sectionTitle New section's subject, only if $section is "new".
1379 * @param string $edittime Revision timestamp or null to use the current revision.
1381 * @throws MWException
1382 * @return Content|null New complete article content, or null if error.
1385 * @deprecated since 1.24, use replaceSectionAtRev instead
1387 public function replaceSectionContent(
1388 $sectionId, Content
$sectionContent, $sectionTitle = '', $edittime = null
1392 if ( $edittime && $sectionId !== 'new' ) {
1393 $dbr = wfGetDB( DB_REPLICA
);
1394 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1395 // Try the master if this thread may have just added it.
1396 // This could be abstracted into a Revision method, but we don't want
1397 // to encourage loading of revisions by timestamp.
1399 && wfGetLB()->getServerCount() > 1
1400 && wfGetLB()->hasOrMadeRecentMasterChanges()
1402 $dbw = wfGetDB( DB_MASTER
);
1403 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1406 $baseRevId = $rev->getId();
1410 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1414 * @param string|number|null|bool $sectionId Section identifier as a number or string
1415 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1416 * or 'new' for a new section.
1417 * @param Content $sectionContent New content of the section.
1418 * @param string $sectionTitle New section's subject, only if $section is "new".
1419 * @param int|null $baseRevId
1421 * @throws MWException
1422 * @return Content|null New complete article content, or null if error.
1426 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1427 $sectionTitle = '', $baseRevId = null
1430 if ( strval( $sectionId ) === '' ) {
1431 // Whole-page edit; let the whole text through
1432 $newContent = $sectionContent;
1434 if ( !$this->supportsSections() ) {
1435 throw new MWException( "sections not supported for content model " .
1436 $this->getContentHandler()->getModelID() );
1439 // Bug 30711: always use current version when adding a new section
1440 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1441 $oldContent = $this->getContent();
1443 $rev = Revision
::newFromId( $baseRevId );
1445 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1446 $this->getId() . "; section: $sectionId)\n" );
1450 $oldContent = $rev->getContent();
1453 if ( !$oldContent ) {
1454 wfDebug( __METHOD__
. ": no page text\n" );
1458 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1465 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1467 * @return int Updated $flags
1469 public function checkFlags( $flags ) {
1470 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1471 if ( $this->exists() ) {
1472 $flags |
= EDIT_UPDATE
;
1482 * Change an existing article or create a new article. Updates RC and all necessary caches,
1483 * optionally via the deferred update array.
1485 * @param string $text New text
1486 * @param string $summary Edit summary
1487 * @param int $flags Bitfield:
1489 * Article is known or assumed to be non-existent, create a new one
1491 * Article is known or assumed to be pre-existing, update it
1493 * Mark this edit minor, if the user is allowed to do so
1495 * Do not log the change in recentchanges
1497 * Mark the edit a "bot" edit regardless of user rights
1499 * Fill in blank summaries with generated text where possible
1501 * Signal that the page retrieve/save cycle happened entirely in this request.
1503 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1504 * article will be detected. If EDIT_UPDATE is specified and the article
1505 * doesn't exist, the function will return an edit-gone-missing error. If
1506 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1507 * error will be returned. These two conditions are also possible with
1508 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1510 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1511 * This is not the parent revision ID, rather the revision ID for older
1512 * content used as the source for a rollback, for example.
1513 * @param User $user The user doing the edit
1515 * @throws MWException
1516 * @return Status Possible errors:
1517 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1518 * set the fatal flag of $status
1519 * edit-gone-missing: In update mode, but the article didn't exist.
1520 * edit-conflict: In update mode, the article changed unexpectedly.
1521 * edit-no-change: Warning that the text was the same as before.
1522 * edit-already-exists: In creation mode, but the article already exists.
1524 * Extensions may define additional errors.
1526 * $return->value will contain an associative array with members as follows:
1527 * new: Boolean indicating if the function attempted to create a new article.
1528 * revision: The revision object for the inserted revision, or null.
1530 * Compatibility note: this function previously returned a boolean value
1531 * indicating success/failure
1533 * @deprecated since 1.21: use doEditContent() instead.
1535 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1536 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1538 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1540 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1544 * Change an existing article or create a new article. Updates RC and all necessary caches,
1545 * optionally via the deferred update array.
1547 * @param Content $content New content
1548 * @param string $summary Edit summary
1549 * @param int $flags Bitfield:
1551 * Article is known or assumed to be non-existent, create a new one
1553 * Article is known or assumed to be pre-existing, update it
1555 * Mark this edit minor, if the user is allowed to do so
1557 * Do not log the change in recentchanges
1559 * Mark the edit a "bot" edit regardless of user rights
1561 * Fill in blank summaries with generated text where possible
1563 * Signal that the page retrieve/save cycle happened entirely in this request.
1565 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1566 * article will be detected. If EDIT_UPDATE is specified and the article
1567 * doesn't exist, the function will return an edit-gone-missing error. If
1568 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1569 * error will be returned. These two conditions are also possible with
1570 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1572 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1573 * This is not the parent revision ID, rather the revision ID for older
1574 * content used as the source for a rollback, for example.
1575 * @param User $user The user doing the edit
1576 * @param string $serialFormat Format for storing the content in the
1578 * @param array|null $tags Change tags to apply to this edit
1579 * Callers are responsible for permission checks
1580 * (with ChangeTags::canAddTagsAccompanyingChange)
1582 * @throws MWException
1583 * @return Status Possible errors:
1584 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1585 * set the fatal flag of $status.
1586 * edit-gone-missing: In update mode, but the article didn't exist.
1587 * edit-conflict: In update mode, the article changed unexpectedly.
1588 * edit-no-change: Warning that the text was the same as before.
1589 * edit-already-exists: In creation mode, but the article already exists.
1591 * Extensions may define additional errors.
1593 * $return->value will contain an associative array with members as follows:
1594 * new: Boolean indicating if the function attempted to create a new article.
1595 * revision: The revision object for the inserted revision, or null.
1598 * @throws MWException
1600 public function doEditContent(
1601 Content
$content, $summary, $flags = 0, $baseRevId = false,
1602 User
$user = null, $serialFormat = null, $tags = null
1604 global $wgUser, $wgUseAutomaticEditSummaries;
1606 // Low-level sanity check
1607 if ( $this->mTitle
->getText() === '' ) {
1608 throw new MWException( 'Something is trying to edit an article with an empty title' );
1610 // Make sure the given content type is allowed for this page
1611 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle
) ) {
1612 return Status
::newFatal( 'content-not-allowed-here',
1613 ContentHandler
::getLocalizedName( $content->getModel() ),
1614 $this->mTitle
->getPrefixedText()
1618 // Load the data from the master database if needed.
1619 // The caller may already loaded it from the master or even loaded it using
1620 // SELECT FOR UPDATE, so do not override that using clear().
1621 $this->loadPageData( 'fromdbmaster' );
1623 $user = $user ?
: $wgUser;
1624 $flags = $this->checkFlags( $flags );
1626 // Trigger pre-save hook (using provided edit summary)
1627 $hookStatus = Status
::newGood( [] );
1628 $hook_args = [ &$this, &$user, &$content, &$summary,
1629 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
1630 // Check if the hook rejected the attempted save
1631 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1632 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args )
1634 if ( $hookStatus->isOK() ) {
1635 // Hook returned false but didn't call fatal(); use generic message
1636 $hookStatus->fatal( 'edit-hook-aborted' );
1642 $old_revision = $this->getRevision(); // current revision
1643 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1645 // Provide autosummaries if one is not provided and autosummaries are enabled
1646 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY
) && $summary == '' ) {
1647 $handler = $content->getContentHandler();
1648 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1651 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1652 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
1658 // Get the pre-save transform content and final parser output
1659 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1660 $pstContent = $editInfo->pstContent
; // Content object
1662 'bot' => ( $flags & EDIT_FORCE_BOT
),
1663 'minor' => ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' ),
1664 'serialized' => $editInfo->pst
,
1665 'serialFormat' => $serialFormat,
1666 'baseRevId' => $baseRevId,
1667 'oldRevision' => $old_revision,
1668 'oldContent' => $old_content,
1669 'oldId' => $this->getLatest(),
1670 'oldIsRedirect' => $this->isRedirect(),
1671 'oldCountable' => $this->isCountable(),
1672 'tags' => ( $tags !== null ) ?
(array)$tags : []
1675 // Actually create the revision and create/update the page
1676 if ( $flags & EDIT_UPDATE
) {
1677 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1679 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1682 // Promote user to any groups they meet the criteria for
1683 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1684 $user->addAutopromoteOnceGroups( 'onEdit' );
1685 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1692 * @param Content $content Pre-save transform content
1693 * @param integer $flags
1695 * @param string $summary
1696 * @param array $meta
1698 * @throws DBUnexpectedError
1700 * @throws FatalError
1701 * @throws MWException
1703 private function doModify(
1704 Content
$content, $flags, User
$user, $summary, array $meta
1706 global $wgUseRCPatrol;
1708 // Update article, but only if changed.
1709 $status = Status
::newGood( [ 'new' => false, 'revision' => null ] );
1711 // Convenience variables
1712 $now = wfTimestampNow();
1713 $oldid = $meta['oldId'];
1714 /** @var $oldContent Content|null */
1715 $oldContent = $meta['oldContent'];
1716 $newsize = $content->getSize();
1719 // Article gone missing
1720 $status->fatal( 'edit-gone-missing' );
1723 } elseif ( !$oldContent ) {
1724 // Sanity check for bug 37225
1725 throw new MWException( "Could not find text for current revision {$oldid}." );
1728 // @TODO: pass content object?!
1729 $revision = new Revision( [
1730 'page' => $this->getId(),
1731 'title' => $this->mTitle
, // for determining the default content model
1732 'comment' => $summary,
1733 'minor_edit' => $meta['minor'],
1734 'text' => $meta['serialized'],
1736 'parent_id' => $oldid,
1737 'user' => $user->getId(),
1738 'user_text' => $user->getName(),
1739 'timestamp' => $now,
1740 'content_model' => $content->getModel(),
1741 'content_format' => $meta['serialFormat'],
1744 $changed = !$content->equals( $oldContent );
1746 $dbw = wfGetDB( DB_MASTER
);
1749 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1750 $status->merge( $prepStatus );
1751 if ( !$status->isOK() ) {
1755 $dbw->startAtomic( __METHOD__
);
1756 // Get the latest page_latest value while locking it.
1757 // Do a CAS style check to see if it's the same as when this method
1758 // started. If it changed then bail out before touching the DB.
1759 $latestNow = $this->lockAndGetLatest();
1760 if ( $latestNow != $oldid ) {
1761 $dbw->endAtomic( __METHOD__
);
1762 // Page updated or deleted in the mean time
1763 $status->fatal( 'edit-conflict' );
1768 // At this point we are now comitted to returning an OK
1769 // status unless some DB query error or other exception comes up.
1770 // This way callers don't have to call rollback() if $status is bad
1771 // unless they actually try to catch exceptions (which is rare).
1773 // Save the revision text
1774 $revisionId = $revision->insertOn( $dbw );
1775 // Update page_latest and friends to reflect the new revision
1776 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1777 throw new MWException( "Failed to update page row to use new revision." );
1780 Hooks
::run( 'NewRevisionFromEditComplete',
1781 [ $this, $revision, $meta['baseRevId'], $user ] );
1783 // Update recentchanges
1784 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1785 // Mark as patrolled if the user can do so
1786 $patrolled = $wgUseRCPatrol && !count(
1787 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1788 // Add RC row to the DB
1789 RecentChange
::notifyEdit(
1792 $revision->isMinor(),
1796 $this->getTimestamp(),
1799 $oldContent ?
$oldContent->getSize() : 0,
1807 $user->incEditCount();
1809 $dbw->endAtomic( __METHOD__
);
1810 $this->mTimestamp
= $now;
1812 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1813 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1814 $revision->setId( $this->getLatest() );
1815 $revision->setUserIdAndName(
1816 $this->getUser( Revision
::RAW
),
1817 $this->getUserText( Revision
::RAW
)
1822 // Return the new revision to the caller
1823 $status->value
['revision'] = $revision;
1825 $status->warning( 'edit-no-change' );
1826 // Update page_touched as updateRevisionOn() was not called.
1827 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1828 $this->mTitle
->invalidateCache( $now );
1831 // Do secondary updates once the main changes have been committed...
1832 DeferredUpdates
::addUpdate(
1833 new AtomicSectionUpdate(
1837 $revision, &$user, $content, $summary, &$flags,
1838 $changed, $meta, &$status
1840 // Update links tables, site stats, etc.
1841 $this->doEditUpdates(
1845 'changed' => $changed,
1846 'oldcountable' => $meta['oldCountable'],
1847 'oldrevision' => $meta['oldRevision']
1850 // Trigger post-save hook
1851 $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR
,
1852 null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1853 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
1854 Hooks
::run( 'PageContentSaveComplete', $params );
1857 DeferredUpdates
::PRESEND
1864 * @param Content $content Pre-save transform content
1865 * @param integer $flags
1867 * @param string $summary
1868 * @param array $meta
1870 * @throws DBUnexpectedError
1872 * @throws FatalError
1873 * @throws MWException
1875 private function doCreate(
1876 Content
$content, $flags, User
$user, $summary, array $meta
1878 global $wgUseRCPatrol, $wgUseNPPatrol;
1880 $status = Status
::newGood( [ 'new' => true, 'revision' => null ] );
1882 $now = wfTimestampNow();
1883 $newsize = $content->getSize();
1884 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1885 $status->merge( $prepStatus );
1886 if ( !$status->isOK() ) {
1890 $dbw = wfGetDB( DB_MASTER
);
1891 $dbw->startAtomic( __METHOD__
);
1893 // Add the page record unless one already exists for the title
1894 $newid = $this->insertOn( $dbw );
1895 if ( $newid === false ) {
1896 $dbw->endAtomic( __METHOD__
); // nothing inserted
1897 $status->fatal( 'edit-already-exists' );
1899 return $status; // nothing done
1902 // At this point we are now comitted to returning an OK
1903 // status unless some DB query error or other exception comes up.
1904 // This way callers don't have to call rollback() if $status is bad
1905 // unless they actually try to catch exceptions (which is rare).
1907 // @TODO: pass content object?!
1908 $revision = new Revision( [
1910 'title' => $this->mTitle
, // for determining the default content model
1911 'comment' => $summary,
1912 'minor_edit' => $meta['minor'],
1913 'text' => $meta['serialized'],
1915 'user' => $user->getId(),
1916 'user_text' => $user->getName(),
1917 'timestamp' => $now,
1918 'content_model' => $content->getModel(),
1919 'content_format' => $meta['serialFormat'],
1922 // Save the revision text...
1923 $revisionId = $revision->insertOn( $dbw );
1924 // Update the page record with revision data
1925 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1926 throw new MWException( "Failed to update page row to use new revision." );
1929 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1931 // Update recentchanges
1932 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1933 // Mark as patrolled if the user can do so
1934 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) &&
1935 !count( $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1936 // Add RC row to the DB
1937 RecentChange
::notifyNew(
1940 $revision->isMinor(),
1952 $user->incEditCount();
1954 $dbw->endAtomic( __METHOD__
);
1955 $this->mTimestamp
= $now;
1957 // Return the new revision to the caller
1958 $status->value
['revision'] = $revision;
1960 // Do secondary updates once the main changes have been committed...
1961 DeferredUpdates
::addUpdate(
1962 new AtomicSectionUpdate(
1966 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1968 // Update links, etc.
1969 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1970 // Trigger post-create hook
1971 $params = [ &$this, &$user, $content, $summary,
1972 $flags & EDIT_MINOR
, null, null, &$flags, $revision ];
1973 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $params );
1974 Hooks
::run( 'PageContentInsertComplete', $params );
1975 // Trigger post-save hook
1976 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1977 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $params );
1978 Hooks
::run( 'PageContentSaveComplete', $params );
1982 DeferredUpdates
::PRESEND
1989 * Get parser options suitable for rendering the primary article wikitext
1991 * @see ContentHandler::makeParserOptions
1993 * @param IContextSource|User|string $context One of the following:
1994 * - IContextSource: Use the User and the Language of the provided
1996 * - User: Use the provided User object and $wgLang for the language,
1997 * so use an IContextSource object if possible.
1998 * - 'canonical': Canonical options (anonymous user with default
1999 * preferences and content language).
2000 * @return ParserOptions
2002 public function makeParserOptions( $context ) {
2003 $options = $this->getContentHandler()->makeParserOptions( $context );
2005 if ( $this->getTitle()->isConversionTable() ) {
2006 // @todo ConversionTable should become a separate content model, so
2007 // we don't need special cases like this one.
2008 $options->disableContentConversion();
2015 * Prepare text which is about to be saved.
2016 * Returns a stdClass with source, pst and output members
2018 * @param string $text
2019 * @param int|null $revid
2020 * @param User|null $user
2021 * @deprecated since 1.21: use prepareContentForEdit instead.
2024 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2025 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2026 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2027 return $this->prepareContentForEdit( $content, $revid, $user );
2031 * Prepare content which is about to be saved.
2032 * Returns a stdClass with source, pst and output members
2034 * @param Content $content
2035 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2036 * revision ID is also accepted, but this is deprecated.
2037 * @param User|null $user
2038 * @param string|null $serialFormat
2039 * @param bool $useCache Check shared prepared edit cache
2045 public function prepareContentForEdit(
2046 Content
$content, $revision = null, User
$user = null,
2047 $serialFormat = null, $useCache = true
2049 global $wgContLang, $wgUser, $wgAjaxEditStash;
2051 if ( is_object( $revision ) ) {
2052 $revid = $revision->getId();
2055 // This code path is deprecated, and nothing is known to
2056 // use it, so performance here shouldn't be a worry.
2057 if ( $revid !== null ) {
2058 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2064 $user = is_null( $user ) ?
$wgUser : $user;
2065 // XXX: check $user->getId() here???
2067 // Use a sane default for $serialFormat, see bug 57026
2068 if ( $serialFormat === null ) {
2069 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2072 if ( $this->mPreparedEdit
2073 && isset( $this->mPreparedEdit
->newContent
)
2074 && $this->mPreparedEdit
->newContent
->equals( $content )
2075 && $this->mPreparedEdit
->revid
== $revid
2076 && $this->mPreparedEdit
->format
== $serialFormat
2077 // XXX: also check $user here?
2080 return $this->mPreparedEdit
;
2083 // The edit may have already been prepared via api.php?action=stashedit
2084 $cachedEdit = $useCache && $wgAjaxEditStash
2085 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2088 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2089 Hooks
::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2092 if ( $cachedEdit ) {
2093 $edit->timestamp
= $cachedEdit->timestamp
;
2095 $edit->timestamp
= wfTimestampNow();
2097 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2098 $edit->revid
= $revid;
2100 if ( $cachedEdit ) {
2101 $edit->pstContent
= $cachedEdit->pstContent
;
2103 $edit->pstContent
= $content
2104 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2108 $edit->format
= $serialFormat;
2109 $edit->popts
= $this->makeParserOptions( 'canonical' );
2110 if ( $cachedEdit ) {
2111 $edit->output
= $cachedEdit->output
;
2114 // We get here if vary-revision is set. This means that this page references
2115 // itself (such as via self-transclusion). In this case, we need to make sure
2116 // that any such self-references refer to the newly-saved revision, and not
2117 // to the previous one, which could otherwise happen due to replica DB lag.
2118 $oldCallback = $edit->popts
->getCurrentRevisionCallback();
2119 $edit->popts
->setCurrentRevisionCallback(
2120 function ( Title
$title, $parser = false ) use ( $revision, &$oldCallback ) {
2121 if ( $title->equals( $revision->getTitle() ) ) {
2124 return call_user_func( $oldCallback, $title, $parser );
2129 // Try to avoid a second parse if {{REVISIONID}} is used
2130 $edit->popts
->setSpeculativeRevIdCallback( function () {
2131 return 1 +
(int)wfGetDB( DB_MASTER
)->selectField(
2139 $edit->output
= $edit->pstContent
2140 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2144 $edit->newContent
= $content;
2145 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2147 // NOTE: B/C for hooks! don't use these fields!
2148 $edit->newText
= $edit->newContent
2149 ? ContentHandler
::getContentText( $edit->newContent
)
2151 $edit->oldText
= $edit->oldContent
2152 ? ContentHandler
::getContentText( $edit->oldContent
)
2154 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2156 if ( $edit->output
) {
2157 $edit->output
->setCacheTime( wfTimestampNow() );
2160 // Process cache the result
2161 $this->mPreparedEdit
= $edit;
2167 * Do standard deferred updates after page edit.
2168 * Update links tables, site stats, search index and message cache.
2169 * Purges pages that include this page if the text was changed here.
2170 * Every 100th edit, prune the recent changes table.
2172 * @param Revision $revision
2173 * @param User $user User object that did the revision
2174 * @param array $options Array of options, following indexes are used:
2175 * - changed: boolean, whether the revision changed the content (default true)
2176 * - created: boolean, whether the revision created the page (default false)
2177 * - moved: boolean, whether the page was moved (default false)
2178 * - restored: boolean, whether the page was undeleted (default false)
2179 * - oldrevision: Revision object for the pre-update revision (default null)
2180 * - oldcountable: boolean, null, or string 'no-change' (default null):
2181 * - boolean: whether the page was counted as an article before that
2182 * revision, only used in changed is true and created is false
2183 * - null: if created is false, don't update the article count; if created
2184 * is true, do update the article count
2185 * - 'no-change': don't update the article count, ever
2187 public function doEditUpdates( Revision
$revision, User
$user, array $options = [] ) {
2188 global $wgRCWatchCategoryMembership, $wgContLang;
2194 'restored' => false,
2195 'oldrevision' => null,
2196 'oldcountable' => null
2198 $content = $revision->getContent();
2200 $logger = LoggerFactory
::getInstance( 'SaveParse' );
2202 // See if the parser output before $revision was inserted is still valid
2204 if ( !$this->mPreparedEdit
) {
2205 $logger->debug( __METHOD__
. ": No prepared edit...\n" );
2206 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2207 $logger->info( __METHOD__
. ": Prepared edit has vary-revision...\n" );
2208 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-revision-id' )
2209 && $this->mPreparedEdit
->output
->getSpeculativeRevIdUsed() !== $revision->getId()
2211 $logger->info( __METHOD__
. ": Prepared edit has vary-revision-id with wrong ID...\n" );
2212 } elseif ( $this->mPreparedEdit
->output
->getFlag( 'vary-user' ) && !$options['changed'] ) {
2213 $logger->info( __METHOD__
. ": Prepared edit has vary-user and is null...\n" );
2215 wfDebug( __METHOD__
. ": Using prepared edit...\n" );
2216 $editInfo = $this->mPreparedEdit
;
2220 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2221 // $text is usually already pre-save transformed once. Avoid using the edit stash
2222 // as any prepared content from there or in doEditContent() was already rejected.
2223 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2226 // Save it to the parser cache.
2227 // Make sure the cache time matches page_touched to avoid double parsing.
2228 ParserCache
::singleton()->save(
2229 $editInfo->output
, $this, $editInfo->popts
,
2230 $revision->getTimestamp(), $editInfo->revid
2233 // Update the links tables and other secondary data
2235 $recursive = $options['changed']; // bug 50785
2236 $updates = $content->getSecondaryDataUpdates(
2237 $this->getTitle(), null, $recursive, $editInfo->output
2239 foreach ( $updates as $update ) {
2240 if ( $update instanceof LinksUpdate
) {
2241 $update->setRevision( $revision );
2242 $update->setTriggeringUser( $user );
2244 DeferredUpdates
::addUpdate( $update );
2246 if ( $wgRCWatchCategoryMembership
2247 && $this->getContentHandler()->supportsCategories() === true
2248 && ( $options['changed'] ||
$options['created'] )
2249 && !$options['restored']
2251 // Note: jobs are pushed after deferred updates, so the job should be able to see
2252 // the recent change entry (also done via deferred updates) and carry over any
2253 // bot/deletion/IP flags, ect.
2254 JobQueueGroup
::singleton()->lazyPush( new CategoryMembershipChangeJob(
2257 'pageId' => $this->getId(),
2258 'revTimestamp' => $revision->getTimestamp()
2264 Hooks
::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2266 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2267 // Flush old entries from the `recentchanges` table
2268 if ( mt_rand( 0, 9 ) == 0 ) {
2269 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2273 if ( !$this->exists() ) {
2277 $id = $this->getId();
2278 $title = $this->mTitle
->getPrefixedDBkey();
2279 $shortTitle = $this->mTitle
->getDBkey();
2281 if ( $options['oldcountable'] === 'no-change' ||
2282 ( !$options['changed'] && !$options['moved'] )
2285 } elseif ( $options['created'] ) {
2286 $good = (int)$this->isCountable( $editInfo );
2287 } elseif ( $options['oldcountable'] !== null ) {
2288 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2292 $edits = $options['changed'] ?
1 : 0;
2293 $total = $options['created'] ?
1 : 0;
2295 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2296 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2298 // If this is another user's talk page, update newtalk.
2299 // Don't do this if $options['changed'] = false (null-edits) nor if
2300 // it's a minor edit and the user doesn't want notifications for those.
2301 if ( $options['changed']
2302 && $this->mTitle
->getNamespace() == NS_USER_TALK
2303 && $shortTitle != $user->getTitleKey()
2304 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2306 $recipient = User
::newFromName( $shortTitle, false );
2307 if ( !$recipient ) {
2308 wfDebug( __METHOD__
. ": invalid username\n" );
2310 // Allow extensions to prevent user notification
2311 // when a new message is added to their talk page
2312 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2313 if ( User
::isIP( $shortTitle ) ) {
2314 // An anonymous user
2315 $recipient->setNewtalk( true, $revision );
2316 } elseif ( $recipient->isLoggedIn() ) {
2317 $recipient->setNewtalk( true, $revision );
2319 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2325 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2326 // XXX: could skip pseudo-messages like js/css here, based on content model.
2327 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2328 if ( $msgtext === false ||
$msgtext === null ) {
2332 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2334 if ( $wgContLang->hasVariants() ) {
2335 $wgContLang->updateConversionTable( $this->mTitle
);
2339 if ( $options['created'] ) {
2340 self
::onArticleCreate( $this->mTitle
);
2341 } elseif ( $options['changed'] ) { // bug 50785
2342 self
::onArticleEdit( $this->mTitle
, $revision );
2347 * Edit an article without doing all that other stuff
2348 * The article must already exist; link tables etc
2349 * are not updated, caches are not flushed.
2351 * @param Content $content Content submitted
2352 * @param User $user The relevant user
2353 * @param string $comment Comment submitted
2354 * @param bool $minor Whereas it's a minor modification
2355 * @param string $serialFormat Format for storing the content in the database
2357 public function doQuickEditContent(
2358 Content
$content, User
$user, $comment = '', $minor = false, $serialFormat = null
2361 $serialized = $content->serialize( $serialFormat );
2363 $dbw = wfGetDB( DB_MASTER
);
2364 $revision = new Revision( [
2365 'title' => $this->getTitle(), // for determining the default content model
2366 'page' => $this->getId(),
2367 'user_text' => $user->getName(),
2368 'user' => $user->getId(),
2369 'text' => $serialized,
2370 'length' => $content->getSize(),
2371 'comment' => $comment,
2372 'minor_edit' => $minor ?
1 : 0,
2373 ] ); // XXX: set the content object?
2374 $revision->insertOn( $dbw );
2375 $this->updateRevisionOn( $dbw, $revision );
2377 Hooks
::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2382 * Update the article's restriction field, and leave a log entry.
2383 * This works for protection both existing and non-existing pages.
2385 * @param array $limit Set of restriction keys
2386 * @param array $expiry Per restriction type expiration
2387 * @param int &$cascade Set to false if cascading protection isn't allowed.
2388 * @param string $reason
2389 * @param User $user The user updating the restrictions
2390 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2391 * ($user should be able to add the specified tags before this is called)
2392 * @return Status Status object; if action is taken, $status->value is the log_id of the
2393 * protection log entry.
2395 public function doUpdateRestrictions( array $limit, array $expiry,
2396 &$cascade, $reason, User
$user, $tags = null
2398 global $wgCascadingRestrictionLevels, $wgContLang;
2400 if ( wfReadOnly() ) {
2401 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2404 $this->loadPageData( 'fromdbmaster' );
2405 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2406 $id = $this->getId();
2412 // Take this opportunity to purge out expired restrictions
2413 Title
::purgeExpiredRestrictions();
2415 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2416 // we expect a single selection, but the schema allows otherwise.
2417 $isProtected = false;
2421 $dbw = wfGetDB( DB_MASTER
);
2423 foreach ( $restrictionTypes as $action ) {
2424 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2425 $expiry[$action] = 'infinity';
2427 if ( !isset( $limit[$action] ) ) {
2428 $limit[$action] = '';
2429 } elseif ( $limit[$action] != '' ) {
2433 // Get current restrictions on $action
2434 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2435 if ( $current != '' ) {
2436 $isProtected = true;
2439 if ( $limit[$action] != $current ) {
2441 } elseif ( $limit[$action] != '' ) {
2442 // Only check expiry change if the action is actually being
2443 // protected, since expiry does nothing on an not-protected
2445 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2451 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2455 // If nothing has changed, do nothing
2457 return Status
::newGood();
2460 if ( !$protect ) { // No protection at all means unprotection
2461 $revCommentMsg = 'unprotectedarticle';
2462 $logAction = 'unprotect';
2463 } elseif ( $isProtected ) {
2464 $revCommentMsg = 'modifiedarticleprotection';
2465 $logAction = 'modify';
2467 $revCommentMsg = 'protectedarticle';
2468 $logAction = 'protect';
2471 // Truncate for whole multibyte characters
2472 $reason = $wgContLang->truncate( $reason, 255 );
2474 $logRelationsValues = [];
2475 $logRelationsField = null;
2476 $logParamsDetails = [];
2478 // Null revision (used for change tag insertion)
2479 $nullRevision = null;
2481 if ( $id ) { // Protection of existing page
2482 if ( !Hooks
::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2483 return Status
::newGood();
2486 // Only certain restrictions can cascade...
2487 $editrestriction = isset( $limit['edit'] )
2488 ?
[ $limit['edit'] ]
2489 : $this->mTitle
->getRestrictions( 'edit' );
2490 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2491 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2493 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2494 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2497 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2498 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2499 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2501 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2502 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2505 // The schema allows multiple restrictions
2506 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2510 // insert null revision to identify the page protection change as edit summary
2511 $latest = $this->getLatest();
2512 $nullRevision = $this->insertProtectNullRevision(
2521 if ( $nullRevision === null ) {
2522 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2525 $logRelationsField = 'pr_id';
2527 // Update restrictions table
2528 foreach ( $limit as $action => $restrictions ) {
2530 'page_restrictions',
2533 'pr_type' => $action
2537 if ( $restrictions != '' ) {
2538 $cascadeValue = ( $cascade && $action == 'edit' ) ?
1 : 0;
2540 'page_restrictions',
2542 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2544 'pr_type' => $action,
2545 'pr_level' => $restrictions,
2546 'pr_cascade' => $cascadeValue,
2547 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2551 $logRelationsValues[] = $dbw->insertId();
2552 $logParamsDetails[] = [
2554 'level' => $restrictions,
2555 'expiry' => $expiry[$action],
2556 'cascade' => (bool)$cascadeValue,
2561 // Clear out legacy restriction fields
2564 [ 'page_restrictions' => '' ],
2565 [ 'page_id' => $id ],
2569 Hooks
::run( 'NewRevisionFromEditComplete',
2570 [ $this, $nullRevision, $latest, $user ] );
2571 Hooks
::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2572 } else { // Protection of non-existing page (also known as "title protection")
2573 // Cascade protection is meaningless in this case
2576 if ( $limit['create'] != '' ) {
2577 $dbw->replace( 'protected_titles',
2578 [ [ 'pt_namespace', 'pt_title' ] ],
2580 'pt_namespace' => $this->mTitle
->getNamespace(),
2581 'pt_title' => $this->mTitle
->getDBkey(),
2582 'pt_create_perm' => $limit['create'],
2583 'pt_timestamp' => $dbw->timestamp(),
2584 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2585 'pt_user' => $user->getId(),
2586 'pt_reason' => $reason,
2589 $logParamsDetails[] = [
2591 'level' => $limit['create'],
2592 'expiry' => $expiry['create'],
2595 $dbw->delete( 'protected_titles',
2597 'pt_namespace' => $this->mTitle
->getNamespace(),
2598 'pt_title' => $this->mTitle
->getDBkey()
2604 $this->mTitle
->flushRestrictions();
2605 InfoAction
::invalidateCache( $this->mTitle
);
2607 if ( $logAction == 'unprotect' ) {
2610 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2612 '4::description' => $protectDescriptionLog, // parameter for IRC
2613 '5:bool:cascade' => $cascade,
2614 'details' => $logParamsDetails, // parameter for localize and api
2618 // Update the protection log
2619 $logEntry = new ManualLogEntry( 'protect', $logAction );
2620 $logEntry->setTarget( $this->mTitle
);
2621 $logEntry->setComment( $reason );
2622 $logEntry->setPerformer( $user );
2623 $logEntry->setParameters( $params );
2624 if ( !is_null( $nullRevision ) ) {
2625 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2627 $logEntry->setTags( $tags );
2628 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2629 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2631 $logId = $logEntry->insert();
2632 $logEntry->publish( $logId );
2634 return Status
::newGood( $logId );
2638 * Insert a new null revision for this page.
2640 * @param string $revCommentMsg Comment message key for the revision
2641 * @param array $limit Set of restriction keys
2642 * @param array $expiry Per restriction type expiration
2643 * @param int $cascade Set to false if cascading protection isn't allowed.
2644 * @param string $reason
2645 * @param User|null $user
2646 * @return Revision|null Null on error
2648 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2649 array $expiry, $cascade, $reason, $user = null
2652 $dbw = wfGetDB( DB_MASTER
);
2654 // Prepare a null revision to be added to the history
2655 $editComment = $wgContLang->ucfirst(
2658 $this->mTitle
->getPrefixedText()
2659 )->inContentLanguage()->text()
2662 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2664 $protectDescription = $this->protectDescription( $limit, $expiry );
2665 if ( $protectDescription ) {
2666 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2667 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2668 ->inContentLanguage()->text();
2671 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2672 $editComment .= wfMessage( 'brackets' )->params(
2673 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2674 )->inContentLanguage()->text();
2677 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2679 $nullRev->insertOn( $dbw );
2681 // Update page record and touch page
2682 $oldLatest = $nullRev->getParentId();
2683 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2690 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2693 protected function formatExpiry( $expiry ) {
2696 if ( $expiry != 'infinity' ) {
2699 $wgContLang->timeanddate( $expiry, false, false ),
2700 $wgContLang->date( $expiry, false, false ),
2701 $wgContLang->time( $expiry, false, false )
2702 )->inContentLanguage()->text();
2704 return wfMessage( 'protect-expiry-indefinite' )
2705 ->inContentLanguage()->text();
2710 * Builds the description to serve as comment for the edit.
2712 * @param array $limit Set of restriction keys
2713 * @param array $expiry Per restriction type expiration
2716 public function protectDescription( array $limit, array $expiry ) {
2717 $protectDescription = '';
2719 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2720 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2721 # All possible message keys are listed here for easier grepping:
2722 # * restriction-create
2723 # * restriction-edit
2724 # * restriction-move
2725 # * restriction-upload
2726 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2727 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2728 # with '' filtered out. All possible message keys are listed below:
2729 # * protect-level-autoconfirmed
2730 # * protect-level-sysop
2731 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2732 ->inContentLanguage()->text();
2734 $expiryText = $this->formatExpiry( $expiry[$action] );
2736 if ( $protectDescription !== '' ) {
2737 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2739 $protectDescription .= wfMessage( 'protect-summary-desc' )
2740 ->params( $actionText, $restrictionsText, $expiryText )
2741 ->inContentLanguage()->text();
2744 return $protectDescription;
2748 * Builds the description to serve as comment for the log entry.
2750 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2751 * protect description text. Keep them in old format to avoid breaking compatibility.
2752 * TODO: Fix protection log to store structured description and format it on-the-fly.
2754 * @param array $limit Set of restriction keys
2755 * @param array $expiry Per restriction type expiration
2758 public function protectDescriptionLog( array $limit, array $expiry ) {
2761 $protectDescriptionLog = '';
2763 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2764 $expiryText = $this->formatExpiry( $expiry[$action] );
2765 $protectDescriptionLog .= $wgContLang->getDirMark() .
2766 "[$action=$restrictions] ($expiryText)";
2769 return trim( $protectDescriptionLog );
2773 * Take an array of page restrictions and flatten it to a string
2774 * suitable for insertion into the page_restrictions field.
2776 * @param string[] $limit
2778 * @throws MWException
2781 protected static function flattenRestrictions( $limit ) {
2782 if ( !is_array( $limit ) ) {
2783 throw new MWException( __METHOD__
. ' given non-array restriction set' );
2789 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2790 $bits[] = "$action=$restrictions";
2793 return implode( ':', $bits );
2797 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2798 * backwards compatibility, if you care about error reporting you should use
2799 * doDeleteArticleReal() instead.
2801 * Deletes the article with database consistency, writes logs, purges caches
2803 * @param string $reason Delete reason for deletion log
2804 * @param bool $suppress Suppress all revisions and log the deletion in
2805 * the suppression log instead of the deletion log
2806 * @param int $u1 Unused
2807 * @param bool $u2 Unused
2808 * @param array|string &$error Array of errors to append to
2809 * @param User $user The deleting user
2810 * @return bool True if successful
2812 public function doDeleteArticle(
2813 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2815 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2816 return $status->isGood();
2820 * Back-end article deletion
2821 * Deletes the article with database consistency, writes logs, purges caches
2825 * @param string $reason Delete reason for deletion log
2826 * @param bool $suppress Suppress all revisions and log the deletion in
2827 * the suppression log instead of the deletion log
2828 * @param int $u1 Unused
2829 * @param bool $u2 Unused
2830 * @param array|string &$error Array of errors to append to
2831 * @param User $user The deleting user
2832 * @return Status Status object; if successful, $status->value is the log_id of the
2833 * deletion log entry. If the page couldn't be deleted because it wasn't
2834 * found, $status is a non-fatal 'cannotdelete' error
2836 public function doDeleteArticleReal(
2837 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User
$user = null
2839 global $wgUser, $wgContentHandlerUseDB;
2841 wfDebug( __METHOD__
. "\n" );
2843 $status = Status
::newGood();
2845 if ( $this->mTitle
->getDBkey() === '' ) {
2846 $status->error( 'cannotdelete',
2847 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2851 $user = is_null( $user ) ?
$wgUser : $user;
2852 if ( !Hooks
::run( 'ArticleDelete',
2853 [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2855 if ( $status->isOK() ) {
2856 // Hook aborted but didn't set a fatal status
2857 $status->fatal( 'delete-hook-aborted' );
2862 $dbw = wfGetDB( DB_MASTER
);
2863 $dbw->startAtomic( __METHOD__
);
2865 $this->loadPageData( self
::READ_LATEST
);
2866 $id = $this->getId();
2867 // T98706: lock the page from various other updates but avoid using
2868 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2869 // the revisions queries (which also JOIN on user). Only lock the page
2870 // row and CAS check on page_latest to see if the trx snapshot matches.
2871 $lockedLatest = $this->lockAndGetLatest();
2872 if ( $id == 0 ||
$this->getLatest() != $lockedLatest ) {
2873 $dbw->endAtomic( __METHOD__
);
2874 // Page not there or trx snapshot is stale
2875 $status->error( 'cannotdelete',
2876 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2880 // Given the lock above, we can be confident in the title and page ID values
2881 $namespace = $this->getTitle()->getNamespace();
2882 $dbKey = $this->getTitle()->getDBkey();
2884 // At this point we are now comitted to returning an OK
2885 // status unless some DB query error or other exception comes up.
2886 // This way callers don't have to call rollback() if $status is bad
2887 // unless they actually try to catch exceptions (which is rare).
2889 // we need to remember the old content so we can use it to generate all deletion updates.
2891 $content = $this->getContent( Revision
::RAW
);
2892 } catch ( Exception
$ex ) {
2893 wfLogWarning( __METHOD__
. ': failed to load content during deletion! '
2894 . $ex->getMessage() );
2899 // Bitfields to further suppress the content
2902 // This should be 15...
2903 $bitfield |
= Revision
::DELETED_TEXT
;
2904 $bitfield |
= Revision
::DELETED_COMMENT
;
2905 $bitfield |
= Revision
::DELETED_USER
;
2906 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2907 $deletionFields = [ $dbw->addQuotes( $bitfield ) . ' AS deleted' ];
2909 $deletionFields = [ 'rev_deleted AS deleted' ];
2912 // For now, shunt the revision data into the archive table.
2913 // Text is *not* removed from the text table; bulk storage
2914 // is left intact to avoid breaking block-compression or
2915 // immutable storage schemes.
2916 // In the future, we may keep revisions and mark them with
2917 // the rev_deleted field, which is reserved for this purpose.
2919 // Get all of the page revisions
2920 $fields = array_diff( Revision
::selectFields(), [ 'rev_deleted' ] );
2921 $res = $dbw->select(
2923 array_merge( $fields, $deletionFields ),
2924 [ 'rev_page' => $id ],
2928 // Build their equivalent archive rows
2930 foreach ( $res as $row ) {
2932 'ar_namespace' => $namespace,
2933 'ar_title' => $dbKey,
2934 'ar_comment' => $row->rev_comment
,
2935 'ar_user' => $row->rev_user
,
2936 'ar_user_text' => $row->rev_user_text
,
2937 'ar_timestamp' => $row->rev_timestamp
,
2938 'ar_minor_edit' => $row->rev_minor_edit
,
2939 'ar_rev_id' => $row->rev_id
,
2940 'ar_parent_id' => $row->rev_parent_id
,
2941 'ar_text_id' => $row->rev_text_id
,
2944 'ar_len' => $row->rev_len
,
2945 'ar_page_id' => $id,
2946 'ar_deleted' => $row->deleted
,
2947 'ar_sha1' => $row->rev_sha1
,
2949 if ( $wgContentHandlerUseDB ) {
2950 $rowInsert['ar_content_model'] = $row->rev_content_model
;
2951 $rowInsert['ar_content_format'] = $row->rev_content_format
;
2953 $rowsInsert[] = $rowInsert;
2955 // Copy them into the archive table
2956 $dbw->insert( 'archive', $rowsInsert, __METHOD__
);
2957 // Save this so we can pass it to the ArticleDeleteComplete hook.
2958 $archivedRevisionCount = $dbw->affectedRows();
2960 // Clone the title and wikiPage, so we have the information we need when
2961 // we log and run the ArticleDeleteComplete hook.
2962 $logTitle = clone $this->mTitle
;
2963 $wikiPageBeforeDelete = clone $this;
2965 // Now that it's safely backed up, delete it
2966 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
2968 if ( !$dbw->cascadingDeletes() ) {
2969 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__
);
2972 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2973 $logtype = $suppress ?
'suppress' : 'delete';
2975 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2976 $logEntry->setPerformer( $user );
2977 $logEntry->setTarget( $logTitle );
2978 $logEntry->setComment( $reason );
2979 $logid = $logEntry->insert();
2981 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2982 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2983 $logEntry->publish( $logid );
2986 $dbw->endAtomic( __METHOD__
);
2988 $this->doDeleteUpdates( $id, $content );
2990 Hooks
::run( 'ArticleDeleteComplete', [
2991 &$wikiPageBeforeDelete,
2997 $archivedRevisionCount
2999 $status->value
= $logid;
3001 // Show log excerpt on 404 pages rather than just a link
3002 $cache = ObjectCache
::getMainStashInstance();
3003 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
3004 $cache->set( $key, 1, $cache::TTL_DAY
);
3010 * Lock the page row for this title+id and return page_latest (or 0)
3012 * @return integer Returns 0 if no row was found with this title+id
3015 public function lockAndGetLatest() {
3016 return (int)wfGetDB( DB_MASTER
)->selectField(
3020 'page_id' => $this->getId(),
3021 // Typically page_id is enough, but some code might try to do
3022 // updates assuming the title is the same, so verify that
3023 'page_namespace' => $this->getTitle()->getNamespace(),
3024 'page_title' => $this->getTitle()->getDBkey()
3032 * Do some database updates after deletion
3034 * @param int $id The page_id value of the page being deleted
3035 * @param Content $content Optional page content to be used when determining
3036 * the required updates. This may be needed because $this->getContent()
3037 * may already return null when the page proper was deleted.
3039 public function doDeleteUpdates( $id, Content
$content = null ) {
3041 $countable = $this->isCountable();
3042 } catch ( Exception
$ex ) {
3043 // fallback for deleting broken pages for which we cannot load the content for
3044 // some reason. Note that doDeleteArticleReal() already logged this problem.
3048 // Update site status
3049 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$countable, -1 ) );
3051 // Delete pagelinks, update secondary indexes, etc
3052 $updates = $this->getDeletionUpdates( $content );
3053 foreach ( $updates as $update ) {
3054 DeferredUpdates
::addUpdate( $update );
3057 // Reparse any pages transcluding this page
3058 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
3060 // Reparse any pages including this image
3061 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
3062 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
3066 WikiPage
::onArticleDelete( $this->mTitle
);
3068 // Reset this object and the Title object
3069 $this->loadFromRow( false, self
::READ_LATEST
);
3072 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
3076 * Roll back the most recent consecutive set of edits to a page
3077 * from the same user; fails if there are no eligible edits to
3078 * roll back to, e.g. user is the sole contributor. This function
3079 * performs permissions checks on $user, then calls commitRollback()
3080 * to do the dirty work
3082 * @todo Separate the business/permission stuff out from backend code
3083 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3085 * @param string $fromP Name of the user whose edits to rollback.
3086 * @param string $summary Custom summary. Set to default summary if empty.
3087 * @param string $token Rollback token.
3088 * @param bool $bot If true, mark all reverted edits as bot.
3090 * @param array $resultDetails Array contains result-specific array of additional values
3091 * 'alreadyrolled' : 'current' (rev)
3092 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3094 * @param User $user The user performing the rollback
3095 * @param array|null $tags Change tags to apply to the rollback
3096 * Callers are responsible for permission checks
3097 * (with ChangeTags::canAddTagsAccompanyingChange)
3099 * @return array Array of errors, each error formatted as
3100 * array(messagekey, param1, param2, ...).
3101 * On success, the array is empty. This array can also be passed to
3102 * OutputPage::showPermissionsErrorPage().
3104 public function doRollback(
3105 $fromP, $summary, $token, $bot, &$resultDetails, User
$user, $tags = null
3107 $resultDetails = null;
3109 // Check permissions
3110 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
3111 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
3112 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3114 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3115 $errors[] = [ 'sessionfailure' ];
3118 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
3119 $errors[] = [ 'actionthrottledtext' ];
3122 // If there were errors, bail out now
3123 if ( !empty( $errors ) ) {
3127 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3131 * Backend implementation of doRollback(), please refer there for parameter
3132 * and return value documentation
3134 * NOTE: This function does NOT check ANY permissions, it just commits the
3135 * rollback to the DB. Therefore, you should only call this function direct-
3136 * ly if you want to use custom permissions checks. If you don't, use
3137 * doRollback() instead.
3138 * @param string $fromP Name of the user whose edits to rollback.
3139 * @param string $summary Custom summary. Set to default summary if empty.
3140 * @param bool $bot If true, mark all reverted edits as bot.
3142 * @param array $resultDetails Contains result-specific array of additional values
3143 * @param User $guser The user performing the rollback
3144 * @param array|null $tags Change tags to apply to the rollback
3145 * Callers are responsible for permission checks
3146 * (with ChangeTags::canAddTagsAccompanyingChange)
3150 public function commitRollback( $fromP, $summary, $bot,
3151 &$resultDetails, User
$guser, $tags = null
3153 global $wgUseRCPatrol, $wgContLang;
3155 $dbw = wfGetDB( DB_MASTER
);
3157 if ( wfReadOnly() ) {
3158 return [ [ 'readonlytext' ] ];
3161 // Get the last editor
3162 $current = $this->getRevision();
3163 if ( is_null( $current ) ) {
3164 // Something wrong... no page?
3165 return [ [ 'notanarticle' ] ];
3168 $from = str_replace( '_', ' ', $fromP );
3169 // User name given should match up with the top revision.
3170 // If the user was deleted then $from should be empty.
3171 if ( $from != $current->getUserText() ) {
3172 $resultDetails = [ 'current' => $current ];
3173 return [ [ 'alreadyrolled',
3174 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3175 htmlspecialchars( $fromP ),
3176 htmlspecialchars( $current->getUserText() )
3180 // Get the last edit not by this person...
3181 // Note: these may not be public values
3182 $user = intval( $current->getUser( Revision
::RAW
) );
3183 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3184 $s = $dbw->selectRow( 'revision',
3185 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3186 [ 'rev_page' => $current->getPage(),
3187 "rev_user != {$user} OR rev_user_text != {$user_text}"
3189 [ 'USE INDEX' => 'page_timestamp',
3190 'ORDER BY' => 'rev_timestamp DESC' ]
3192 if ( $s === false ) {
3193 // No one else ever edited this page
3194 return [ [ 'cantrollback' ] ];
3195 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3196 ||
$s->rev_deleted
& Revision
::DELETED_USER
3198 // Only admins can see this text
3199 return [ [ 'notvisiblerev' ] ];
3202 // Generate the edit summary if necessary
3203 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3204 if ( empty( $summary ) ) {
3205 if ( $from == '' ) { // no public user name
3206 $summary = wfMessage( 'revertpage-nouser' );
3208 $summary = wfMessage( 'revertpage' );
3212 // Allow the custom summary to use the same args as the default message
3214 $target->getUserText(), $from, $s->rev_id
,
3215 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3216 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3218 if ( $summary instanceof Message
) {
3219 $summary = $summary->params( $args )->inContentLanguage()->text();
3221 $summary = wfMsgReplaceArgs( $summary, $args );
3224 // Trim spaces on user supplied text
3225 $summary = trim( $summary );
3227 // Truncate for whole multibyte characters.
3228 $summary = $wgContLang->truncate( $summary, 255 );
3231 $flags = EDIT_UPDATE | EDIT_INTERNAL
;
3233 if ( $guser->isAllowed( 'minoredit' ) ) {
3234 $flags |
= EDIT_MINOR
;
3237 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3238 $flags |
= EDIT_FORCE_BOT
;
3241 $targetContent = $target->getContent();
3242 $changingContentModel = $targetContent->getModel() !== $current->getContentModel();
3244 // Actually store the edit
3245 $status = $this->doEditContent(
3255 // Set patrolling and bot flag on the edits, which gets rollbacked.
3256 // This is done even on edit failure to have patrolling in that case (bug 62157).
3258 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3259 // Mark all reverted edits as bot
3263 if ( $wgUseRCPatrol ) {
3264 // Mark all reverted edits as patrolled
3265 $set['rc_patrolled'] = 1;
3268 if ( count( $set ) ) {
3269 $dbw->update( 'recentchanges', $set,
3271 'rc_cur_id' => $current->getPage(),
3272 'rc_user_text' => $current->getUserText(),
3273 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3279 if ( !$status->isOK() ) {
3280 return $status->getErrorsArray();
3283 // raise error, when the edit is an edit without a new version
3284 $statusRev = isset( $status->value
['revision'] )
3285 ?
$status->value
['revision']
3287 if ( !( $statusRev instanceof Revision
) ) {
3288 $resultDetails = [ 'current' => $current ];
3289 return [ [ 'alreadyrolled',
3290 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3291 htmlspecialchars( $fromP ),
3292 htmlspecialchars( $current->getUserText() )
3296 if ( $changingContentModel ) {
3297 // If the content model changed during the rollback,
3298 // make sure it gets logged to Special:Log/contentmodel
3299 $log = new ManualLogEntry( 'contentmodel', 'change' );
3300 $log->setPerformer( $guser );
3301 $log->setTarget( $this->mTitle
);
3302 $log->setComment( $summary );
3303 $log->setParameters( [
3304 '4::oldmodel' => $current->getContentModel(),
3305 '5::newmodel' => $targetContent->getModel(),
3308 $logId = $log->insert( $dbw );
3309 $log->publish( $logId );
3312 $revId = $statusRev->getId();
3314 Hooks
::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3317 'summary' => $summary,
3318 'current' => $current,
3319 'target' => $target,
3327 * The onArticle*() functions are supposed to be a kind of hooks
3328 * which should be called whenever any of the specified actions
3331 * This is a good place to put code to clear caches, for instance.
3333 * This is called on page move and undelete, as well as edit
3335 * @param Title $title
3337 public static function onArticleCreate( Title
$title ) {
3338 // Update existence markers on article/talk tabs...
3339 $other = $title->getOtherPage();
3341 $other->purgeSquid();
3343 $title->touchLinks();
3344 $title->purgeSquid();
3345 $title->deleteTitleProtection();
3347 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3349 if ( $title->getNamespace() == NS_CATEGORY
) {
3350 // Load the Category object, which will schedule a job to create
3351 // the category table row if necessary. Checking a replica DB is ok
3352 // here, in the worst case it'll run an unnecessary recount job on
3353 // a category that probably doesn't have many members.
3354 Category
::newFromTitle( $title )->getID();
3359 * Clears caches when article is deleted
3361 * @param Title $title
3363 public static function onArticleDelete( Title
$title ) {
3366 // Update existence markers on article/talk tabs...
3367 $other = $title->getOtherPage();
3369 $other->purgeSquid();
3371 $title->touchLinks();
3372 $title->purgeSquid();
3374 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3377 HTMLFileCache
::clearFileCache( $title );
3378 InfoAction
::invalidateCache( $title );
3381 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3382 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3384 if ( $wgContLang->hasVariants() ) {
3385 $wgContLang->updateConversionTable( $title );
3390 if ( $title->getNamespace() == NS_FILE
) {
3391 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3395 if ( $title->getNamespace() == NS_USER_TALK
) {
3396 $user = User
::newFromName( $title->getText(), false );
3398 $user->setNewtalk( false );
3403 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3407 * Purge caches on page update etc
3409 * @param Title $title
3410 * @param Revision|null $revision Revision that was just saved, may be null
3412 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3413 // Invalidate caches of articles which include this page
3414 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3416 // Invalidate the caches of all pages which redirect here
3417 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3419 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $title );
3421 // Purge CDN for this page only
3422 $title->purgeSquid();
3423 // Clear file cache for this page only
3424 HTMLFileCache
::clearFileCache( $title );
3426 $revid = $revision ?
$revision->getId() : null;
3427 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3428 InfoAction
::invalidateCache( $title, $revid );
3435 * Returns a list of categories this page is a member of.
3436 * Results will include hidden categories
3438 * @return TitleArray
3440 public function getCategories() {
3441 $id = $this->getId();
3443 return TitleArray
::newFromResult( new FakeResultWrapper( [] ) );
3446 $dbr = wfGetDB( DB_REPLICA
);
3447 $res = $dbr->select( 'categorylinks',
3448 [ 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ],
3449 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3450 // as not being aliases, and NS_CATEGORY is numeric
3451 [ 'cl_from' => $id ],
3454 return TitleArray
::newFromResult( $res );
3458 * Returns a list of hidden categories this page is a member of.
3459 * Uses the page_props and categorylinks tables.
3461 * @return array Array of Title objects
3463 public function getHiddenCategories() {
3465 $id = $this->getId();
3471 $dbr = wfGetDB( DB_REPLICA
);
3472 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3474 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3475 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ],
3478 if ( $res !== false ) {
3479 foreach ( $res as $row ) {
3480 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3488 * Return an applicable autosummary if one exists for the given edit.
3489 * @param string|null $oldtext The previous text of the page.
3490 * @param string|null $newtext The submitted text of the page.
3491 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3492 * @return string An appropriate autosummary, or an empty string.
3494 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3496 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3497 // NOTE: stub for backwards-compatibility. assumes the given text is
3498 // wikitext. will break horribly if it isn't.
3500 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3502 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3503 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3504 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3506 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3510 * Auto-generates a deletion reason
3512 * @param bool &$hasHistory Whether the page has a history
3513 * @return string|bool String containing deletion reason or empty string, or boolean false
3514 * if no revision occurred
3516 public function getAutoDeleteReason( &$hasHistory ) {
3517 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3521 * Update all the appropriate counts in the category table, given that
3522 * we've added the categories $added and deleted the categories $deleted.
3524 * @param array $added The names of categories that were added
3525 * @param array $deleted The names of categories that were deleted
3526 * @param integer $id Page ID (this should be the original deleted page ID)
3528 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3529 $id = $id ?
: $this->getId();
3530 $dbw = wfGetDB( DB_MASTER
);
3531 $method = __METHOD__
;
3532 // Do this at the end of the commit to reduce lock wait timeouts
3533 $dbw->onTransactionPreCommitOrIdle(
3534 function () use ( $dbw, $added, $deleted, $id, $method ) {
3535 $ns = $this->getTitle()->getNamespace();
3537 $addFields = [ 'cat_pages = cat_pages + 1' ];
3538 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3539 if ( $ns == NS_CATEGORY
) {
3540 $addFields[] = 'cat_subcats = cat_subcats + 1';
3541 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3542 } elseif ( $ns == NS_FILE
) {
3543 $addFields[] = 'cat_files = cat_files + 1';
3544 $removeFields[] = 'cat_files = cat_files - 1';
3547 if ( count( $added ) ) {
3548 $existingAdded = $dbw->selectFieldValues(
3551 [ 'cat_title' => $added ],
3555 // For category rows that already exist, do a plain
3556 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3557 // to avoid creating gaps in the cat_id sequence.
3558 if ( count( $existingAdded ) ) {
3562 [ 'cat_title' => $existingAdded ],
3567 $missingAdded = array_diff( $added, $existingAdded );
3568 if ( count( $missingAdded ) ) {
3570 foreach ( $missingAdded as $cat ) {
3572 'cat_title' => $cat,
3574 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3575 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3588 if ( count( $deleted ) ) {
3592 [ 'cat_title' => $deleted ],
3597 foreach ( $added as $catName ) {
3598 $cat = Category
::newFromName( $catName );
3599 Hooks
::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3602 foreach ( $deleted as $catName ) {
3603 $cat = Category
::newFromName( $catName );
3604 Hooks
::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3607 // Refresh counts on categories that should be empty now, to
3608 // trigger possible deletion. Check master for the most
3609 // up-to-date cat_pages.
3610 if ( count( $deleted ) ) {
3611 $rows = $dbw->select(
3613 [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3614 [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3617 foreach ( $rows as $row ) {
3618 $cat = Category
::newFromRow( $row );
3619 $cat->refreshCounts();
3627 * Opportunistically enqueue link update jobs given fresh parser output if useful
3629 * @param ParserOutput $parserOutput Current version page output
3632 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3633 if ( wfReadOnly() ) {
3637 if ( !Hooks
::run( 'OpportunisticLinksUpdate',
3638 [ $this, $this->mTitle
, $parserOutput ]
3643 $config = RequestContext
::getMain()->getConfig();
3646 'isOpportunistic' => true,
3647 'rootJobTimestamp' => $parserOutput->getCacheTime()
3650 if ( $this->mTitle
->areRestrictionsCascading() ) {
3651 // If the page is cascade protecting, the links should really be up-to-date
3652 JobQueueGroup
::singleton()->lazyPush(
3653 RefreshLinksJob
::newPrioritized( $this->mTitle
, $params )
3655 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3656 // Assume the output contains "dynamic" time/random based magic words.
3657 // Only update pages that expired due to dynamic content and NOT due to edits
3658 // to referenced templates/files. When the cache expires due to dynamic content,
3659 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3660 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3661 // template/file edit already triggered recursive RefreshLinksJob jobs.
3662 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3663 // If a page is uncacheable, do not keep spamming a job for it.
3664 // Although it would be de-duplicated, it would still waste I/O.
3665 $cache = ObjectCache
::getLocalClusterInstance();
3666 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3667 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3668 if ( $cache->add( $key, time(), $ttl ) ) {
3669 JobQueueGroup
::singleton()->lazyPush(
3670 RefreshLinksJob
::newDynamic( $this->mTitle
, $params )
3678 * Returns a list of updates to be performed when this page is deleted. The
3679 * updates should remove any information about this page from secondary data
3680 * stores such as links tables.
3682 * @param Content|null $content Optional Content object for determining the
3683 * necessary updates.
3684 * @return DataUpdate[]
3686 public function getDeletionUpdates( Content
$content = null ) {
3688 // load content object, which may be used to determine the necessary updates.
3689 // XXX: the content may not be needed to determine the updates.
3691 $content = $this->getContent( Revision
::RAW
);
3692 } catch ( Exception
$ex ) {
3693 // If we can't load the content, something is wrong. Perhaps that's why
3694 // the user is trying to delete the page, so let's not fail in that case.
3695 // Note that doDeleteArticleReal() will already have logged an issue with
3696 // loading the content.
3703 $updates = $content->getDeletionUpdates( $this );
3706 Hooks
::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );