Merge "docs: Fix typo"
[mediawiki.git] / includes / page / WikiPage.php
blobf9eebd8ea506ce4fbfbff21fefc108ca61484814
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 use MediaWiki\Category\Category;
22 use MediaWiki\CommentStore\CommentStoreComment;
23 use MediaWiki\Content\Content;
24 use MediaWiki\Content\ContentHandler;
25 use MediaWiki\Context\IContextSource;
26 use MediaWiki\DAO\WikiAwareEntityTrait;
27 use MediaWiki\Deferred\DeferredUpdates;
28 use MediaWiki\Edit\PreparedEdit;
29 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
30 use MediaWiki\Linker\LinkTarget;
31 use MediaWiki\Logger\LoggerFactory;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\MediaWikiServices;
34 use MediaWiki\Page\DeletePage;
35 use MediaWiki\Page\ExistingPageRecord;
36 use MediaWiki\Page\PageIdentity;
37 use MediaWiki\Page\PageRecord;
38 use MediaWiki\Page\PageReference;
39 use MediaWiki\Page\PageStoreRecord;
40 use MediaWiki\Page\ParserOutputAccess;
41 use MediaWiki\Parser\ParserOptions;
42 use MediaWiki\Parser\ParserOutput;
43 use MediaWiki\Permissions\Authority;
44 use MediaWiki\Revision\RevisionRecord;
45 use MediaWiki\Revision\RevisionStore;
46 use MediaWiki\Revision\SlotRecord;
47 use MediaWiki\Status\Status;
48 use MediaWiki\Storage\DerivedPageDataUpdater;
49 use MediaWiki\Storage\EditResult;
50 use MediaWiki\Storage\PageUpdater;
51 use MediaWiki\Storage\PageUpdaterFactory;
52 use MediaWiki\Storage\PageUpdateStatus;
53 use MediaWiki\Storage\PreparedUpdate;
54 use MediaWiki\Storage\RevisionSlotsUpdate;
55 use MediaWiki\Title\Title;
56 use MediaWiki\Title\TitleArrayFromResult;
57 use MediaWiki\User\User;
58 use MediaWiki\User\UserIdentity;
59 use MediaWiki\Utils\MWTimestamp;
60 use MediaWiki\WikiMap\WikiMap;
61 use Wikimedia\Assert\Assert;
62 use Wikimedia\Assert\PreconditionException;
63 use Wikimedia\NonSerializable\NonSerializableTrait;
64 use Wikimedia\Rdbms\FakeResultWrapper;
65 use Wikimedia\Rdbms\IDatabase;
66 use Wikimedia\Rdbms\IDBAccessObject;
67 use Wikimedia\Rdbms\ILoadBalancer;
68 use Wikimedia\Rdbms\IReadableDatabase;
69 use Wikimedia\Rdbms\RawSQLValue;
70 use Wikimedia\Rdbms\SelectQueryBuilder;
72 /**
73 * @defgroup Page Page
76 /**
77 * Base representation for an editable wiki page.
79 * Some fields are public only for backwards-compatibility. Use accessor methods.
80 * In the past, this class was part of Article.php and everything was public.
82 * @ingroup Page
84 class WikiPage implements Stringable, Page, PageRecord {
85 use NonSerializableTrait;
86 use ProtectedHookAccessorTrait;
87 use WikiAwareEntityTrait;
89 // Constants for $mDataLoadedFrom and related
91 /**
92 * @var Title
93 * @note for access by subclasses only
95 protected $mTitle;
97 /**
98 * @var bool
99 * @note for access by subclasses only
101 protected $mDataLoaded = false;
104 * A cache of the page_is_redirect field, loaded with page data
105 * @var bool
107 private $mPageIsRedirectField = false;
110 * @var bool
112 private $mIsNew = false;
115 * @var int|false False means "not loaded"
116 * @note for access by subclasses only
118 protected $mLatest = false;
121 * @var PreparedEdit|false Map of cache fields (text, parser output, ect) for a proposed/new edit
122 * @note for access by subclasses only
124 protected $mPreparedEdit = false;
127 * @var int|null
129 protected $mId = null;
132 * @var int One of the READ_* constants
134 protected $mDataLoadedFrom = IDBAccessObject::READ_NONE;
137 * @var RevisionRecord|null
139 private $mLastRevision = null;
142 * @var string Timestamp of the current revision or empty string if not loaded
144 protected $mTimestamp = '';
147 * @var string
149 protected $mTouched = '19700101000000';
152 * @var string|null
154 protected $mLanguage = null;
157 * @var string
159 protected $mLinksUpdated = '19700101000000';
162 * @var DerivedPageDataUpdater|null
164 private $derivedDataUpdater = null;
166 public function __construct( PageIdentity $pageIdentity ) {
167 $pageIdentity->assertWiki( PageIdentity::LOCAL );
169 // TODO: remove the need for casting to Title.
170 $title = Title::newFromPageIdentity( $pageIdentity );
171 if ( !$title->canExist() ) {
172 throw new InvalidArgumentException( "WikiPage constructed on a Title that cannot exist as a page: $title" );
175 $this->mTitle = $title;
179 * Makes sure that the mTitle object is cloned
180 * to the newly cloned WikiPage.
182 public function __clone() {
183 $this->mTitle = clone $this->mTitle;
187 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
189 * @param stdClass|string|int $type
190 * @return mixed
192 public static function convertSelectType( $type ) {
193 switch ( $type ) {
194 case 'fromdb':
195 return IDBAccessObject::READ_NORMAL;
196 case 'fromdbmaster':
197 return IDBAccessObject::READ_LATEST;
198 case 'forupdate':
199 return IDBAccessObject::READ_LOCKING;
200 default:
201 // It may already be an integer or whatever else
202 return $type;
206 private function getPageUpdaterFactory(): PageUpdaterFactory {
207 return MediaWikiServices::getInstance()->getPageUpdaterFactory();
211 * @return RevisionStore
213 private function getRevisionStore() {
214 return MediaWikiServices::getInstance()->getRevisionStore();
218 * @return ILoadBalancer
220 private function getDBLoadBalancer() {
221 return MediaWikiServices::getInstance()->getDBLoadBalancer();
225 * @todo Move this UI stuff somewhere else
227 * @see ContentHandler::getActionOverrides
228 * @return array
230 public function getActionOverrides() {
231 return $this->getContentHandler()->getActionOverrides();
235 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
237 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
239 * @return ContentHandler
241 * @since 1.21
243 public function getContentHandler() {
244 $factory = MediaWikiServices::getInstance()->getContentHandlerFactory();
245 return $factory->getContentHandler( $this->getContentModel() );
249 * Get the title object of the article
250 * @return Title Title object of this page
252 public function getTitle(): Title {
253 return $this->mTitle;
257 * Clear the object
258 * @return void
260 public function clear() {
261 $this->mDataLoaded = false;
262 $this->mDataLoadedFrom = IDBAccessObject::READ_NONE;
264 $this->clearCacheFields();
268 * Clear the object cache fields
269 * @return void
271 protected function clearCacheFields() {
272 $this->mId = null;
273 $this->mPageIsRedirectField = false;
274 $this->mLastRevision = null; // Latest revision
275 $this->mTouched = '19700101000000';
276 $this->mLanguage = null;
277 $this->mLinksUpdated = '19700101000000';
278 $this->mTimestamp = '';
279 $this->mIsNew = false;
280 $this->mLatest = false;
281 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
282 // checks the requested rev ID and content against the cached one. For most
283 // content types, the output should not change during the lifetime of this cache.
284 // Clearing it can cause extra parses on edit for no reason.
288 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
289 * @return void
290 * @since 1.23
292 public function clearPreparedEdit() {
293 $this->mPreparedEdit = false;
297 * Return the tables, fields, and join conditions to be selected to create
298 * a new page object.
299 * @since 1.31
300 * @return array[] With three keys:
301 * - tables: (string[]) to include in the `$table` to `IReadableDatabase->select()` or
302 * `SelectQueryBuilder::tables`
303 * - fields: (string[]) to include in the `$vars` to `IReadableDatabase->select()` or
304 * `SelectQueryBuilder::fields`
305 * - joins: (array) to include in the `$join_conds` to `IReadableDatabase->select()` or
306 * `SelectQueryBuilder::joinConds`
307 * @phan-return array{tables:string[],fields:string[],joins:array}
309 public static function getQueryInfo() {
310 $pageLanguageUseDB = MediaWikiServices::getInstance()->getMainConfig()->get(
311 MainConfigNames::PageLanguageUseDB );
313 $ret = [
314 'tables' => [ 'page' ],
315 'fields' => [
316 'page_id',
317 'page_namespace',
318 'page_title',
319 'page_is_redirect',
320 'page_is_new',
321 'page_random',
322 'page_touched',
323 'page_links_updated',
324 'page_latest',
325 'page_len',
326 'page_content_model',
328 'joins' => [],
331 if ( $pageLanguageUseDB ) {
332 $ret['fields'][] = 'page_lang';
335 return $ret;
339 * Fetch a page record with the given conditions
340 * @param IReadableDatabase $dbr
341 * @param array $conditions
342 * @param array $options
343 * @return stdClass|false Database result resource, or false on failure
345 protected function pageData( $dbr, $conditions, $options = [] ) {
346 $pageQuery = self::getQueryInfo();
348 $this->getHookRunner()->onArticlePageDataBefore(
349 $this, $pageQuery['fields'], $pageQuery['tables'], $pageQuery['joins'] );
351 $row = $dbr->newSelectQueryBuilder()
352 ->queryInfo( $pageQuery )
353 ->where( $conditions )
354 ->caller( __METHOD__ )
355 ->options( $options )
356 ->fetchRow();
358 $this->getHookRunner()->onArticlePageDataAfter( $this, $row );
360 return $row;
364 * Fetch a page record matching the Title object's namespace and title
365 * using a sanitized title string
367 * @param IReadableDatabase $dbr
368 * @param Title $title
369 * @param int $recency
370 * @return stdClass|false Database result resource, or false on failure
372 public function pageDataFromTitle( $dbr, $title, $recency = IDBAccessObject::READ_NORMAL ) {
373 if ( !$title->canExist() ) {
374 return false;
376 $options = [];
377 if ( ( $recency & IDBAccessObject::READ_EXCLUSIVE ) == IDBAccessObject::READ_EXCLUSIVE ) {
378 $options[] = 'FOR UPDATE';
379 } elseif ( ( $recency & IDBAccessObject::READ_LOCKING ) == IDBAccessObject::READ_LOCKING ) {
380 $options[] = 'LOCK IN SHARE MODE';
383 return $this->pageData( $dbr, [
384 'page_namespace' => $title->getNamespace(),
385 'page_title' => $title->getDBkey() ], $options );
389 * Fetch a page record matching the requested ID
391 * @param IReadableDatabase $dbr
392 * @param int $id
393 * @param array $options
394 * @return stdClass|false Database result resource, or false on failure
396 public function pageDataFromId( $dbr, $id, $options = [] ) {
397 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
401 * Load the object from a given source by title
403 * @param stdClass|string|int $from One of the following:
404 * - A DB query result object.
405 * - "fromdb" or IDBAccessObject::READ_NORMAL to get from a replica DB.
406 * - "fromdbmaster" or IDBAccessObject::READ_LATEST to get from the primary DB.
407 * - "forupdate" or IDBAccessObject::READ_LOCKING to get from the primary DB
408 * using SELECT FOR UPDATE.
410 * @return void
412 public function loadPageData( $from = 'fromdb' ) {
413 $from = self::convertSelectType( $from );
414 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
415 // We already have the data from the correct location, no need to load it twice.
416 return;
419 if ( is_int( $from ) ) {
420 $loadBalancer = $this->getDBLoadBalancer();
421 if ( ( $from & IDBAccessObject::READ_LATEST ) == IDBAccessObject::READ_LATEST ) {
422 $index = DB_PRIMARY;
423 } else {
424 $index = DB_REPLICA;
426 $db = $loadBalancer->getConnection( $index );
427 $data = $this->pageDataFromTitle( $db, $this->mTitle, $from );
429 if ( !$data
430 && $index == DB_REPLICA
431 && $loadBalancer->hasReplicaServers()
432 && $loadBalancer->hasOrMadeRecentPrimaryChanges()
434 $from = IDBAccessObject::READ_LATEST;
435 $db = $loadBalancer->getConnection( DB_PRIMARY );
436 $data = $this->pageDataFromTitle( $db, $this->mTitle, $from );
438 } else {
439 // No idea from where the caller got this data, assume replica DB.
440 $data = $from;
441 $from = IDBAccessObject::READ_NORMAL;
444 $this->loadFromRow( $data, $from );
448 * Checks whether the page data was loaded using the given database access mode (or better).
450 * @since 1.32
452 * @param string|int $from One of the following:
453 * - "fromdb" or IDBAccessObject::READ_NORMAL to get from a replica DB.
454 * - "fromdbmaster" or IDBAccessObject::READ_LATEST to get from the primary DB.
455 * - "forupdate" or IDBAccessObject::READ_LOCKING to get from the primary DB
456 * using SELECT FOR UPDATE.
458 * @return bool
460 public function wasLoadedFrom( $from ) {
461 $from = self::convertSelectType( $from );
463 if ( !is_int( $from ) ) {
464 // No idea from where the caller got this data, assume replica DB.
465 $from = IDBAccessObject::READ_NORMAL;
468 if ( $from <= $this->mDataLoadedFrom ) {
469 return true;
472 return false;
476 * Load the object from a database row
478 * @since 1.20
479 * @param stdClass|false $data DB row containing fields returned by getQueryInfo() or false
480 * @param string|int $from One of the following:
481 * - "fromdb" or IDBAccessObject::READ_NORMAL if the data comes from a replica DB
482 * - "fromdbmaster" or IDBAccessObject::READ_LATEST if the data comes from the primary DB
483 * - "forupdate" or IDBAccessObject::READ_LOCKING if the data comes from
484 * the primary DB using SELECT FOR UPDATE
486 public function loadFromRow( $data, $from ) {
487 $lc = MediaWikiServices::getInstance()->getLinkCache();
488 $lc->clearLink( $this->mTitle );
490 if ( $data ) {
491 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
493 $this->mTitle->loadFromRow( $data );
494 $this->mId = intval( $data->page_id );
495 $this->mTouched = MWTimestamp::convert( TS_MW, $data->page_touched );
496 $this->mLanguage = $data->page_lang ?? null;
497 $this->mLinksUpdated = $data->page_links_updated === null
498 ? null
499 : MWTimestamp::convert( TS_MW, $data->page_links_updated );
500 $this->mPageIsRedirectField = (bool)$data->page_is_redirect;
501 $this->mIsNew = (bool)( $data->page_is_new ?? 0 );
502 $this->mLatest = intval( $data->page_latest );
503 // T39225: $latest may no longer match the cached latest RevisionRecord object.
504 // Double-check the ID of any cached latest RevisionRecord object for consistency.
505 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
506 $this->mLastRevision = null;
507 $this->mTimestamp = '';
509 } else {
510 $lc->addBadLinkObj( $this->mTitle );
512 $this->mTitle->loadFromRow( false );
514 $this->clearCacheFields();
516 $this->mId = 0;
519 $this->mDataLoaded = true;
520 $this->mDataLoadedFrom = self::convertSelectType( $from );
524 * @param string|false $wikiId
526 * @return int Page ID
528 public function getId( $wikiId = self::LOCAL ): int {
529 $this->assertWiki( $wikiId );
531 if ( !$this->mDataLoaded ) {
532 $this->loadPageData();
534 return $this->mId;
538 * @return bool Whether or not the page exists in the database
540 public function exists(): bool {
541 if ( !$this->mDataLoaded ) {
542 $this->loadPageData();
544 return $this->mId > 0;
548 * Check if this page is something we're going to be showing
549 * some sort of sensible content for. If we return false, page
550 * views (plain action=view) will return an HTTP 404 response,
551 * so spiders and robots can know they're following a bad link.
553 * @return bool
555 public function hasViewableContent() {
556 return $this->mTitle->isKnown();
560 * Is the page a redirect, according to secondary tracking tables?
561 * If this is true, getRedirectTarget() will return a Title.
563 * @return bool
565 public function isRedirect() {
566 $this->loadPageData();
567 if ( $this->mPageIsRedirectField ) {
568 return MediaWikiServices::getInstance()->getRedirectLookup()
569 ->getRedirectTarget( $this->getTitle() ) !== null;
572 return false;
576 * Tests if the page is new (only has one revision).
577 * May produce false negatives for some old pages.
579 * @since 1.36
581 * @return bool
583 public function isNew() {
584 if ( !$this->mDataLoaded ) {
585 $this->loadPageData();
588 return $this->mIsNew;
592 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
594 * Will use the revisions actual content model if the page exists,
595 * and the page's default if the page doesn't exist yet.
597 * @return string
599 * @since 1.21
601 public function getContentModel() {
602 if ( $this->exists() ) {
603 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
605 return $cache->getWithSetCallback(
606 $cache->makeKey( 'page-content-model', $this->getLatest() ),
607 $cache::TTL_MONTH,
608 function () {
609 $rev = $this->getRevisionRecord();
610 if ( $rev ) {
611 // Look at the revision's actual content model
612 $slot = $rev->getSlot(
613 SlotRecord::MAIN,
614 RevisionRecord::RAW
616 return $slot->getModel();
617 } else {
618 LoggerFactory::getInstance( 'wikipage' )->warning(
619 'Page exists but has no (visible) revisions!',
621 'page-title' => $this->mTitle->getPrefixedDBkey(),
622 'page-id' => $this->getId(),
625 return $this->mTitle->getContentModel();
628 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
632 // use the default model for this page
633 return $this->mTitle->getContentModel();
637 * Loads page_touched and returns a value indicating if it should be used
638 * @return bool True if this page exists and is not a redirect
640 public function checkTouched() {
641 return ( $this->exists() && !$this->isRedirect() );
645 * Get the page_touched field
646 * @return string Timestamp in TS_MW format
648 public function getTouched() {
649 if ( !$this->mDataLoaded ) {
650 $this->loadPageData();
652 return $this->mTouched;
656 * @return ?string language code for the page
658 public function getLanguage() {
659 if ( !$this->mDataLoaded ) {
660 $this->loadLastEdit();
663 return $this->mLanguage;
667 * Get the page_links_updated field
668 * @return string|null Timestamp in TS_MW format
670 public function getLinksTimestamp() {
671 if ( !$this->mDataLoaded ) {
672 $this->loadPageData();
674 return $this->mLinksUpdated;
678 * Get the page_latest field
679 * @param string|false $wikiId
680 * @return int The rev_id of current revision
682 public function getLatest( $wikiId = self::LOCAL ) {
683 $this->assertWiki( $wikiId );
685 if ( !$this->mDataLoaded ) {
686 $this->loadPageData();
688 return (int)$this->mLatest;
692 * Loads everything except the text
693 * This isn't necessary for all uses, so it's only done if needed.
695 protected function loadLastEdit() {
696 if ( $this->mLastRevision !== null ) {
697 return; // already loaded
700 $latest = $this->getLatest();
701 if ( !$latest ) {
702 return; // page doesn't exist or is missing page_latest info
705 if ( $this->mDataLoadedFrom == IDBAccessObject::READ_LOCKING ) {
706 // T39225: if session S1 loads the page row FOR UPDATE, the result always
707 // includes the latest changes committed. This is true even within REPEATABLE-READ
708 // transactions, where S1 normally only sees changes committed before the first S1
709 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
710 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
711 // happened after the first S1 SELECT.
712 // https://dev.mysql.com/doc/refman/5.7/en/set-transaction.html#isolevel_repeatable-read
713 $revision = $this->getRevisionStore()
714 ->getRevisionByPageId( $this->getId(), $latest, IDBAccessObject::READ_LOCKING );
715 } elseif ( $this->mDataLoadedFrom == IDBAccessObject::READ_LATEST ) {
716 // Bug T93976: if page_latest was loaded from the primary DB, fetch the
717 // revision from there as well, as it may not exist yet on a replica DB.
718 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
719 $revision = $this->getRevisionStore()
720 ->getRevisionByPageId( $this->getId(), $latest, IDBAccessObject::READ_LATEST );
721 } else {
722 $revision = $this->getRevisionStore()->getKnownCurrentRevision( $this->getTitle(), $latest );
725 if ( $revision ) {
726 $this->setLastEdit( $revision );
731 * Set the latest revision
733 private function setLastEdit( RevisionRecord $revRecord ) {
734 $this->mLastRevision = $revRecord;
735 $this->mLatest = $revRecord->getId();
736 $this->mTimestamp = $revRecord->getTimestamp();
737 $this->mTouched = max( $this->mTouched, $revRecord->getTimestamp() );
741 * Get the latest revision
742 * @since 1.32
743 * @return RevisionRecord|null
745 public function getRevisionRecord() {
746 $this->loadLastEdit();
747 return $this->mLastRevision;
751 * Get the content of the current revision. No side-effects...
753 * @param int $audience One of:
754 * RevisionRecord::FOR_PUBLIC to be displayed to all users
755 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
756 * RevisionRecord::RAW get the text regardless of permissions
757 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
758 * to the $audience parameter
759 * @return Content|null The content of the current revision
761 * @since 1.21
763 public function getContent( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
764 $this->loadLastEdit();
765 if ( $this->mLastRevision ) {
766 return $this->mLastRevision->getContent( SlotRecord::MAIN, $audience, $performer );
768 return null;
772 * @return string MW timestamp of last article revision
774 public function getTimestamp() {
775 // Check if the field has been filled by WikiPage::setTimestamp()
776 if ( !$this->mTimestamp ) {
777 $this->loadLastEdit();
780 return MWTimestamp::convert( TS_MW, $this->mTimestamp );
784 * Set the page timestamp (use only to avoid DB queries)
785 * @param string $ts MW timestamp of last article revision
786 * @return void
788 public function setTimestamp( $ts ) {
789 $this->mTimestamp = MWTimestamp::convert( TS_MW, $ts );
793 * @param int $audience One of:
794 * RevisionRecord::FOR_PUBLIC to be displayed to all users
795 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
796 * RevisionRecord::RAW get the text regardless of permissions
797 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
798 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
799 * a user no fallback is provided and the RevisionRecord method will throw an error)
800 * @return int User ID for the user that made the last article revision
802 public function getUser( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
803 $this->loadLastEdit();
804 if ( $this->mLastRevision ) {
805 $revUser = $this->mLastRevision->getUser( $audience, $performer );
806 return $revUser ? $revUser->getId() : 0;
807 } else {
808 return -1;
813 * Get the User object of the user who created the page
814 * @param int $audience One of:
815 * RevisionRecord::FOR_PUBLIC to be displayed to all users
816 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
817 * RevisionRecord::RAW get the text regardless of permissions
818 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
819 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
820 * a user no fallback is provided and the RevisionRecord method will throw an error)
821 * @return UserIdentity|null
823 public function getCreator( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
824 $revRecord = $this->getRevisionStore()->getFirstRevision( $this->getTitle() );
825 if ( $revRecord ) {
826 return $revRecord->getUser( $audience, $performer );
827 } else {
828 return null;
833 * @param int $audience One of:
834 * RevisionRecord::FOR_PUBLIC to be displayed to all users
835 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
836 * RevisionRecord::RAW get the text regardless of permissions
837 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
838 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
839 * a user no fallback is provided and the RevisionRecord method will throw an error)
840 * @return string Username of the user that made the last article revision
842 public function getUserText( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
843 $this->loadLastEdit();
844 if ( $this->mLastRevision ) {
845 $revUser = $this->mLastRevision->getUser( $audience, $performer );
846 return $revUser ? $revUser->getName() : '';
847 } else {
848 return '';
853 * @param int $audience One of:
854 * RevisionRecord::FOR_PUBLIC to be displayed to all users
855 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
856 * RevisionRecord::RAW get the text regardless of permissions
857 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
858 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
859 * a user no fallback is provided and the RevisionRecord method will throw an error)
860 * @return string|null Comment stored for the last article revision, or null if the specified
861 * audience does not have access to the comment.
863 public function getComment( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
864 $this->loadLastEdit();
865 if ( $this->mLastRevision ) {
866 $revComment = $this->mLastRevision->getComment( $audience, $performer );
867 return $revComment ? $revComment->text : '';
868 } else {
869 return '';
874 * Returns true if last revision was marked as "minor edit"
876 * @return bool Minor edit indicator for the last article revision.
878 public function getMinorEdit() {
879 $this->loadLastEdit();
880 if ( $this->mLastRevision ) {
881 return $this->mLastRevision->isMinor();
882 } else {
883 return false;
888 * Determine whether a page would be suitable for being counted as an
889 * article in the site_stats table based on the title & its content
891 * @param PreparedEdit|PreparedUpdate|false $editInfo (false):
892 * An object returned by prepareTextForEdit() or getCurrentUpdate() respectively;
893 * If false is given, the current database state will be used.
895 * @return bool
897 public function isCountable( $editInfo = false ) {
898 $mwServices = MediaWikiServices::getInstance();
899 $articleCountMethod = $mwServices->getMainConfig()->get( MainConfigNames::ArticleCountMethod );
901 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
903 if ( !$this->mTitle->isContentPage() ) {
904 return false;
907 if ( $editInfo instanceof PreparedEdit ) {
908 // NOTE: only the main slot can make a page a redirect
909 $content = $editInfo->pstContent;
910 } elseif ( $editInfo instanceof PreparedUpdate ) {
911 // NOTE: only the main slot can make a page a redirect
912 $content = $editInfo->getRawContent( SlotRecord::MAIN );
913 } else {
914 $content = $this->getContent();
917 if ( !$content || $content->isRedirect() ) {
918 return false;
921 $hasLinks = null;
923 if ( $articleCountMethod === 'link' ) {
924 // nasty special case to avoid re-parsing to detect links
926 if ( $editInfo ) {
927 $hasLinks = $editInfo->output->hasLinks();
928 } else {
929 // NOTE: keep in sync with RevisionRenderer::getLinkCount
930 // NOTE: keep in sync with DerivedPageDataUpdater::isCountable
931 $dbr = $mwServices->getConnectionProvider()->getReplicaDatabase();
932 $hasLinks = (bool)$dbr->newSelectQueryBuilder()
933 ->select( '1' )
934 ->from( 'pagelinks' )
935 ->where( [ 'pl_from' => $this->getId() ] )
936 ->caller( __METHOD__ )->fetchField();
940 // TODO: MCR: determine $hasLinks for each slot, and use that info
941 // with that slot's Content's isCountable method. That requires per-
942 // slot ParserOutput in the ParserCache, or per-slot info in the
943 // pagelinks table.
944 return $content->isCountable( $hasLinks );
948 * If this page is a redirect, get its target
950 * The target will be fetched from the redirect table if possible.
952 * @deprecated since 1.38 Use RedirectLookup::getRedirectTarget() instead.
954 * @return Title|null Title object, or null if this page is not a redirect
956 public function getRedirectTarget() {
957 $target = MediaWikiServices::getInstance()->getRedirectLookup()->getRedirectTarget( $this );
958 return Title::castFromLinkTarget( $target );
962 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
963 * @deprecated since 1.43; use {@link RedirectStore::updateRedirectTarget()} instead.
964 * @param LinkTarget $rt Redirect target
965 * @param int|null $oldLatest Prior page_latest for check and set
966 * @return bool Success
968 public function insertRedirectEntry( LinkTarget $rt, $oldLatest = null ) {
969 return MediaWikiServices::getInstance()->getRedirectStore()
970 ->updateRedirectTarget( $this, $rt );
974 * Get the Title object or URL this page redirects to
976 * @return bool|Title|string False, Title of in-wiki target, or string with URL
978 public function followRedirect() {
979 return $this->getRedirectURL( $this->getRedirectTarget() );
983 * Get the Title object or URL to use for a redirect. We use Title
984 * objects for same-wiki, non-special redirects and URLs for everything
985 * else.
986 * @param Title $rt Redirect target
987 * @return Title|string|false False, Title object of local target, or string with URL
989 public function getRedirectURL( $rt ) {
990 if ( !$rt ) {
991 return false;
994 if ( $rt->isExternal() ) {
995 if ( $rt->isLocal() ) {
996 // Offsite wikis need an HTTP redirect.
997 // This can be hard to reverse and may produce loops,
998 // so they may be disabled in the site configuration.
999 $source = $this->mTitle->getFullURL( 'redirect=no' );
1000 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1001 } else {
1002 // External pages without "local" bit set are not valid
1003 // redirect targets
1004 return false;
1008 if ( $rt->isSpecialPage() ) {
1009 // Gotta handle redirects to special pages differently:
1010 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1011 // Some pages are not valid targets.
1012 if ( $rt->isValidRedirectTarget() ) {
1013 return $rt->getFullURL();
1014 } else {
1015 return false;
1017 } elseif ( !$rt->isValidRedirectTarget() ) {
1018 // We somehow got a bad redirect target into the database (T278367)
1019 return false;
1022 return $rt;
1026 * Get a list of users who have edited this article, not including the user who made
1027 * the most recent revision, which you can get from $article->getUser() if you want it
1028 * @return UserArray
1030 public function getContributors() {
1031 // @todo: This is expensive; cache this info somewhere.
1033 $services = MediaWikiServices::getInstance();
1034 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
1035 $actorNormalization = $services->getActorNormalization();
1036 $userIdentityLookup = $services->getUserIdentityLookup();
1038 $user = $this->getUser()
1039 ? User::newFromId( $this->getUser() )
1040 : User::newFromName( $this->getUserText(), false );
1042 $res = $dbr->newSelectQueryBuilder()
1043 ->select( [
1044 'user_id' => 'actor_user',
1045 'user_name' => 'actor_name',
1046 'actor_id' => 'MIN(rev_actor)',
1047 'user_real_name' => 'MIN(user_real_name)',
1048 'timestamp' => 'MAX(rev_timestamp)',
1050 ->from( 'revision' )
1051 ->join( 'actor', null, 'rev_actor = actor_id' )
1052 ->leftJoin( 'user', null, 'actor_user = user_id' )
1053 ->where( [
1054 'rev_page' => $this->getId(),
1055 // The user who made the top revision gets credited as "this page was last edited by
1056 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1057 $dbr->expr( 'rev_actor', '!=', $actorNormalization->findActorId( $user, $dbr ) ),
1058 // Username hidden?
1059 $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0',
1061 ->groupBy( [ 'actor_user', 'actor_name' ] )
1062 ->orderBy( 'timestamp', SelectQueryBuilder::SORT_DESC )
1063 ->caller( __METHOD__ )
1064 ->fetchResultSet();
1065 return new UserArrayFromResult( $res );
1069 * Should the parser cache be used?
1071 * @param ParserOptions $parserOptions ParserOptions to check
1072 * @param int $oldId
1073 * @return bool
1075 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1076 // NOTE: Keep in sync with ParserOutputAccess::shouldUseCache().
1077 // TODO: Once ParserOutputAccess is stable, deprecated this method.
1078 return $this->exists()
1079 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1080 && $this->getContentHandler()->isParserCacheSupported();
1084 * Get a ParserOutput for the given ParserOptions and revision ID.
1086 * The parser cache will be used if possible. Cache misses that result
1087 * in parser runs are debounced with PoolCounter.
1089 * XXX merge this with updateParserCache()?
1091 * @since 1.19
1092 * @param ParserOptions|null $parserOptions ParserOptions to use for the parse operation
1093 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1094 * get the current revision (default value)
1095 * @param bool $noCache Do not read from or write to caches.
1096 * @return ParserOutput|false ParserOutput or false if the revision was not found or is not public
1098 public function getParserOutput(
1099 ?ParserOptions $parserOptions = null, $oldid = null, $noCache = false
1101 if ( $oldid ) {
1102 $revision = $this->getRevisionStore()->getRevisionByTitle( $this->getTitle(), $oldid );
1104 if ( !$revision ) {
1105 return false;
1107 } else {
1108 $revision = $this->getRevisionRecord();
1111 if ( !$parserOptions ) {
1112 $parserOptions = ParserOptions::newFromAnon();
1115 $options = $noCache ? ParserOutputAccess::OPT_NO_CACHE : 0;
1117 $status = MediaWikiServices::getInstance()->getParserOutputAccess()->getParserOutput(
1118 $this, $parserOptions, $revision, $options
1120 return $status->isOK() ? $status->getValue() : false; // convert null to false
1124 * Do standard deferred updates after page view (existing or missing page)
1125 * @param Authority $performer The viewing user
1126 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1127 * @param RevisionRecord|null $oldRev The RevisionRecord associated with $oldid.
1129 public function doViewUpdates(
1130 Authority $performer,
1131 $oldid = 0,
1132 ?RevisionRecord $oldRev = null
1134 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1135 return;
1138 DeferredUpdates::addCallableUpdate(
1139 function () use ( $performer ) {
1140 // In practice, these hook handlers simply debounce into a post-send
1141 // to do their work since none of the use cases for this hook require
1142 // a blocking pre-send callback.
1144 // TODO: Move this hook to post-send.
1146 // For now, it is unofficially possible for an extension to use
1147 // onPageViewUpdates to try to insert JavaScript via global $wgOut.
1148 // This isn't supported (the hook doesn't pass OutputPage), and
1149 // can't be since OutputPage may be disabled or replaced on some
1150 // pages that we do support page view updates for. We also run
1151 // this hook after HTMLFileCache, which also naturally can't
1152 // support modifying OutputPage. Handlers that modify the page
1153 // may use onBeforePageDisplay instead, which runs behind
1154 // HTMLFileCache and won't run on non-OutputPage responses.
1155 $legacyUser = MediaWikiServices::getInstance()
1156 ->getUserFactory()
1157 ->newFromAuthority( $performer );
1158 $this->getHookRunner()->onPageViewUpdates( $this, $legacyUser );
1160 DeferredUpdates::PRESEND
1163 // Update newtalk and watchlist notification status
1164 MediaWikiServices::getInstance()
1165 ->getWatchlistManager()
1166 ->clearTitleUserNotifications( $performer, $this, $oldid, $oldRev );
1170 * Perform the actions of a page purging
1171 * @return bool
1172 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1173 * controlled how much purging was done.
1175 public function doPurge() {
1176 if ( !$this->getHookRunner()->onArticlePurge( $this ) ) {
1177 return false;
1180 $this->mTitle->invalidateCache();
1182 // Clear file cache and send purge after above page_touched update was committed
1183 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1184 $hcu->purgeTitleUrls( $this->mTitle, $hcu::PURGE_PRESEND );
1186 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1187 MediaWikiServices::getInstance()->getMessageCache()
1188 ->updateMessageOverride( $this->mTitle, $this->getContent() );
1190 InfoAction::invalidateCache( $this->mTitle, $this->getLatest() );
1192 return true;
1196 * Insert a new empty page record for this article.
1197 * This *must* be followed up by creating a revision
1198 * and running $this->updateRevisionOn( ... );
1199 * or else the record will be left in a funky state.
1200 * Best if all done inside a transaction.
1202 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1204 * @param IDatabase $dbw
1205 * @param int|null $pageId Custom page ID that will be used for the insert statement
1207 * @return int|false The newly created page_id key; false if the row was not
1208 * inserted, e.g. because the title already existed or because the specified
1209 * page ID is already in use.
1211 public function insertOn( $dbw, $pageId = null ) {
1212 $pageIdForInsert = $pageId ? [ 'page_id' => $pageId ] : [];
1213 $dbw->newInsertQueryBuilder()
1214 ->insertInto( 'page' )
1215 ->ignore()
1216 ->row( [
1217 'page_namespace' => $this->mTitle->getNamespace(),
1218 'page_title' => $this->mTitle->getDBkey(),
1219 'page_is_redirect' => 0, // Will set this shortly...
1220 'page_is_new' => 1,
1221 'page_random' => wfRandom(),
1222 'page_touched' => $dbw->timestamp(),
1223 'page_latest' => 0, // Fill this in shortly...
1224 'page_len' => 0, // Fill this in shortly...
1225 ] + $pageIdForInsert )
1226 ->caller( __METHOD__ )->execute();
1228 if ( $dbw->affectedRows() > 0 ) {
1229 $newid = $pageId ? (int)$pageId : $dbw->insertId();
1230 $this->mId = $newid;
1231 $this->mTitle->resetArticleID( $newid );
1233 return $newid;
1234 } else {
1235 return false; // nothing changed
1240 * Update the page record to point to a newly saved revision.
1242 * @todo Factor out into a PageStore service, or move into PageUpdater.
1244 * @param IDatabase $dbw
1245 * @param RevisionRecord $revision For ID number, and text used to set
1246 * length and redirect status fields.
1247 * @param int|null $lastRevision If given, will not overwrite the page field
1248 * when different from the currently set value.
1249 * Giving 0 indicates the new page flag should be set on.
1250 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1251 * removing rows in redirect table.
1252 * @return bool Success; false if the page row was missing or page_latest changed
1254 public function updateRevisionOn(
1255 $dbw,
1256 RevisionRecord $revision,
1257 $lastRevision = null,
1258 $lastRevIsRedirect = null
1260 // TODO: move into PageUpdater or PageStore
1261 // NOTE: when doing that, make sure cached fields get reset in doUserEditContent,
1262 // and in the compat stub!
1264 $revId = $revision->getId();
1265 Assert::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1267 $content = $revision->getContent( SlotRecord::MAIN );
1268 $len = $content ? $content->getSize() : 0;
1269 $rt = $content ? $content->getRedirectTarget() : null;
1270 $isNew = $lastRevision === 0;
1271 $isRedirect = $rt !== null;
1273 $conditions = [ 'page_id' => $this->getId() ];
1275 if ( $lastRevision !== null ) {
1276 // An extra check against threads stepping on each other
1277 $conditions['page_latest'] = $lastRevision;
1280 $model = $revision->getMainContentModel();
1282 $row = [ /* SET */
1283 'page_latest' => $revId,
1284 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1285 'page_is_new' => $isNew ? 1 : 0,
1286 'page_is_redirect' => $isRedirect ? 1 : 0,
1287 'page_len' => $len,
1288 'page_content_model' => $model,
1291 $dbw->newUpdateQueryBuilder()
1292 ->update( 'page' )
1293 ->set( $row )
1294 ->where( $conditions )
1295 ->caller( __METHOD__ )->execute();
1297 $result = $dbw->affectedRows() > 0;
1298 if ( $result ) {
1299 $insertedRow = $this->pageData( $dbw, [ 'page_id' => $this->getId() ] );
1301 if ( !$insertedRow ) {
1302 throw new RuntimeException( 'Failed to load freshly inserted row' );
1305 $this->mTitle->loadFromRow( $insertedRow );
1306 MediaWikiServices::getInstance()->getRedirectStore()
1307 ->updateRedirectTarget( $this, $rt, $lastRevIsRedirect );
1308 $this->setLastEdit( $revision );
1309 $this->mPageIsRedirectField = (bool)$rt;
1310 $this->mIsNew = $isNew;
1312 // Update the LinkCache.
1313 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1314 $linkCache->addGoodLinkObjFromRow(
1315 $this->mTitle,
1316 $insertedRow
1320 return $result;
1324 * Helper method for checking whether two revisions have differences that go
1325 * beyond the main slot.
1327 * MCR migration note: this method should go away!
1329 * @deprecated since 1.43; Use only as a stop-gap before refactoring to support MCR.
1331 * @param RevisionRecord $a
1332 * @param RevisionRecord $b
1333 * @return bool
1335 public static function hasDifferencesOutsideMainSlot( RevisionRecord $a, RevisionRecord $b ) {
1336 $aSlots = $a->getSlots();
1337 $bSlots = $b->getSlots();
1338 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1340 return ( $changedRoles !== [ SlotRecord::MAIN ] && $changedRoles !== [] );
1344 * Returns true if this page's content model supports sections.
1346 * @return bool
1348 * @todo The skin should check this and not offer section functionality if
1349 * sections are not supported.
1350 * @todo The EditPage should check this and not offer section functionality
1351 * if sections are not supported.
1353 public function supportsSections() {
1354 return $this->getContentHandler()->supportsSections();
1358 * @param string|int|null|false $sectionId Section identifier as a number or string
1359 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1360 * or 'new' for a new section.
1361 * @param Content $sectionContent New content of the section.
1362 * @param string $sectionTitle New section's subject, only if $section is "new".
1363 * @param string $edittime Revision timestamp or null to use the current revision.
1365 * @return Content|null New complete article content, or null if error.
1367 * @since 1.21
1368 * @deprecated since 1.24, use replaceSectionAtRev instead
1370 public function replaceSectionContent(
1371 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1373 $baseRevId = null;
1374 if ( $edittime && $sectionId !== 'new' ) {
1375 $lb = $this->getDBLoadBalancer();
1376 $rev = $this->getRevisionStore()->getRevisionByTimestamp( $this->mTitle, $edittime );
1377 // Try the primary database if this thread may have just added it.
1378 // The logic to fallback to the primary database if the replica is missing
1379 // the revision could be generalized into RevisionStore, but we don't want
1380 // to encourage loading of revisions by timestamp.
1381 if ( !$rev
1382 && $lb->hasReplicaServers()
1383 && $lb->hasOrMadeRecentPrimaryChanges()
1385 $rev = $this->getRevisionStore()->getRevisionByTimestamp(
1386 $this->mTitle, $edittime, IDBAccessObject::READ_LATEST );
1388 if ( $rev ) {
1389 $baseRevId = $rev->getId();
1393 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1397 * @param string|int|null|false $sectionId Section identifier as a number or string
1398 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1399 * or 'new' for a new section.
1400 * @param Content $sectionContent New content of the section.
1401 * @param string $sectionTitle New section's subject, only if $section is "new".
1402 * @param int|null $baseRevId
1404 * @return Content|null New complete article content, or null if error.
1406 * @since 1.24
1408 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1409 $sectionTitle = '', $baseRevId = null
1411 if ( strval( $sectionId ) === '' ) {
1412 // Whole-page edit; let the whole text through
1413 $newContent = $sectionContent;
1414 } else {
1415 if ( !$this->supportsSections() ) {
1416 throw new BadMethodCallException( "sections not supported for content model " .
1417 $this->getContentHandler()->getModelID() );
1420 // T32711: always use current version when adding a new section
1421 if ( $baseRevId === null || $sectionId === 'new' ) {
1422 $oldContent = $this->getContent();
1423 } else {
1424 $revRecord = $this->getRevisionStore()->getRevisionById( $baseRevId );
1425 if ( !$revRecord ) {
1426 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1427 $this->getId() . "; section: $sectionId)" );
1428 return null;
1431 $oldContent = $revRecord->getContent( SlotRecord::MAIN );
1434 if ( !$oldContent ) {
1435 wfDebug( __METHOD__ . ": no page text" );
1436 return null;
1439 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1442 return $newContent;
1446 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1448 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1449 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1451 * @param int $flags
1452 * @return int Updated $flags
1454 public function checkFlags( $flags ) {
1455 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1456 if ( $this->exists() ) {
1457 $flags |= EDIT_UPDATE;
1458 } else {
1459 $flags |= EDIT_NEW;
1463 return $flags;
1467 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1468 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1469 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1470 * returned matches that caller's expectations, allowing an existing instance to be re-used
1471 * if the given parameters match that instance's internal state according to
1472 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1473 * match the existing one.
1475 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1476 * created, replacing any DerivedPageDataUpdater currently cached.
1478 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1480 * @since 1.32
1482 * @param UserIdentity|null $forUser The user that will be used for, or was used for, PST.
1483 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1484 * to perform updates, if the edit was already saved.
1485 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1486 * if the edit was not yet saved.
1487 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1488 * revision as the edit's parent revision. This ensures that the same
1489 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1491 * @return DerivedPageDataUpdater
1493 private function getDerivedDataUpdater(
1494 ?UserIdentity $forUser = null,
1495 ?RevisionRecord $forRevision = null,
1496 ?RevisionSlotsUpdate $forUpdate = null,
1497 $forEdit = false
1499 if ( !$forRevision && !$forUpdate ) {
1500 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1501 // going to use it with.
1502 $this->derivedDataUpdater = null;
1505 if ( $this->derivedDataUpdater && !$this->derivedDataUpdater->isContentPrepared() ) {
1506 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1507 // to it did not yet initialize it, because we don't know what data it will be
1508 // initialized with.
1509 $this->derivedDataUpdater = null;
1512 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1513 // However, there is no good way to construct a cache key. We'd need to check against all
1514 // cached instances.
1516 if ( $this->derivedDataUpdater
1517 && !$this->derivedDataUpdater->isReusableFor(
1518 $forUser,
1519 $forRevision,
1520 $forUpdate,
1521 $forEdit ? $this->getLatest() : null
1524 $this->derivedDataUpdater = null;
1527 if ( !$this->derivedDataUpdater ) {
1528 $this->derivedDataUpdater =
1529 $this->getPageUpdaterFactory()->newDerivedPageDataUpdater( $this );
1532 return $this->derivedDataUpdater;
1536 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1538 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1539 * and to protected such conflict resolution from concurrent edits using a check-and-set
1540 * mechanism.
1542 * @since 1.32
1544 * @note Once extensions no longer rely on WikiPage to get access to the state of an ongoing
1545 * edit via prepareContentForEdit() and WikiPage::getCurrentUpdate(),
1546 * this method should be deprecated and callers should be migrated to using
1547 * PageUpdaterFactory::newPageUpdater() instead.
1549 * @param Authority|UserIdentity $performer
1550 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1551 * that may already have been returned via getDerivedDataUpdater to be re-used.
1553 * @return PageUpdater
1555 public function newPageUpdater( $performer, ?RevisionSlotsUpdate $forUpdate = null ) {
1556 if ( $performer instanceof Authority ) {
1557 // TODO: Deprecate this. But better get rid of this method entirely.
1558 $performer = $performer->getUser();
1561 $pageUpdater = $this->getPageUpdaterFactory()->newPageUpdaterForDerivedPageDataUpdater(
1562 $this,
1563 $performer,
1564 $this->getDerivedDataUpdater( $performer, null, $forUpdate, true )
1567 return $pageUpdater;
1571 * Change an existing article or create a new article. Updates RC and all necessary caches,
1572 * optionally via the deferred update array.
1574 * @deprecated since 1.36, use PageUpdater::saveRevision instead. Note that the new method
1575 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1576 * apply the autopatrol right as appropriate.
1578 * @param Content $content New content
1579 * @param Authority $performer doing the edit
1580 * @param string|CommentStoreComment $summary Edit summary
1581 * @param int $flags Bitfield:
1582 * EDIT_NEW
1583 * Article is known or assumed to be non-existent, create a new one
1584 * EDIT_UPDATE
1585 * Article is known or assumed to be pre-existing, update it
1586 * EDIT_MINOR
1587 * Mark this edit minor, if the user is allowed to do so
1588 * EDIT_SUPPRESS_RC
1589 * Do not log the change in recentchanges
1590 * EDIT_FORCE_BOT
1591 * Mark the edit a "bot" edit regardless of user rights
1592 * EDIT_AUTOSUMMARY
1593 * Fill in blank summaries with generated text where possible
1594 * EDIT_INTERNAL
1595 * Signal that the page retrieve/save cycle happened entirely in this request.
1597 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1598 * article will be detected. If EDIT_UPDATE is specified and the article
1599 * doesn't exist, the function will return an edit-gone-missing error. If
1600 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1601 * error will be returned. These two conditions are also possible with
1602 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1604 * @param int|false $originalRevId: The ID of an original revision that the edit
1605 * restores or repeats. The new revision is expected to have the exact same content as
1606 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1607 * which are created to record things like page moves. Default is false, meaning we are not
1608 * making a rollback edit.
1609 * @param array|null $tags Change tags to apply to this edit
1610 * Callers are responsible for permission checks
1611 * (with ChangeTags::canAddTagsAccompanyingChange)
1612 * @param int $undidRevId Id of revision that was undone or 0
1614 * @return PageUpdateStatus Possible errors:
1615 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1616 * set the fatal flag of $status.
1617 * edit-gone-missing: In update mode, but the article didn't exist.
1618 * edit-conflict: In update mode, the article changed unexpectedly.
1619 * edit-no-change: Warning that the text was the same as before.
1620 * edit-already-exists: In creation mode, but the article already exists.
1622 * Extensions may define additional errors.
1624 * $return->value will contain an associative array with members as follows:
1625 * new: Boolean indicating if the function attempted to create a new article.
1626 * revision-record: The revision record object for the inserted revision, or null.
1628 * @since 1.36
1630 public function doUserEditContent(
1631 Content $content,
1632 Authority $performer,
1633 $summary,
1634 $flags = 0,
1635 $originalRevId = false,
1636 $tags = [],
1637 $undidRevId = 0
1638 ): PageUpdateStatus {
1639 $useNPPatrol = MediaWikiServices::getInstance()->getMainConfig()->get(
1640 MainConfigNames::UseNPPatrol );
1641 $useRCPatrol = MediaWikiServices::getInstance()->getMainConfig()->get(
1642 MainConfigNames::UseRCPatrol );
1643 if ( !( $summary instanceof CommentStoreComment ) ) {
1644 $summary = CommentStoreComment::newUnsavedComment( trim( $summary ) );
1647 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1648 // Checking the minoredit right should be done in the same place the 'bot' right is
1649 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1650 if ( ( $flags & EDIT_MINOR ) && !$performer->isAllowed( 'minoredit' ) ) {
1651 $flags &= ~EDIT_MINOR;
1654 $slotsUpdate = new RevisionSlotsUpdate();
1655 $slotsUpdate->modifyContent( SlotRecord::MAIN, $content );
1657 // NOTE: while doUserEditContent() executes, callbacks to getDerivedDataUpdater and
1658 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1659 // used by this PageUpdater. However, there is no guarantee for this.
1660 $updater = $this->newPageUpdater( $performer, $slotsUpdate )
1661 ->setContent( SlotRecord::MAIN, $content )
1662 ->setOriginalRevisionId( $originalRevId );
1663 if ( $undidRevId ) {
1664 $updater->markAsRevert(
1665 EditResult::REVERT_UNDO,
1666 $undidRevId,
1667 $originalRevId ?: null
1671 $needsPatrol = $useRCPatrol || ( $useNPPatrol && !$this->exists() );
1673 // TODO: this logic should not be in the storage layer, it's here for compatibility
1674 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1675 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1677 if ( $needsPatrol && $performer->authorizeWrite( 'autopatrol', $this->getTitle() ) ) {
1678 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
1681 $updater->addTags( $tags );
1683 $revRec = $updater->saveRevision(
1684 $summary,
1685 $flags
1688 // $revRec will be null if the edit failed, or if no new revision was created because
1689 // the content did not change.
1690 if ( $revRec ) {
1691 // update cached fields
1692 // TODO: this is currently redundant to what is done in updateRevisionOn.
1693 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1694 $this->setLastEdit( $revRec );
1697 return $updater->getStatus();
1701 * Get parser options suitable for rendering the primary article wikitext
1703 * @see ParserOptions::newCanonical
1705 * @param IContextSource|UserIdentity|string $context One of the following:
1706 * - IContextSource: Use the User and the Language of the provided
1707 * context
1708 * - UserIdentity: Use the provided UserIdentity object and $wgLang
1709 * for the language, so use an IContextSource object if possible.
1710 * - 'canonical': Canonical options (anonymous user with default
1711 * preferences and content language).
1712 * @return ParserOptions
1714 public function makeParserOptions( $context ) {
1715 return self::makeParserOptionsFromTitleAndModel(
1716 $this->getTitle(), $this->getContentModel(), $context
1721 * Create canonical parser options for a given title and content model.
1722 * @internal
1723 * @param PageReference $pageRef
1724 * @param string $contentModel
1725 * @param IContextSource|UserIdentity|string $context See ::makeParserOptions
1726 * @return ParserOptions
1728 public static function makeParserOptionsFromTitleAndModel(
1729 PageReference $pageRef, string $contentModel, $context
1731 $options = ParserOptions::newCanonical( $context );
1733 $title = Title::newFromPageReference( $pageRef );
1734 if ( $title->isConversionTable() ) {
1735 // @todo ConversionTable should become a separate content model, so
1736 // we don't need special cases like this one, but see T313455.
1737 $options->disableContentConversion();
1740 return $options;
1744 * Prepare content which is about to be saved.
1746 * Prior to 1.30, this returned a stdClass.
1748 * @deprecated since 1.32, use newPageUpdater() or getCurrentUpdate() instead.
1749 * @note Calling without a UserIdentity was separately deprecated from 1.37 to 1.39, since
1750 * 1.39 the UserIdentity has been required.
1752 * @param Content $content
1753 * @param RevisionRecord|null $revision
1754 * Used with vary-revision or vary-revision-id.
1755 * @param UserIdentity $user
1756 * @param string|null $serialFormat IGNORED
1757 * @param bool $useStash Use prepared edit stash
1759 * @return PreparedEdit
1761 * @since 1.21
1763 public function prepareContentForEdit(
1764 Content $content,
1765 ?RevisionRecord $revision,
1766 UserIdentity $user,
1767 $serialFormat = null,
1768 $useStash = true
1770 $slots = RevisionSlotsUpdate::newFromContent( [ SlotRecord::MAIN => $content ] );
1771 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1773 if ( !$updater->isUpdatePrepared() ) {
1774 $updater->prepareContent( $user, $slots, $useStash );
1776 if ( $revision ) {
1777 $updater->prepareUpdate(
1778 $revision,
1780 'causeAction' => 'prepare-edit',
1781 'causeAgent' => $user->getName(),
1787 return $updater->getPreparedEdit();
1791 * Do standard deferred updates after page edit.
1792 * Update links tables, site stats, search index and message cache.
1793 * Purges pages that include this page if the text was changed here.
1794 * Every 100th edit, prune the recent changes table.
1796 * @deprecated since 1.32, use DerivedPageDataUpdater::doUpdates instead.
1797 * Emitting warnings since 1.44
1799 * @param RevisionRecord $revisionRecord (Switched from the old Revision class to
1800 * RevisionRecord since 1.35)
1801 * @param UserIdentity $user User object that did the revision
1802 * @param array $options Array of options, see DerivedPageDataUpdater::prepareUpdate.
1804 public function doEditUpdates(
1805 RevisionRecord $revisionRecord,
1806 UserIdentity $user,
1807 array $options = []
1809 wfDeprecated( __METHOD__, '1.32' ); // emitting warnings since 1.44
1811 $options += [
1812 'causeAction' => 'edit-page',
1813 'causeAgent' => $user->getName(),
1816 $updater = $this->getDerivedDataUpdater( $user, $revisionRecord );
1818 $updater->prepareUpdate( $revisionRecord, $options );
1820 $updater->doUpdates();
1824 * Update the parser cache.
1826 * @note This does not update links tables. Use doSecondaryDataUpdates() for that.
1828 * @param array $options
1829 * - causeAction: an arbitrary string identifying the reason for the update.
1830 * See DataUpdate::getCauseAction(). (default 'edit-page')
1831 * - causeAgent: name of the user who caused the update (string, defaults to the
1832 * user who created the revision)
1833 * @since 1.32
1835 public function updateParserCache( array $options = [] ) {
1836 $revision = $this->getRevisionRecord();
1837 if ( !$revision || !$revision->getId() ) {
1838 LoggerFactory::getInstance( 'wikipage' )->info(
1839 __METHOD__ . ' called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
1841 return;
1843 $userIdentity = $revision->getUser( RevisionRecord::RAW );
1845 $updater = $this->getDerivedDataUpdater( $userIdentity, $revision );
1846 $updater->prepareUpdate( $revision, $options );
1847 $updater->doParserCacheUpdate();
1851 * Do secondary data updates (such as updating link tables).
1852 * Secondary data updates are only a small part of the updates needed after saving
1853 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
1854 * secondary data updates). This method is provided for partial purges.
1856 * @note This does not update the parser cache. Use updateParserCache() for that.
1858 * @param array $options
1859 * - recursive (bool, default true): whether to do a recursive update (update pages that
1860 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
1861 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
1862 * was something that did not really change the page, such as a null edit.
1863 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
1864 * user who created the revision)
1865 * - causeAction: an arbitrary string identifying the reason for the update.
1866 * See DataUpdate::getCauseAction(). (default 'unknown')
1867 * - causeAgent: name of the user who caused the update (string, default 'unknown')
1868 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
1869 * Note that even when this is set to false, some updates might still get deferred (as
1870 * some update might directly add child updates to DeferredUpdates).
1871 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
1872 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
1873 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
1874 * for the time until caches have been changed to store RenderedRevision states instead
1875 * of ParserOutput objects. (default: null) (since 1.33)
1876 * @since 1.32
1878 public function doSecondaryDataUpdates( array $options = [] ) {
1879 $options['recursive'] ??= true;
1880 $revision = $this->getRevisionRecord();
1881 if ( !$revision || !$revision->getId() ) {
1882 LoggerFactory::getInstance( 'wikipage' )->info(
1883 __METHOD__ . ' called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
1885 return;
1887 $userIdentity = $revision->getUser( RevisionRecord::RAW );
1889 $updater = $this->getDerivedDataUpdater( $userIdentity, $revision );
1890 $updater->prepareUpdate( $revision, $options );
1891 $updater->doSecondaryDataUpdates( $options );
1895 * Update the article's restriction field, and leave a log entry.
1896 * This works for protection both existing and non-existing pages.
1898 * @param array $limit Set of restriction keys
1899 * @param array $expiry Per restriction type expiration
1900 * @param bool &$cascade Set to false if cascading protection isn't allowed.
1901 * @param string $reason
1902 * @param UserIdentity $user The user updating the restrictions
1903 * @param string[] $tags Change tags to add to the pages and protection log entries
1904 * ($user should be able to add the specified tags before this is called)
1905 * @return Status Status object; if action is taken, $status->value is the log_id of the
1906 * protection log entry.
1908 public function doUpdateRestrictions( array $limit, array $expiry,
1909 &$cascade, $reason, UserIdentity $user, $tags = []
1911 $services = MediaWikiServices::getInstance();
1912 $readOnlyMode = $services->getReadOnlyMode();
1913 if ( $readOnlyMode->isReadOnly() ) {
1914 return Status::newFatal( wfMessage( 'readonlytext', $readOnlyMode->getReason() ) );
1917 $this->loadPageData( 'fromdbmaster' );
1918 $restrictionStore = $services->getRestrictionStore();
1919 $restrictionStore->loadRestrictions( $this->mTitle, IDBAccessObject::READ_LATEST );
1920 $restrictionTypes = $restrictionStore->listApplicableRestrictionTypes( $this->mTitle );
1921 $id = $this->getId();
1923 if ( !$cascade ) {
1924 $cascade = false;
1927 // Take this opportunity to purge out expired restrictions
1928 Title::purgeExpiredRestrictions();
1930 // @todo: Same limitations as described in ProtectionForm.php (line 37);
1931 // we expect a single selection, but the schema allows otherwise.
1932 $isProtected = false;
1933 $protect = false;
1934 $changed = false;
1936 $dbw = $services->getConnectionProvider()->getPrimaryDatabase();
1938 foreach ( $restrictionTypes as $action ) {
1939 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
1940 $expiry[$action] = 'infinity';
1942 if ( !isset( $limit[$action] ) ) {
1943 $limit[$action] = '';
1944 } elseif ( $limit[$action] != '' ) {
1945 $protect = true;
1948 // Get current restrictions on $action
1949 $current = implode( '', $restrictionStore->getRestrictions( $this->mTitle, $action ) );
1950 if ( $current != '' ) {
1951 $isProtected = true;
1954 if ( $limit[$action] != $current ) {
1955 $changed = true;
1956 } elseif ( $limit[$action] != '' ) {
1957 // Only check expiry change if the action is actually being
1958 // protected, since expiry does nothing on an not-protected
1959 // action.
1960 if ( $restrictionStore->getRestrictionExpiry( $this->mTitle, $action ) != $expiry[$action] ) {
1961 $changed = true;
1966 if ( !$changed && $protect && $restrictionStore->areRestrictionsCascading( $this->mTitle ) != $cascade ) {
1967 $changed = true;
1970 // If nothing has changed, do nothing
1971 if ( !$changed ) {
1972 return Status::newGood();
1975 if ( !$protect ) { // No protection at all means unprotection
1976 $revCommentMsg = 'unprotectedarticle-comment';
1977 $logAction = 'unprotect';
1978 } elseif ( $isProtected ) {
1979 $revCommentMsg = 'modifiedarticleprotection-comment';
1980 $logAction = 'modify';
1981 } else {
1982 $revCommentMsg = 'protectedarticle-comment';
1983 $logAction = 'protect';
1986 $logRelationsValues = [];
1987 $logRelationsField = null;
1988 $logParamsDetails = [];
1990 // Null revision (used for change tag insertion)
1991 $nullRevisionRecord = null;
1993 $legacyUser = $services->getUserFactory()->newFromUserIdentity( $user );
1994 if ( !$this->getHookRunner()->onArticleProtect( $this, $legacyUser, $limit, $reason ) ) {
1995 return Status::newGood();
1998 if ( $id ) { // Protection of existing page
1999 // Only certain restrictions can cascade...
2000 $editrestriction = isset( $limit['edit'] )
2001 ? [ $limit['edit'] ]
2002 : $restrictionStore->getRestrictions( $this->mTitle, 'edit' );
2003 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2004 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2006 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2007 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2010 $cascadingRestrictionLevels = $services->getMainConfig()
2011 ->get( MainConfigNames::CascadingRestrictionLevels );
2013 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2014 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2016 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2017 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2020 // The schema allows multiple restrictions
2021 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2022 $cascade = false;
2025 // insert null revision to identify the page protection change as edit summary
2026 $latest = $this->getLatest();
2027 $nullRevisionRecord = $this->insertNullProtectionRevision(
2028 $revCommentMsg,
2029 $limit,
2030 $expiry,
2031 $cascade,
2032 $reason,
2033 $user
2036 if ( $nullRevisionRecord === null ) {
2037 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2040 $logRelationsField = 'pr_id';
2042 // T214035: Avoid deadlock on MySQL.
2043 // Do a DELETE by primary key (pr_id) for any existing protection rows.
2044 // On MySQL and derivatives, unconditionally deleting by page ID (pr_page) would.
2045 // place a gap lock if there are no matching rows. This can deadlock when another
2046 // thread modifies protection settings for page IDs in the same gap.
2047 $existingProtectionIds = $dbw->newSelectQueryBuilder()
2048 ->select( 'pr_id' )
2049 ->from( 'page_restrictions' )
2050 ->where( [ 'pr_page' => $id, 'pr_type' => array_map( 'strval', array_keys( $limit ) ) ] )
2051 ->caller( __METHOD__ )->fetchFieldValues();
2053 if ( $existingProtectionIds ) {
2054 $dbw->newDeleteQueryBuilder()
2055 ->deleteFrom( 'page_restrictions' )
2056 ->where( [ 'pr_id' => $existingProtectionIds ] )
2057 ->caller( __METHOD__ )->execute();
2060 // Update restrictions table
2061 foreach ( $limit as $action => $restrictions ) {
2062 if ( $restrictions != '' ) {
2063 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2064 $dbw->newInsertQueryBuilder()
2065 ->insertInto( 'page_restrictions' )
2066 ->row( [
2067 'pr_page' => $id,
2068 'pr_type' => $action,
2069 'pr_level' => $restrictions,
2070 'pr_cascade' => $cascadeValue,
2071 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2073 ->caller( __METHOD__ )->execute();
2074 $logRelationsValues[] = $dbw->insertId();
2075 $logParamsDetails[] = [
2076 'type' => $action,
2077 'level' => $restrictions,
2078 'expiry' => $expiry[$action],
2079 'cascade' => (bool)$cascadeValue,
2084 $this->getHookRunner()->onRevisionFromEditComplete(
2085 $this, $nullRevisionRecord, $latest, $user, $tags );
2086 } else { // Protection of non-existing page (also known as "title protection")
2087 // Cascade protection is meaningless in this case
2088 $cascade = false;
2090 if ( $limit['create'] != '' ) {
2091 $commentFields = $services->getCommentStore()->insert( $dbw, 'pt_reason', $reason );
2092 $dbw->newReplaceQueryBuilder()
2093 ->table( 'protected_titles' )
2094 ->uniqueIndexFields( [ 'pt_namespace', 'pt_title' ] )
2095 ->rows( [
2096 'pt_namespace' => $this->mTitle->getNamespace(),
2097 'pt_title' => $this->mTitle->getDBkey(),
2098 'pt_create_perm' => $limit['create'],
2099 'pt_timestamp' => $dbw->timestamp(),
2100 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2101 'pt_user' => $user->getId(),
2102 ] + $commentFields )
2103 ->caller( __METHOD__ )->execute();
2104 $logParamsDetails[] = [
2105 'type' => 'create',
2106 'level' => $limit['create'],
2107 'expiry' => $expiry['create'],
2109 } else {
2110 $dbw->newDeleteQueryBuilder()
2111 ->deleteFrom( 'protected_titles' )
2112 ->where( [
2113 'pt_namespace' => $this->mTitle->getNamespace(),
2114 'pt_title' => $this->mTitle->getDBkey()
2116 ->caller( __METHOD__ )->execute();
2120 $this->getHookRunner()->onArticleProtectComplete( $this, $legacyUser, $limit, $reason );
2122 $services->getRestrictionStore()->flushRestrictions( $this->mTitle );
2124 InfoAction::invalidateCache( $this->mTitle );
2126 if ( $logAction == 'unprotect' ) {
2127 $params = [];
2128 } else {
2129 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2130 $params = [
2131 '4::description' => $protectDescriptionLog, // parameter for IRC
2132 '5:bool:cascade' => $cascade,
2133 'details' => $logParamsDetails, // parameter for localize and api
2137 // Update the protection log
2138 $logEntry = new ManualLogEntry( 'protect', $logAction );
2139 $logEntry->setTarget( $this->mTitle );
2140 $logEntry->setComment( $reason );
2141 $logEntry->setPerformer( $user );
2142 $logEntry->setParameters( $params );
2143 if ( $nullRevisionRecord !== null ) {
2144 $logEntry->setAssociatedRevId( $nullRevisionRecord->getId() );
2146 $logEntry->addTags( $tags );
2147 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2148 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2150 $logId = $logEntry->insert();
2151 $logEntry->publish( $logId );
2153 return Status::newGood( $logId );
2157 * Get the state of an ongoing update, shortly before or just after it is saved to the database.
2158 * If there is no ongoing edit tracked by this WikiPage instance, this methods throws a
2159 * PreconditionException.
2161 * If possible, state is shared with subsequent calls of getPreparedUpdate(),
2162 * prepareContentForEdit(), and newPageUpdater().
2164 * @note This method should generally be avoided, since it forces WikiPage to maintain state
2165 * representing ongoing edits. Code that initiates an edit should use newPageUpdater()
2166 * instead. Hooks that interact with the edit should have a the relevant
2167 * information provided as a PageUpdater, PreparedUpdate, or RenderedRevision.
2169 * @throws PreconditionException if there is no ongoing update. This method must only be
2170 * called after newPageUpdater() had already been called, typically while executing
2171 * a handler for a hook that is triggered during a page edit.
2172 * @return PreparedUpdate
2174 * @since 1.38
2176 public function getCurrentUpdate(): PreparedUpdate {
2177 Assert::precondition(
2178 $this->derivedDataUpdater !== null,
2179 'There is no ongoing update tracked by this instance of WikiPage!'
2182 return $this->derivedDataUpdater;
2186 * Insert a new null revision for this page.
2188 * @since 1.35
2190 * @param string $revCommentMsg Comment message key for the revision
2191 * @param array $limit Set of restriction keys
2192 * @param array $expiry Per restriction type expiration
2193 * @param bool $cascade Set to false if cascading protection isn't allowed.
2194 * @param string $reason
2195 * @param UserIdentity $user User to attribute to
2196 * @return RevisionRecord|null Null on error
2198 public function insertNullProtectionRevision(
2199 string $revCommentMsg,
2200 array $limit,
2201 array $expiry,
2202 bool $cascade,
2203 string $reason,
2204 UserIdentity $user
2205 ): ?RevisionRecord {
2206 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2208 // Prepare a null revision to be added to the history
2209 $editComment = wfMessage(
2210 $revCommentMsg,
2211 $this->mTitle->getPrefixedText(),
2212 $user->getName()
2213 )->inContentLanguage()->text();
2214 if ( $reason ) {
2215 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2217 $protectDescription = $this->protectDescription( $limit, $expiry );
2218 if ( $protectDescription ) {
2219 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2220 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2221 ->inContentLanguage()->text();
2223 if ( $cascade ) {
2224 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2225 $editComment .= wfMessage( 'brackets' )->params(
2226 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2227 )->inContentLanguage()->text();
2230 $revStore = $this->getRevisionStore();
2231 $comment = CommentStoreComment::newUnsavedComment( $editComment );
2232 $nullRevRecord = $revStore->newNullRevision(
2233 $dbw,
2234 $this->getTitle(),
2235 $comment,
2236 true,
2237 $user
2240 if ( $nullRevRecord ) {
2241 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2243 // Update page record and touch page
2244 $oldLatest = $inserted->getParentId();
2246 $this->updateRevisionOn( $dbw, $inserted, $oldLatest );
2248 return $inserted;
2249 } else {
2250 return null;
2255 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2256 * @return string
2258 protected function formatExpiry( $expiry ) {
2259 if ( $expiry != 'infinity' ) {
2260 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2261 return wfMessage(
2262 'protect-expiring',
2263 $contLang->timeanddate( $expiry, false, false ),
2264 $contLang->date( $expiry, false, false ),
2265 $contLang->time( $expiry, false, false )
2266 )->inContentLanguage()->text();
2267 } else {
2268 return wfMessage( 'protect-expiry-indefinite' )
2269 ->inContentLanguage()->text();
2274 * Builds the description to serve as comment for the edit.
2276 * @param array $limit Set of restriction keys
2277 * @param array $expiry Per restriction type expiration
2278 * @return string
2280 public function protectDescription( array $limit, array $expiry ) {
2281 $protectDescription = '';
2283 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2284 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2285 # All possible message keys are listed here for easier grepping:
2286 # * restriction-create
2287 # * restriction-edit
2288 # * restriction-move
2289 # * restriction-upload
2290 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2291 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2292 # with '' filtered out. All possible message keys are listed below:
2293 # * protect-level-autoconfirmed
2294 # * protect-level-sysop
2295 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2296 ->inContentLanguage()->text();
2298 $expiryText = $this->formatExpiry( $expiry[$action] );
2300 if ( $protectDescription !== '' ) {
2301 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2303 $protectDescription .= wfMessage( 'protect-summary-desc' )
2304 ->params( $actionText, $restrictionsText, $expiryText )
2305 ->inContentLanguage()->text();
2308 return $protectDescription;
2312 * Builds the description to serve as comment for the log entry.
2314 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2315 * protect description text. Keep them in old format to avoid breaking compatibility.
2316 * TODO: Fix protection log to store structured description and format it on-the-fly.
2318 * @param array $limit Set of restriction keys
2319 * @param array $expiry Per restriction type expiration
2320 * @return string
2322 public function protectDescriptionLog( array $limit, array $expiry ) {
2323 $protectDescriptionLog = '';
2325 $dirMark = MediaWikiServices::getInstance()->getContentLanguage()->getDirMark();
2326 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2327 $expiryText = $this->formatExpiry( $expiry[$action] );
2328 $protectDescriptionLog .=
2329 $dirMark .
2330 "[$action=$restrictions] ($expiryText)";
2333 return trim( $protectDescriptionLog );
2337 * Determines if deletion of this page would be batched (executed over time by the job queue)
2338 * or not (completed in the same request as the delete call).
2340 * It is unlikely but possible that an edit from another request could push the page over the
2341 * batching threshold after this function is called, but before the caller acts upon the
2342 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2343 * is provided as an unreliable but situationally useful help for some common cases.
2345 * @deprecated since 1.37 Use DeletePage::isBatchedDelete instead.
2347 * @param int $safetyMargin Added to the revision count when checking for batching
2348 * @return bool True if deletion would be batched, false otherwise
2350 public function isBatchedDelete( $safetyMargin = 0 ) {
2351 $deleteRevisionsBatchSize = MediaWikiServices::getInstance()
2352 ->getMainConfig()->get( MainConfigNames::DeleteRevisionsBatchSize );
2354 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2355 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2356 $revCount += $safetyMargin;
2358 return $revCount >= $deleteRevisionsBatchSize;
2362 * Back-end article deletion
2363 * Deletes the article with database consistency, writes logs, purges caches
2365 * @since 1.19
2366 * @since 1.35 Signature changed, user moved to second parameter to prepare for requiring
2367 * a user to be passed
2368 * @since 1.36 User second parameter is required
2369 * @deprecated since 1.37 Use DeletePage instead. Calling ::deleteIfAllowed and letting DeletePage handle
2370 * permission checks is preferred over doing permission checks yourself and then calling ::deleteUnsafe.
2371 * Note that DeletePage returns a good status with false value in case of scheduled deletion, instead of
2372 * a status with a warning. Also, the new method doesn't have an $error parameter, since any error is
2373 * added to the returned Status.
2375 * @param string $reason Delete reason for deletion log
2376 * @param UserIdentity $deleter The deleting user
2377 * @param bool $suppress Suppress all revisions and log the deletion in
2378 * the suppression log instead of the deletion log
2379 * @param bool|null $u1 Unused
2380 * @param array|string &$error Array of errors to append to
2381 * @param mixed $u2 Unused
2382 * @param string[]|null $tags Tags to apply to the deletion action
2383 * @param string $logsubtype
2384 * @param bool $immediate false allows deleting over time via the job queue
2385 * @return Status Status object; if successful, $status->value is the log_id of the
2386 * deletion log entry. If the page couldn't be deleted because it wasn't
2387 * found, $status is a non-fatal 'cannotdelete' error
2389 public function doDeleteArticleReal(
2390 $reason, UserIdentity $deleter, $suppress = false, $u1 = null, &$error = '', $u2 = null,
2391 $tags = [], $logsubtype = 'delete', $immediate = false
2393 $services = MediaWikiServices::getInstance();
2394 $deletePage = $services->getDeletePageFactory()->newDeletePage(
2395 $this,
2396 $services->getUserFactory()->newFromUserIdentity( $deleter )
2399 $status = $deletePage
2400 ->setSuppress( $suppress )
2401 ->setTags( $tags ?: [] )
2402 ->setLogSubtype( $logsubtype )
2403 ->forceImmediate( $immediate )
2404 ->keepLegacyHookErrorsSeparate()
2405 ->deleteUnsafe( $reason );
2406 $error = $deletePage->getLegacyHookErrors();
2407 if ( $status->isGood() ) {
2408 // BC with old return format
2409 if ( $deletePage->deletionsWereScheduled()[DeletePage::PAGE_BASE] ) {
2410 $status->warning( 'delete-scheduled', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2411 } else {
2412 $status->value = $deletePage->getSuccessfulDeletionsIDs()[DeletePage::PAGE_BASE];
2415 return $status;
2419 * Lock the page row for this title+id and return page_latest (or 0)
2421 * @return int Returns 0 if no row was found with this title+id
2422 * @since 1.27
2424 public function lockAndGetLatest() {
2425 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2426 return (int)$dbw->newSelectQueryBuilder()
2427 ->select( 'page_latest' )
2428 ->forUpdate()
2429 ->from( 'page' )
2430 ->where( [
2431 'page_id' => $this->getId(),
2432 // Typically page_id is enough, but some code might try to do
2433 // updates assuming the title is the same, so verify that
2434 'page_namespace' => $this->getTitle()->getNamespace(),
2435 'page_title' => $this->getTitle()->getDBkey()
2437 ->caller( __METHOD__ )->fetchField();
2441 * The onArticle*() functions are supposed to be a kind of hooks
2442 * which should be called whenever any of the specified actions
2443 * are done.
2445 * This is a good place to put code to clear caches, for instance.
2447 * This is called on page move and undelete, as well as edit
2449 * @param Title $title
2450 * @param bool $maybeIsRedirect True if the page may have been created as a redirect.
2451 * If false, this is used as a hint to skip some unnecessary updates.
2453 public static function onArticleCreate( Title $title, $maybeIsRedirect = true ) {
2454 // TODO: move this into a PageEventEmitter service
2456 // Update existence markers on article/talk tabs...
2457 $other = $title->getOtherPage();
2459 $services = MediaWikiServices::getInstance();
2460 $hcu = $services->getHtmlCacheUpdater();
2461 $hcu->purgeTitleUrls( [ $title, $other ], $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2463 $title->touchLinks();
2464 $title->deleteTitleProtection();
2466 $services->getLinkCache()->invalidateTitle( $title );
2468 DeferredUpdates::addCallableUpdate(
2469 static function () use ( $title, $maybeIsRedirect ) {
2470 self::queueBacklinksJobs( $title, true, $maybeIsRedirect, 'create-page' );
2474 if ( $title->getNamespace() === NS_CATEGORY ) {
2475 // Load the Category object, which will schedule a job to create
2476 // the category table row if necessary. Checking a replica DB is ok
2477 // here, in the worst case it'll run an unnecessary recount job on
2478 // a category that probably doesn't have many members.
2479 Category::newFromTitle( $title )->getID();
2484 * Clears caches when article is deleted
2486 public static function onArticleDelete( Title $title ) {
2487 // TODO: move this into a PageEventEmitter service
2489 // Update existence markers on article/talk tabs...
2490 $other = $title->getOtherPage();
2492 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2493 $hcu->purgeTitleUrls( [ $title, $other ], $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2495 $title->touchLinks();
2497 $services = MediaWikiServices::getInstance();
2498 $services->getLinkCache()->invalidateTitle( $title );
2500 InfoAction::invalidateCache( $title );
2502 // Messages
2503 if ( $title->getNamespace() === NS_MEDIAWIKI ) {
2504 $services->getMessageCache()->updateMessageOverride( $title, null );
2507 // Invalidate caches of articles which include this page
2508 DeferredUpdates::addCallableUpdate( static function () use ( $title ) {
2509 self::queueBacklinksJobs( $title, true, true, 'delete-page' );
2510 } );
2512 // User talk pages
2513 if ( $title->getNamespace() === NS_USER_TALK ) {
2514 $user = User::newFromName( $title->getText(), false );
2515 if ( $user ) {
2516 MediaWikiServices::getInstance()
2517 ->getTalkPageNotificationManager()
2518 ->removeUserHasNewMessages( $user );
2522 // Image redirects
2523 $services->getRepoGroup()->getLocalRepo()->invalidateImageRedirect( $title );
2525 // Purge cross-wiki cache entities referencing this page
2526 self::purgeInterwikiCheckKey( $title );
2530 * Purge caches on page update etc
2532 * @param Title $title
2533 * @param RevisionRecord|null $revRecord revision that was just saved, may be null
2534 * @param string[]|null $slotsChanged The role names of the slots that were changed.
2535 * If not given, all slots are assumed to have changed.
2536 * @param bool $maybeRedirectChanged True if the page's redirect target may have changed in the
2537 * latest revision. If false, this is used as a hint to skip some unnecessary updates.
2539 public static function onArticleEdit(
2540 Title $title,
2541 ?RevisionRecord $revRecord = null,
2542 $slotsChanged = null,
2543 $maybeRedirectChanged = true
2545 // TODO: move this into a PageEventEmitter service
2547 DeferredUpdates::addCallableUpdate(
2548 static function () use ( $title, $slotsChanged, $maybeRedirectChanged ) {
2549 self::queueBacklinksJobs(
2550 $title,
2551 $slotsChanged === null || in_array( SlotRecord::MAIN, $slotsChanged ),
2552 $maybeRedirectChanged,
2553 'edit-page'
2558 $services = MediaWikiServices::getInstance();
2559 $services->getLinkCache()->invalidateTitle( $title );
2561 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2562 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2564 // Purge ?action=info cache
2565 $revid = $revRecord ? $revRecord->getId() : null;
2566 DeferredUpdates::addCallableUpdate( static function () use ( $title, $revid ) {
2567 InfoAction::invalidateCache( $title, $revid );
2568 } );
2570 // Purge cross-wiki cache entities referencing this page
2571 self::purgeInterwikiCheckKey( $title );
2574 private static function queueBacklinksJobs(
2575 Title $title, $mainSlotChanged, $maybeRedirectChanged, $causeAction
2577 $services = MediaWikiServices::getInstance();
2578 $backlinkCache = $services->getBacklinkCacheFactory()->getBacklinkCache( $title );
2580 $jobs = [];
2581 if ( $mainSlotChanged
2582 && $backlinkCache->hasLinks( 'templatelinks' )
2584 // Invalidate caches of articles which include this page.
2585 // Only for the main slot, because only the main slot is transcluded.
2586 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
2587 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2588 $title,
2589 'templatelinks',
2590 [ 'causeAction' => $causeAction ]
2593 // Images
2594 if ( $maybeRedirectChanged && $title->getNamespace() === NS_FILE
2595 && $backlinkCache->hasLinks( 'imagelinks' )
2597 // Process imagelinks in case the redirect target has changed
2598 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2599 $title,
2600 'imagelinks',
2601 [ 'causeAction' => $causeAction ]
2604 // Invalidate the caches of all pages which redirect here
2605 if ( $backlinkCache->hasLinks( 'redirect' ) ) {
2606 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2607 $title,
2608 'redirect',
2609 [ 'causeAction' => $causeAction ]
2612 if ( $jobs ) {
2613 $services->getJobQueueGroup()->push( $jobs );
2618 * Purge the check key for cross-wiki cache entries referencing this page
2620 private static function purgeInterwikiCheckKey( Title $title ) {
2621 $enableScaryTranscluding = MediaWikiServices::getInstance()->getMainConfig()->get(
2622 MainConfigNames::EnableScaryTranscluding );
2624 if ( !$enableScaryTranscluding ) {
2625 return; // @todo: perhaps this wiki is only used as a *source* for content?
2628 DeferredUpdates::addCallableUpdate( static function () use ( $title ) {
2629 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2630 $cache->resetCheckKey(
2631 // Do not include the namespace since there can be multiple aliases to it
2632 // due to different namespace text definitions on different wikis. This only
2633 // means that some cache invalidations happen that are not strictly needed.
2634 $cache->makeGlobalKey(
2635 'interwiki-page',
2636 WikiMap::getCurrentWikiDbDomain()->getId(),
2637 $title->getDBkey()
2640 } );
2644 * Returns a list of categories this page is a member of.
2645 * Results will include hidden categories
2647 * @return TitleArrayFromResult
2649 public function getCategories() {
2650 $services = MediaWikiServices::getInstance();
2651 $id = $this->getId();
2652 if ( $id == 0 ) {
2653 return $services->getTitleFactory()->newTitleArrayFromResult( new FakeResultWrapper( [] ) );
2656 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
2657 $res = $dbr->newSelectQueryBuilder()
2658 ->select( [ 'page_title' => 'cl_to', 'page_namespace' => (string)NS_CATEGORY ] )
2659 ->from( 'categorylinks' )
2660 ->where( [ 'cl_from' => $id ] )
2661 ->caller( __METHOD__ )->fetchResultSet();
2663 return $services->getTitleFactory()->newTitleArrayFromResult( $res );
2667 * Returns a list of hidden categories this page is a member of.
2668 * Uses the page_props and categorylinks tables.
2670 * @return Title[]
2672 public function getHiddenCategories() {
2673 $result = [];
2674 $id = $this->getId();
2676 if ( $id == 0 ) {
2677 return [];
2680 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2681 $res = $dbr->newSelectQueryBuilder()
2682 ->select( [ 'cl_to' ] )
2683 ->from( 'categorylinks' )
2684 ->join( 'page', null, 'page_title=cl_to' )
2685 ->join( 'page_props', null, 'pp_page=page_id' )
2686 ->where( [ 'cl_from' => $id, 'pp_propname' => 'hiddencat', 'page_namespace' => NS_CATEGORY ] )
2687 ->caller( __METHOD__ )->fetchResultSet();
2689 foreach ( $res as $row ) {
2690 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2693 return $result;
2697 * Auto-generates a deletion reason
2699 * @param bool &$hasHistory Whether the page has a history
2700 * @return string|false String containing deletion reason or empty string, or boolean false
2701 * if no revision occurred
2703 public function getAutoDeleteReason( &$hasHistory = false ) {
2704 if ( func_num_args() === 1 ) {
2705 wfDeprecated( __METHOD__ . ': $hasHistory parameter', '1.38' );
2706 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2708 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle() );
2712 * Update all the appropriate counts in the category table, given that
2713 * we've added the categories $added and deleted the categories $deleted.
2715 * This should only be called from deferred updates or jobs to avoid contention.
2717 * @param string[] $added The names of categories that were added
2718 * @param string[] $deleted The names of categories that were deleted
2719 * @param int $id Page ID (this should be the original deleted page ID)
2721 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
2722 $id = $id ?: $this->getId();
2723 // Guard against data corruption T301433
2724 $added = array_map( 'strval', $added );
2725 $deleted = array_map( 'strval', $deleted );
2726 $type = MediaWikiServices::getInstance()->getNamespaceInfo()->
2727 getCategoryLinkType( $this->getTitle()->getNamespace() );
2729 $addFields = [ 'cat_pages' => new RawSQLValue( 'cat_pages + 1' ) ];
2730 $removeFields = [ 'cat_pages' => new RawSQLValue( 'cat_pages - 1' ) ];
2731 if ( $type !== 'page' ) {
2732 $addFields["cat_{$type}s"] = new RawSQLValue( "cat_{$type}s + 1" );
2733 $removeFields["cat_{$type}s"] = new RawSQLValue( "cat_{$type}s - 1" );
2736 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2737 $res = $dbw->newSelectQueryBuilder()
2738 ->select( [ 'cat_id', 'cat_title' ] )
2739 ->from( 'category' )
2740 ->where( [ 'cat_title' => array_merge( $added, $deleted ) ] )
2741 ->caller( __METHOD__ )
2742 ->fetchResultSet();
2743 $existingCategories = [];
2744 foreach ( $res as $row ) {
2745 $existingCategories[$row->cat_id] = $row->cat_title;
2747 $existingAdded = array_intersect( $existingCategories, $added );
2748 $existingDeleted = array_intersect( $existingCategories, $deleted );
2749 $missingAdded = array_diff( $added, $existingAdded );
2751 // For category rows that already exist, do a plain
2752 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
2753 // to avoid creating gaps in the cat_id sequence.
2754 if ( $existingAdded ) {
2755 $dbw->newUpdateQueryBuilder()
2756 ->update( 'category' )
2757 ->set( $addFields )
2758 ->where( [ 'cat_id' => array_keys( $existingAdded ) ] )
2759 ->caller( __METHOD__ )->execute();
2762 if ( $missingAdded ) {
2763 $queryBuilder = $dbw->newInsertQueryBuilder()
2764 ->insertInto( 'category' )
2765 ->onDuplicateKeyUpdate()
2766 ->uniqueIndexFields( [ 'cat_title' ] )
2767 ->set( $addFields );
2768 foreach ( $missingAdded as $cat ) {
2769 $queryBuilder->row( [
2770 'cat_title' => $cat,
2771 'cat_pages' => 1,
2772 'cat_subcats' => ( $type === 'subcat' ) ? 1 : 0,
2773 'cat_files' => ( $type === 'file' ) ? 1 : 0,
2774 ] );
2776 $queryBuilder->caller( __METHOD__ )->execute();
2779 if ( $existingDeleted ) {
2780 $dbw->newUpdateQueryBuilder()
2781 ->update( 'category' )
2782 ->set( $removeFields )
2783 ->where( [ 'cat_id' => array_keys( $existingDeleted ) ] )
2784 ->caller( __METHOD__ )->execute();
2787 foreach ( $added as $catName ) {
2788 $cat = Category::newFromName( $catName );
2789 $this->getHookRunner()->onCategoryAfterPageAdded( $cat, $this );
2792 foreach ( $deleted as $catName ) {
2793 $cat = Category::newFromName( $catName );
2794 $this->getHookRunner()->onCategoryAfterPageRemoved( $cat, $this, $id );
2795 // Refresh counts on categories that should be empty now (after commit, T166757)
2796 DeferredUpdates::addCallableUpdate( static function () use ( $cat ) {
2797 $cat->refreshCountsIfEmpty();
2798 } );
2803 * Opportunistically enqueue link update jobs after a fresh parser output was generated.
2805 * This method should only be called by PoolWorkArticleViewCurrent, after a page view
2806 * experienced a miss from the ParserCache, and a new ParserOutput was generated.
2807 * Specifically, for load reasons, this method must not get called during page views that
2808 * use a cached ParserOutput.
2810 * @since 1.25
2811 * @internal For use by PoolWorkArticleViewCurrent
2812 * @param ParserOutput $parserOutput Current version page output
2814 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
2815 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2816 return;
2819 if ( !$this->getHookRunner()->onOpportunisticLinksUpdate( $this,
2820 $this->mTitle, $parserOutput )
2822 return;
2825 $config = MediaWikiServices::getInstance()->getMainConfig();
2827 $params = [
2828 'isOpportunistic' => true,
2829 'rootJobTimestamp' => $parserOutput->getCacheTime()
2832 if ( MediaWikiServices::getInstance()->getRestrictionStore()->areRestrictionsCascading( $this->mTitle ) ) {
2833 // In general, MediaWiki does not re-run LinkUpdate (e.g. for search index, category
2834 // listings, and backlinks for Whatlinkshere), unless either the page was directly
2835 // edited, or was re-generate following a template edit propagating to an affected
2836 // page. As such, during page views when there is no valid ParserCache entry,
2837 // we re-parse and save, but leave indexes as-is.
2839 // We make an exception for pages that have cascading protection (perhaps for a wiki's
2840 // "Main Page"). When such page is re-parsed on-demand after a parser cache miss, we
2841 // queue a high-priority LinksUpdate job, to ensure that we really protect all
2842 // content that is currently transcluded onto the page. This is important, because
2843 // wikitext supports conditional statements based on the current time, which enables
2844 // transcluding of a different subpage based on which day it is, and then show that
2845 // information on the Main Page, without the Main Page itself being edited.
2846 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush(
2847 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
2849 } elseif ( !$config->get( MainConfigNames::MiserMode ) &&
2850 $parserOutput->hasReducedExpiry()
2852 // Assume the output contains "dynamic" time/random based magic words.
2853 // Only update pages that expired due to dynamic content and NOT due to edits
2854 // to referenced templates/files. When the cache expires due to dynamic content,
2855 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
2856 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
2857 // template/file edit already triggered recursive RefreshLinksJob jobs.
2858 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
2859 // If a page is uncacheable, do not keep spamming a job for it.
2860 // Although it would be de-duplicated, it would still waste I/O.
2861 $services = MediaWikiServices::getInstance()->getObjectCacheFactory();
2862 $cache = $services->getLocalClusterInstance();
2863 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
2864 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
2865 if ( $cache->add( $key, time(), $ttl ) ) {
2866 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush(
2867 RefreshLinksJob::newDynamic( $this->mTitle, $params )
2875 * Whether this content displayed on this page
2876 * comes from the local database
2878 * @since 1.28
2879 * @return bool
2881 public function isLocal() {
2882 return true;
2886 * The display name for the site this content
2887 * come from. If a subclass overrides isLocal(),
2888 * this could return something other than the
2889 * current site name
2891 * @since 1.28
2892 * @return string
2894 public function getWikiDisplayName() {
2895 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get(
2896 MainConfigNames::Sitename );
2897 return $sitename;
2901 * Get the source URL for the content on this page,
2902 * typically the canonical URL, but may be a remote
2903 * link if the content comes from another site
2905 * @since 1.28
2906 * @return string
2908 public function getSourceURL() {
2909 return $this->getTitle()->getCanonicalURL();
2913 * Ensure consistency when unserializing.
2914 * @note WikiPage objects should never be serialized in the first place.
2915 * But some extensions like AbuseFilter did (see T213006),
2916 * and we need to be able to read old data (see T187153).
2918 public function __wakeup() {
2919 // Make sure we re-fetch the latest state from the database.
2920 // In particular, the latest revision may have changed.
2921 // As a side-effect, this makes sure mLastRevision doesn't
2922 // end up being an instance of the old Revision class (see T259181),
2923 // especially since that class was removed entirely in 1.37.
2924 $this->clear();
2928 * @inheritDoc
2929 * @since 1.36
2931 public function getNamespace(): int {
2932 return $this->getTitle()->getNamespace();
2936 * @inheritDoc
2937 * @since 1.36
2939 public function getDBkey(): string {
2940 return $this->getTitle()->getDBkey();
2944 * @return false self::LOCAL
2945 * @since 1.36
2947 public function getWikiId() {
2948 return $this->getTitle()->getWikiId();
2952 * @return true
2953 * @since 1.36
2955 public function canExist(): bool {
2956 return true;
2960 * @inheritDoc
2961 * @since 1.36
2963 public function __toString(): string {
2964 return $this->mTitle->__toString();
2968 * @inheritDoc
2969 * @since 1.36
2971 public function isSamePageAs( PageReference $other ): bool {
2972 // NOTE: keep in sync with PageReferenceValue::isSamePageAs()!
2973 return $this->getWikiId() === $other->getWikiId()
2974 && $this->getNamespace() === $other->getNamespace()
2975 && $this->getDBkey() === $other->getDBkey();
2979 * Returns the page represented by this WikiPage as a PageStoreRecord.
2980 * The PageRecord returned by this method is guaranteed to be immutable.
2982 * It is preferred to use this method rather than using the WikiPage as a PageIdentity directly.
2983 * @since 1.36
2985 * @throws PreconditionException if the page does not exist.
2987 * @return ExistingPageRecord
2989 public function toPageRecord(): ExistingPageRecord {
2990 // TODO: replace individual member fields with a PageRecord instance that is always present
2992 if ( !$this->mDataLoaded ) {
2993 $this->loadPageData();
2996 Assert::precondition(
2997 $this->exists(),
2998 'This WikiPage instance does not represent an existing page: ' . $this->mTitle
3001 return new PageStoreRecord(
3002 (object)[
3003 'page_id' => $this->getId(),
3004 'page_namespace' => $this->mTitle->getNamespace(),
3005 'page_title' => $this->mTitle->getDBkey(),
3006 'page_latest' => $this->mLatest,
3007 'page_is_new' => $this->mIsNew ? 1 : 0,
3008 'page_is_redirect' => $this->mPageIsRedirectField ? 1 : 0,
3009 'page_touched' => $this->getTouched(),
3010 'page_lang' => $this->getLanguage()
3012 PageIdentity::LOCAL