Debian Codegraph @

includes/page/WikiPage.php

raw symbols SCIP
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
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\UserArrayFromResult;
59 use MediaWiki\User\UserIdentity;
60 use MediaWiki\Utils\MWTimestamp;
61 use MediaWiki\WikiMap\WikiMap;
62 use Wikimedia\Assert\Assert;
63 use Wikimedia\Assert\PreconditionException;
64 use Wikimedia\NonSerializable\NonSerializableTrait;
65 use Wikimedia\Rdbms\FakeResultWrapper;
66 use Wikimedia\Rdbms\IDatabase;
67 use Wikimedia\Rdbms\IDBAccessObject;
68 use Wikimedia\Rdbms\ILoadBalancer;
69 use Wikimedia\Rdbms\IReadableDatabase;
70 use Wikimedia\Rdbms\RawSQLValue;
71 use Wikimedia\Rdbms\SelectQueryBuilder;
72
73 /**
74 * @defgroup Page Page
75 */
76
77 /**
78 * Base representation for an editable wiki page.
79 *
80 * Some fields are public only for backwards-compatibility. Use accessor methods.
81 * In the past, this class was part of Article.php and everything was public.
82 *
83 * @ingroup Page
84 */
85 class WikiPage implements Stringable, Page, PageRecord {
86 use NonSerializableTrait;
87 use ProtectedHookAccessorTrait;
88 use WikiAwareEntityTrait;
89
90 // Constants for $mDataLoadedFrom and related
91
92 /**
93 * @var Title
94 * @note for access by subclasses only
95 */
96 protected $mTitle;
97
98 /**
99 * @var bool
100 * @note for access by subclasses only
101 */
102 protected $mDataLoaded = false;
103
104 /**
105 * A cache of the page_is_redirect field, loaded with page data
106 * @var bool
107 */
108 private $mPageIsRedirectField = false;
109
110 /**
111 * @var bool
112 */
113 private $mIsNew = false;
114
115 /**
116 * @var int|false False means "not loaded"
117 * @note for access by subclasses only
118 */
119 protected $mLatest = false;
120
121 /**
122 * @var PreparedEdit|false Map of cache fields (text, parser output, ect) for a proposed/new edit
123 * @note for access by subclasses only
124 */
125 protected $mPreparedEdit = false;
126
127 /**
128 * @var int|null
129 */
130 protected $mId = null;
131
132 /**
133 * @var int One of the READ_* constants
134 */
135 protected $mDataLoadedFrom = IDBAccessObject::READ_NONE;
136
137 /**
138 * @var RevisionRecord|null
139 */
140 private $mLastRevision = null;
141
142 /**
143 * @var string Timestamp of the current revision or empty string if not loaded
144 */
145 protected $mTimestamp = '';
146
147 /**
148 * @var string
149 */
150 protected $mTouched = '19700101000000';
151
152 /**
153 * @var string|null
154 */
155 protected $mLanguage = null;
156
157 /**
158 * @var string
159 */
160 protected $mLinksUpdated = '19700101000000';
161
162 /**
163 * @var DerivedPageDataUpdater|null
164 */
165 private $derivedDataUpdater = null;
166
167 /**
168 * @param PageIdentity $pageIdentity
169 */
170 public function __construct( PageIdentity $pageIdentity ) {
171 $pageIdentity->assertWiki( PageIdentity::LOCAL );
172
173 // TODO: remove the need for casting to Title.
174 $title = Title::newFromPageIdentity( $pageIdentity );
175 if ( !$title->canExist() ) {
176 throw new InvalidArgumentException( "WikiPage constructed on a Title that cannot exist as a page: $title" );
177 }
178
179 $this->mTitle = $title;
180 }
181
182 /**
183 * Makes sure that the mTitle object is cloned
184 * to the newly cloned WikiPage.
185 */
186 public function __clone() {
187 $this->mTitle = clone $this->mTitle;
188 }
189
190 /**
191 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
192 *
193 * @param stdClass|string|int $type
194 * @return mixed
195 */
196 public static function convertSelectType( $type ) {
197 switch ( $type ) {
198 case 'fromdb':
199 return IDBAccessObject::READ_NORMAL;
200 case 'fromdbmaster':
201 return IDBAccessObject::READ_LATEST;
202 case 'forupdate':
203 return IDBAccessObject::READ_LOCKING;
204 default:
205 // It may already be an integer or whatever else
206 return $type;
207 }
208 }
209
210 /**
211 * @return PageUpdaterFactory
212 */
213 private function getPageUpdaterFactory(): PageUpdaterFactory {
214 return MediaWikiServices::getInstance()->getPageUpdaterFactory();
215 }
216
217 /**
218 * @return RevisionStore
219 */
220 private function getRevisionStore() {
221 return MediaWikiServices::getInstance()->getRevisionStore();
222 }
223
224 /**
225 * @return ILoadBalancer
226 */
227 private function getDBLoadBalancer() {
228 return MediaWikiServices::getInstance()->getDBLoadBalancer();
229 }
230
231 /**
232 * @todo Move this UI stuff somewhere else
233 *
234 * @see ContentHandler::getActionOverrides
235 * @return array
236 */
237 public function getActionOverrides() {
238 return $this->getContentHandler()->getActionOverrides();
239 }
240
241 /**
242 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
243 *
244 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
245 *
246 * @return ContentHandler
247 *
248 * @since 1.21
249 */
250 public function getContentHandler() {
251 $factory = MediaWikiServices::getInstance()->getContentHandlerFactory();
252 return $factory->getContentHandler( $this->getContentModel() );
253 }
254
255 /**
256 * Get the title object of the article
257 * @return Title Title object of this page
258 */
259 public function getTitle(): Title {
260 return $this->mTitle;
261 }
262
263 /**
264 * Clear the object
265 * @return void
266 */
267 public function clear() {
268 $this->mDataLoaded = false;
269 $this->mDataLoadedFrom = IDBAccessObject::READ_NONE;
270
271 $this->clearCacheFields();
272 }
273
274 /**
275 * Clear the object cache fields
276 * @return void
277 */
278 protected function clearCacheFields() {
279 $this->mId = null;
280 $this->mPageIsRedirectField = false;
281 $this->mLastRevision = null; // Latest revision
282 $this->mTouched = '19700101000000';
283 $this->mLanguage = null;
284 $this->mLinksUpdated = '19700101000000';
285 $this->mTimestamp = '';
286 $this->mIsNew = false;
287 $this->mLatest = false;
288 // T59026: do not clear $this->derivedDataUpdater since getDerivedDataUpdater() already
289 // checks the requested rev ID and content against the cached one. For most
290 // content types, the output should not change during the lifetime of this cache.
291 // Clearing it can cause extra parses on edit for no reason.
292 }
293
294 /**
295 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
296 * @return void
297 * @since 1.23
298 */
299 public function clearPreparedEdit() {
300 $this->mPreparedEdit = false;
301 }
302
303 /**
304 * Return the tables, fields, and join conditions to be selected to create
305 * a new page object.
306 * @since 1.31
307 * @return array[] With three keys:
308 * - tables: (string[]) to include in the `$table` to `IReadableDatabase->select()` or
309 * `SelectQueryBuilder::tables`
310 * - fields: (string[]) to include in the `$vars` to `IReadableDatabase->select()` or
311 * `SelectQueryBuilder::fields`
312 * - joins: (array) to include in the `$join_conds` to `IReadableDatabase->select()` or
313 * `SelectQueryBuilder::joinConds`
314 * @phan-return array{tables:string[],fields:string[],joins:array}
315 */
316 public static function getQueryInfo() {
317 $pageLanguageUseDB = MediaWikiServices::getInstance()->getMainConfig()->get(
318 MainConfigNames::PageLanguageUseDB );
319
320 $ret = [
321 'tables' => [ 'page' ],
322 'fields' => [
323 'page_id',
324 'page_namespace',
325 'page_title',
326 'page_is_redirect',
327 'page_is_new',
328 'page_random',
329 'page_touched',
330 'page_links_updated',
331 'page_latest',
332 'page_len',
333 'page_content_model',
334 ],
335 'joins' => [],
336 ];
337
338 if ( $pageLanguageUseDB ) {
339 $ret['fields'][] = 'page_lang';
340 }
341
342 return $ret;
343 }
344
345 /**
346 * Fetch a page record with the given conditions
347 * @param IReadableDatabase $dbr
348 * @param array $conditions
349 * @param array $options
350 * @return stdClass|false Database result resource, or false on failure
351 */
352 protected function pageData( $dbr, $conditions, $options = [] ) {
353 $pageQuery = self::getQueryInfo();
354
355 $this->getHookRunner()->onArticlePageDataBefore(
356 $this, $pageQuery['fields'], $pageQuery['tables'], $pageQuery['joins'] );
357
358 $row = $dbr->newSelectQueryBuilder()
359 ->queryInfo( $pageQuery )
360 ->where( $conditions )
361 ->caller( __METHOD__ )
362 ->options( $options )
363 ->fetchRow();
364
365 $this->getHookRunner()->onArticlePageDataAfter( $this, $row );
366
367 return $row;
368 }
369
370 /**
371 * Fetch a page record matching the Title object's namespace and title
372 * using a sanitized title string
373 *
374 * @param IReadableDatabase $dbr
375 * @param Title $title
376 * @param int $recency
377 * @return stdClass|false Database result resource, or false on failure
378 */
379 public function pageDataFromTitle( $dbr, $title, $recency = IDBAccessObject::READ_NORMAL ) {
380 if ( !$title->canExist() ) {
381 return false;
382 }
383 $options = [];
384 if ( ( $recency & IDBAccessObject::READ_EXCLUSIVE ) == IDBAccessObject::READ_EXCLUSIVE ) {
385 $options[] = 'FOR UPDATE';
386 } elseif ( ( $recency & IDBAccessObject::READ_LOCKING ) == IDBAccessObject::READ_LOCKING ) {
387 $options[] = 'LOCK IN SHARE MODE';
388 }
389
390 return $this->pageData( $dbr, [
391 'page_namespace' => $title->getNamespace(),
392 'page_title' => $title->getDBkey() ], $options );
393 }
394
395 /**
396 * Fetch a page record matching the requested ID
397 *
398 * @param IReadableDatabase $dbr
399 * @param int $id
400 * @param array $options
401 * @return stdClass|false Database result resource, or false on failure
402 */
403 public function pageDataFromId( $dbr, $id, $options = [] ) {
404 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
405 }
406
407 /**
408 * Load the object from a given source by title
409 *
410 * @param stdClass|string|int $from One of the following:
411 * - A DB query result object.
412 * - "fromdb" or IDBAccessObject::READ_NORMAL to get from a replica DB.
413 * - "fromdbmaster" or IDBAccessObject::READ_LATEST to get from the primary DB.
414 * - "forupdate" or IDBAccessObject::READ_LOCKING to get from the primary DB
415 * using SELECT FOR UPDATE.
416 *
417 * @return void
418 */
419 public function loadPageData( $from = 'fromdb' ) {
420 $from = self::convertSelectType( $from );
421 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
422 // We already have the data from the correct location, no need to load it twice.
423 return;
424 }
425
426 if ( is_int( $from ) ) {
427 $loadBalancer = $this->getDBLoadBalancer();
428 if ( ( $from & IDBAccessObject::READ_LATEST ) == IDBAccessObject::READ_LATEST ) {
429 $index = DB_PRIMARY;
430 } else {
431 $index = DB_REPLICA;
432 }
433 $db = $loadBalancer->getConnection( $index );
434 $data = $this->pageDataFromTitle( $db, $this->mTitle, $from );
435
436 if ( !$data
437 && $index == DB_REPLICA
438 && $loadBalancer->hasReplicaServers()
439 && $loadBalancer->hasOrMadeRecentPrimaryChanges()
440 ) {
441 $from = IDBAccessObject::READ_LATEST;
442 $db = $loadBalancer->getConnection( DB_PRIMARY );
443 $data = $this->pageDataFromTitle( $db, $this->mTitle, $from );
444 }
445 } else {
446 // No idea from where the caller got this data, assume replica DB.
447 $data = $from;
448 $from = IDBAccessObject::READ_NORMAL;
449 }
450
451 $this->loadFromRow( $data, $from );
452 }
453
454 /**
455 * Checks whether the page data was loaded using the given database access mode (or better).
456 *
457 * @since 1.32
458 *
459 * @param string|int $from One of the following:
460 * - "fromdb" or IDBAccessObject::READ_NORMAL to get from a replica DB.
461 * - "fromdbmaster" or IDBAccessObject::READ_LATEST to get from the primary DB.
462 * - "forupdate" or IDBAccessObject::READ_LOCKING to get from the primary DB
463 * using SELECT FOR UPDATE.
464 *
465 * @return bool
466 */
467 public function wasLoadedFrom( $from ) {
468 $from = self::convertSelectType( $from );
469
470 if ( !is_int( $from ) ) {
471 // No idea from where the caller got this data, assume replica DB.
472 $from = IDBAccessObject::READ_NORMAL;
473 }
474
475 if ( $from <= $this->mDataLoadedFrom ) {
476 return true;
477 }
478
479 return false;
480 }
481
482 /**
483 * Load the object from a database row
484 *
485 * @since 1.20
486 * @param stdClass|false $data DB row containing fields returned by getQueryInfo() or false
487 * @param string|int $from One of the following:
488 * - "fromdb" or IDBAccessObject::READ_NORMAL if the data comes from a replica DB
489 * - "fromdbmaster" or IDBAccessObject::READ_LATEST if the data comes from the primary DB
490 * - "forupdate" or IDBAccessObject::READ_LOCKING if the data comes from
491 * the primary DB using SELECT FOR UPDATE
492 */
493 public function loadFromRow( $data, $from ) {
494 $lc = MediaWikiServices::getInstance()->getLinkCache();
495 $lc->clearLink( $this->mTitle );
496
497 if ( $data ) {
498 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
499
500 $this->mTitle->loadFromRow( $data );
501 $this->mId = intval( $data->page_id );
502 $this->mTouched = MWTimestamp::convert( TS_MW, $data->page_touched );
503 $this->mLanguage = $data->page_lang ?? null;
504 $this->mLinksUpdated = $data->page_links_updated === null
505 ? null
506 : MWTimestamp::convert( TS_MW, $data->page_links_updated );
507 $this->mPageIsRedirectField = (bool)$data->page_is_redirect;
508 $this->mIsNew = (bool)( $data->page_is_new ?? 0 );
509 $this->mLatest = intval( $data->page_latest );
510 // T39225: $latest may no longer match the cached latest RevisionRecord object.
511 // Double-check the ID of any cached latest RevisionRecord object for consistency.
512 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
513 $this->mLastRevision = null;
514 $this->mTimestamp = '';
515 }
516 } else {
517 $lc->addBadLinkObj( $this->mTitle );
518
519 $this->mTitle->loadFromRow( false );
520
521 $this->clearCacheFields();
522
523 $this->mId = 0;
524 }
525
526 $this->mDataLoaded = true;
527 $this->mDataLoadedFrom = self::convertSelectType( $from );
528 }
529
530 /**
531 * @param string|false $wikiId
532 *
533 * @return int Page ID
534 */
535 public function getId( $wikiId = self::LOCAL ): int {
536 $this->assertWiki( $wikiId );
537
538 if ( !$this->mDataLoaded ) {
539 $this->loadPageData();
540 }
541 return $this->mId;
542 }
543
544 /**
545 * @return bool Whether or not the page exists in the database
546 */
547 public function exists(): bool {
548 if ( !$this->mDataLoaded ) {
549 $this->loadPageData();
550 }
551 return $this->mId > 0;
552 }
553
554 /**
555 * Check if this page is something we're going to be showing
556 * some sort of sensible content for. If we return false, page
557 * views (plain action=view) will return an HTTP 404 response,
558 * so spiders and robots can know they're following a bad link.
559 *
560 * @return bool
561 */
562 public function hasViewableContent() {
563 return $this->mTitle->isKnown();
564 }
565
566 /**
567 * Is the page a redirect, according to secondary tracking tables?
568 * If this is true, getRedirectTarget() will return a Title.
569 *
570 * @return bool
571 */
572 public function isRedirect() {
573 $this->loadPageData();
574 if ( $this->mPageIsRedirectField ) {
575 return MediaWikiServices::getInstance()->getRedirectLookup()
576 ->getRedirectTarget( $this->getTitle() ) !== null;
577 }
578
579 return false;
580 }
581
582 /**
583 * Tests if the page is new (only has one revision).
584 * May produce false negatives for some old pages.
585 *
586 * @since 1.36
587 *
588 * @return bool
589 */
590 public function isNew() {
591 if ( !$this->mDataLoaded ) {
592 $this->loadPageData();
593 }
594
595 return $this->mIsNew;
596 }
597
598 /**
599 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
600 *
601 * Will use the revisions actual content model if the page exists,
602 * and the page's default if the page doesn't exist yet.
603 *
604 * @return string
605 *
606 * @since 1.21
607 */
608 public function getContentModel() {
609 if ( $this->exists() ) {
610 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
611
612 return $cache->getWithSetCallback(
613 $cache->makeKey( 'page-content-model', $this->getLatest() ),
614 $cache::TTL_MONTH,
615 function () {
616 $rev = $this->getRevisionRecord();
617 if ( $rev ) {
618 // Look at the revision's actual content model
619 $slot = $rev->getSlot(
620 SlotRecord::MAIN,
621 RevisionRecord::RAW
622 );
623 return $slot->getModel();
624 } else {
625 LoggerFactory::getInstance( 'wikipage' )->warning(
626 'Page exists but has no (visible) revisions!',
627 [
628 'page-title' => $this->mTitle->getPrefixedDBkey(),
629 'page-id' => $this->getId(),
630 ]
631 );
632 return $this->mTitle->getContentModel();
633 }
634 },
635 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
636 );
637 }
638
639 // use the default model for this page
640 return $this->mTitle->getContentModel();
641 }
642
643 /**
644 * Loads page_touched and returns a value indicating if it should be used
645 * @return bool True if this page exists and is not a redirect
646 */
647 public function checkTouched() {
648 return ( $this->exists() && !$this->isRedirect() );
649 }
650
651 /**
652 * Get the page_touched field
653 * @return string Timestamp in TS_MW format
654 */
655 public function getTouched() {
656 if ( !$this->mDataLoaded ) {
657 $this->loadPageData();
658 }
659 return $this->mTouched;
660 }
661
662 /**
663 * @return ?string language code for the page
664 */
665 public function getLanguage() {
666 if ( !$this->mDataLoaded ) {
667 $this->loadLastEdit();
668 }
669
670 return $this->mLanguage;
671 }
672
673 /**
674 * Get the page_links_updated field
675 * @return string|null Timestamp in TS_MW format
676 */
677 public function getLinksTimestamp() {
678 if ( !$this->mDataLoaded ) {
679 $this->loadPageData();
680 }
681 return $this->mLinksUpdated;
682 }
683
684 /**
685 * Get the page_latest field
686 * @param string|false $wikiId
687 * @return int The rev_id of current revision
688 */
689 public function getLatest( $wikiId = self::LOCAL ) {
690 $this->assertWiki( $wikiId );
691
692 if ( !$this->mDataLoaded ) {
693 $this->loadPageData();
694 }
695 return (int)$this->mLatest;
696 }
697
698 /**
699 * Loads everything except the text
700 * This isn't necessary for all uses, so it's only done if needed.
701 */
702 protected function loadLastEdit() {
703 if ( $this->mLastRevision !== null ) {
704 return; // already loaded
705 }
706
707 $latest = $this->getLatest();
708 if ( !$latest ) {
709 return; // page doesn't exist or is missing page_latest info
710 }
711
712 if ( $this->mDataLoadedFrom == IDBAccessObject::READ_LOCKING ) {
713 // T39225: if session S1 loads the page row FOR UPDATE, the result always
714 // includes the latest changes committed. This is true even within REPEATABLE-READ
715 // transactions, where S1 normally only sees changes committed before the first S1
716 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
717 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
718 // happened after the first S1 SELECT.
719 // https://dev.mysql.com/doc/refman/5.7/en/set-transaction.html#isolevel_repeatable-read
720 $revision = $this->getRevisionStore()
721 ->getRevisionByPageId( $this->getId(), $latest, IDBAccessObject::READ_LOCKING );
722 } elseif ( $this->mDataLoadedFrom == IDBAccessObject::READ_LATEST ) {
723 // Bug T93976: if page_latest was loaded from the primary DB, fetch the
724 // revision from there as well, as it may not exist yet on a replica DB.
725 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
726 $revision = $this->getRevisionStore()
727 ->getRevisionByPageId( $this->getId(), $latest, IDBAccessObject::READ_LATEST );
728 } else {
729 $revision = $this->getRevisionStore()->getKnownCurrentRevision( $this->getTitle(), $latest );
730 }
731
732 if ( $revision ) {
733 $this->setLastEdit( $revision );
734 }
735 }
736
737 /**
738 * Set the latest revision
739 * @param RevisionRecord $revRecord
740 */
741 private function setLastEdit( RevisionRecord $revRecord ) {
742 $this->mLastRevision = $revRecord;
743 $this->mLatest = $revRecord->getId();
744 $this->mTimestamp = $revRecord->getTimestamp();
745 $this->mTouched = max( $this->mTouched, $revRecord->getTimestamp() );
746 }
747
748 /**
749 * Get the latest revision
750 * @since 1.32
751 * @return RevisionRecord|null
752 */
753 public function getRevisionRecord() {
754 $this->loadLastEdit();
755 return $this->mLastRevision;
756 }
757
758 /**
759 * Get the content of the current revision. No side-effects...
760 *
761 * @param int $audience One of:
762 * RevisionRecord::FOR_PUBLIC to be displayed to all users
763 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
764 * RevisionRecord::RAW get the text regardless of permissions
765 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
766 * to the $audience parameter
767 * @return Content|null The content of the current revision
768 *
769 * @since 1.21
770 */
771 public function getContent( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
772 $this->loadLastEdit();
773 if ( $this->mLastRevision ) {
774 return $this->mLastRevision->getContent( SlotRecord::MAIN, $audience, $performer );
775 }
776 return null;
777 }
778
779 /**
780 * @return string MW timestamp of last article revision
781 */
782 public function getTimestamp() {
783 // Check if the field has been filled by WikiPage::setTimestamp()
784 if ( !$this->mTimestamp ) {
785 $this->loadLastEdit();
786 }
787
788 return MWTimestamp::convert( TS_MW, $this->mTimestamp );
789 }
790
791 /**
792 * Set the page timestamp (use only to avoid DB queries)
793 * @param string $ts MW timestamp of last article revision
794 * @return void
795 */
796 public function setTimestamp( $ts ) {
797 $this->mTimestamp = MWTimestamp::convert( TS_MW, $ts );
798 }
799
800 /**
801 * @param int $audience One of:
802 * RevisionRecord::FOR_PUBLIC to be displayed to all users
803 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
804 * RevisionRecord::RAW get the text regardless of permissions
805 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
806 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
807 * a user no fallback is provided and the RevisionRecord method will throw an error)
808 * @return int User ID for the user that made the last article revision
809 */
810 public function getUser( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
811 $this->loadLastEdit();
812 if ( $this->mLastRevision ) {
813 $revUser = $this->mLastRevision->getUser( $audience, $performer );
814 return $revUser ? $revUser->getId() : 0;
815 } else {
816 return -1;
817 }
818 }
819
820 /**
821 * Get the User object of the user who created the page
822 * @param int $audience One of:
823 * RevisionRecord::FOR_PUBLIC to be displayed to all users
824 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
825 * RevisionRecord::RAW get the text regardless of permissions
826 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
827 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
828 * a user no fallback is provided and the RevisionRecord method will throw an error)
829 * @return UserIdentity|null
830 */
831 public function getCreator( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
832 $revRecord = $this->getRevisionStore()->getFirstRevision( $this->getTitle() );
833 if ( $revRecord ) {
834 return $revRecord->getUser( $audience, $performer );
835 } else {
836 return null;
837 }
838 }
839
840 /**
841 * @param int $audience One of:
842 * RevisionRecord::FOR_PUBLIC to be displayed to all users
843 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
844 * RevisionRecord::RAW get the text regardless of permissions
845 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
846 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
847 * a user no fallback is provided and the RevisionRecord method will throw an error)
848 * @return string Username of the user that made the last article revision
849 */
850 public function getUserText( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
851 $this->loadLastEdit();
852 if ( $this->mLastRevision ) {
853 $revUser = $this->mLastRevision->getUser( $audience, $performer );
854 return $revUser ? $revUser->getName() : '';
855 } else {
856 return '';
857 }
858 }
859
860 /**
861 * @param int $audience One of:
862 * RevisionRecord::FOR_PUBLIC to be displayed to all users
863 * RevisionRecord::FOR_THIS_USER to be displayed to the given user
864 * RevisionRecord::RAW get the text regardless of permissions
865 * @param Authority|null $performer object to check for, only if FOR_THIS_USER is passed
866 * to the $audience parameter (since 1.36, if using FOR_THIS_USER and not specifying
867 * a user no fallback is provided and the RevisionRecord method will throw an error)
868 * @return string|null Comment stored for the last article revision, or null if the specified
869 * audience does not have access to the comment.
870 */
871 public function getComment( $audience = RevisionRecord::FOR_PUBLIC, ?Authority $performer = null ) {
872 $this->loadLastEdit();
873 if ( $this->mLastRevision ) {
874 $revComment = $this->mLastRevision->getComment( $audience, $performer );
875 return $revComment ? $revComment->text : '';
876 } else {
877 return '';
878 }
879 }
880
881 /**
882 * Returns true if last revision was marked as "minor edit"
883 *
884 * @return bool Minor edit indicator for the last article revision.
885 */
886 public function getMinorEdit() {
887 $this->loadLastEdit();
888 if ( $this->mLastRevision ) {
889 return $this->mLastRevision->isMinor();
890 } else {
891 return false;
892 }
893 }
894
895 /**
896 * Determine whether a page would be suitable for being counted as an
897 * article in the site_stats table based on the title & its content
898 *
899 * @param PreparedEdit|PreparedUpdate|false $editInfo (false):
900 * An object returned by prepareTextForEdit() or getCurrentUpdate() respectively;
901 * If false is given, the current database state will be used.
902 *
903 * @return bool
904 */
905 public function isCountable( $editInfo = false ) {
906 $mwServices = MediaWikiServices::getInstance();
907 $articleCountMethod = $mwServices->getMainConfig()->get( MainConfigNames::ArticleCountMethod );
908
909 // NOTE: Keep in sync with DerivedPageDataUpdater::isCountable.
910
911 if ( !$this->mTitle->isContentPage() ) {
912 return false;
913 }
914
915 if ( $editInfo instanceof PreparedEdit ) {
916 // NOTE: only the main slot can make a page a redirect
917 $content = $editInfo->pstContent;
918 } elseif ( $editInfo instanceof PreparedUpdate ) {
919 // NOTE: only the main slot can make a page a redirect
920 $content = $editInfo->getRawContent( SlotRecord::MAIN );
921 } else {
922 $content = $this->getContent();
923 }
924
925 if ( !$content || $content->isRedirect() ) {
926 return false;
927 }
928
929 $hasLinks = null;
930
931 if ( $articleCountMethod === 'link' ) {
932 // nasty special case to avoid re-parsing to detect links
933
934 if ( $editInfo ) {
935 // ParserOutput::getLinks() is a 2D array of page links, so
936 // to be really correct we would need to recurse in the array
937 // but the main array should only have items in it if there are
938 // links.
939 $hasLinks = (bool)count( $editInfo->output->getLinks() );
940 } else {
941 // NOTE: keep in sync with RevisionRenderer::getLinkCount
942 // NOTE: keep in sync with DerivedPageDataUpdater::isCountable
943 $dbr = $mwServices->getConnectionProvider()->getReplicaDatabase();
944 $hasLinks = (bool)$dbr->newSelectQueryBuilder()
945 ->select( '1' )
946 ->from( 'pagelinks' )
947 ->where( [ 'pl_from' => $this->getId() ] )
948 ->caller( __METHOD__ )->fetchField();
949 }
950 }
951
952 // TODO: MCR: determine $hasLinks for each slot, and use that info
953 // with that slot's Content's isCountable method. That requires per-
954 // slot ParserOutput in the ParserCache, or per-slot info in the
955 // pagelinks table.
956 return $content->isCountable( $hasLinks );
957 }
958
959 /**
960 * If this page is a redirect, get its target
961 *
962 * The target will be fetched from the redirect table if possible.
963 *
964 * @deprecated since 1.38 Use RedirectLookup::getRedirectTarget() instead.
965 *
966 * @return Title|null Title object, or null if this page is not a redirect
967 */
968 public function getRedirectTarget() {
969 $target = MediaWikiServices::getInstance()->getRedirectLookup()->getRedirectTarget( $this );
970 return Title::castFromLinkTarget( $target );
971 }
972
973 /**
974 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
975 * @deprecated since 1.43; use {@link RedirectStore::updateRedirectTarget()} instead.
976 * @param LinkTarget $rt Redirect target
977 * @param int|null $oldLatest Prior page_latest for check and set
978 * @return bool Success
979 */
980 public function insertRedirectEntry( LinkTarget $rt, $oldLatest = null ) {
981 return MediaWikiServices::getInstance()->getRedirectStore()
982 ->updateRedirectTarget( $this, $rt );
983 }
984
985 /**
986 * Get the Title object or URL this page redirects to
987 *
988 * @return bool|Title|string False, Title of in-wiki target, or string with URL
989 */
990 public function followRedirect() {
991 return $this->getRedirectURL( $this->getRedirectTarget() );
992 }
993
994 /**
995 * Get the Title object or URL to use for a redirect. We use Title
996 * objects for same-wiki, non-special redirects and URLs for everything
997 * else.
998 * @param Title $rt Redirect target
999 * @return Title|string|false False, Title object of local target, or string with URL
1000 */
1001 public function getRedirectURL( $rt ) {
1002 if ( !$rt ) {
1003 return false;
1004 }
1005
1006 if ( $rt->isExternal() ) {
1007 if ( $rt->isLocal() ) {
1008 // Offsite wikis need an HTTP redirect.
1009 // This can be hard to reverse and may produce loops,
1010 // so they may be disabled in the site configuration.
1011 $source = $this->mTitle->getFullURL( 'redirect=no' );
1012 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1013 } else {
1014 // External pages without "local" bit set are not valid
1015 // redirect targets
1016 return false;
1017 }
1018 }
1019
1020 if ( $rt->isSpecialPage() ) {
1021 // Gotta handle redirects to special pages differently:
1022 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1023 // Some pages are not valid targets.
1024 if ( $rt->isValidRedirectTarget() ) {
1025 return $rt->getFullURL();
1026 } else {
1027 return false;
1028 }
1029 } elseif ( !$rt->isValidRedirectTarget() ) {
1030 // We somehow got a bad redirect target into the database (T278367)
1031 return false;
1032 }
1033
1034 return $rt;
1035 }
1036
1037 /**
1038 * Get a list of users who have edited this article, not including the user who made
1039 * the most recent revision, which you can get from $article->getUser() if you want it
1040 * @return UserArrayFromResult
1041 */
1042 public function getContributors() {
1043 // @todo: This is expensive; cache this info somewhere.
1044
1045 $services = MediaWikiServices::getInstance();
1046 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
1047 $actorNormalization = $services->getActorNormalization();
1048 $userIdentityLookup = $services->getUserIdentityLookup();
1049
1050 $user = $this->getUser()
1051 ? User::newFromId( $this->getUser() )
1052 : User::newFromName( $this->getUserText(), false );
1053
1054 $res = $dbr->newSelectQueryBuilder()
1055 ->select( [
1056 'user_id' => 'actor_user',
1057 'user_name' => 'actor_name',
1058 'actor_id' => 'MIN(rev_actor)',
1059 'user_real_name' => 'MIN(user_real_name)',
1060 'timestamp' => 'MAX(rev_timestamp)',
1061 ] )
1062 ->from( 'revision' )
1063 ->join( 'actor', null, 'rev_actor = actor_id' )
1064 ->leftJoin( 'user', null, 'actor_user = user_id' )
1065 ->where( [
1066 'rev_page' => $this->getId(),
1067 // The user who made the top revision gets credited as "this page was last edited by
1068 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1069 $dbr->expr( 'rev_actor', '!=', $actorNormalization->findActorId( $user, $dbr ) ),
1070 // Username hidden?
1071 $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0',
1072 ] )
1073 ->groupBy( [ 'actor_user', 'actor_name' ] )
1074 ->orderBy( 'timestamp', SelectQueryBuilder::SORT_DESC )
1075 ->caller( __METHOD__ )
1076 ->fetchResultSet();
1077 return new UserArrayFromResult( $res );
1078 }
1079
1080 /**
1081 * Should the parser cache be used?
1082 *
1083 * @param ParserOptions $parserOptions ParserOptions to check
1084 * @param int $oldId
1085 * @return bool
1086 */
1087 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1088 // NOTE: Keep in sync with ParserOutputAccess::shouldUseCache().
1089 // TODO: Once ParserOutputAccess is stable, deprecated this method.
1090 return $this->exists()
1091 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1092 && $this->getContentHandler()->isParserCacheSupported();
1093 }
1094
1095 /**
1096 * Get a ParserOutput for the given ParserOptions and revision ID.
1097 *
1098 * The parser cache will be used if possible. Cache misses that result
1099 * in parser runs are debounced with PoolCounter.
1100 *
1101 * XXX merge this with updateParserCache()?
1102 *
1103 * @since 1.19
1104 * @param ParserOptions|null $parserOptions ParserOptions to use for the parse operation
1105 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1106 * get the current revision (default value)
1107 * @param bool $noCache Do not read from or write to caches.
1108 * @return ParserOutput|false ParserOutput or false if the revision was not found or is not public
1109 */
1110 public function getParserOutput(
1111 ?ParserOptions $parserOptions = null, $oldid = null, $noCache = false
1112 ) {
1113 if ( $oldid ) {
1114 $revision = $this->getRevisionStore()->getRevisionByTitle( $this->getTitle(), $oldid );
1115
1116 if ( !$revision ) {
1117 return false;
1118 }
1119 } else {
1120 $revision = $this->getRevisionRecord();
1121 }
1122
1123 if ( !$parserOptions ) {
1124 $parserOptions = ParserOptions::newFromAnon();
1125 }
1126
1127 $options = $noCache ? ParserOutputAccess::OPT_NO_CACHE : 0;
1128
1129 $status = MediaWikiServices::getInstance()->getParserOutputAccess()->getParserOutput(
1130 $this, $parserOptions, $revision, $options
1131 );
1132 return $status->isOK() ? $status->getValue() : false; // convert null to false
1133 }
1134
1135 /**
1136 * Do standard deferred updates after page view (existing or missing page)
1137 * @param Authority $performer The viewing user
1138 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1139 * @param RevisionRecord|null $oldRev The RevisionRecord associated with $oldid.
1140 */
1141 public function doViewUpdates(
1142 Authority $performer,
1143 $oldid = 0,
1144 ?RevisionRecord $oldRev = null
1145 ) {
1146 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1147 return;
1148 }
1149
1150 DeferredUpdates::addCallableUpdate(
1151 function () use ( $performer ) {
1152 // In practice, these hook handlers simply debounce into a post-send
1153 // to do their work since none of the use cases for this hook require
1154 // a blocking pre-send callback.
1155 //
1156 // TODO: Move this hook to post-send.
1157 //
1158 // For now, it is unofficially possible for an extension to use
1159 // onPageViewUpdates to try to insert JavaScript via global $wgOut.
1160 // This isn't supported (the hook doesn't pass OutputPage), and
1161 // can't be since OutputPage may be disabled or replaced on some
1162 // pages that we do support page view updates for. We also run
1163 // this hook after HTMLFileCache, which also naturally can't
1164 // support modifying OutputPage. Handlers that modify the page
1165 // may use onBeforePageDisplay instead, which runs behind
1166 // HTMLFileCache and won't run on non-OutputPage responses.
1167 $legacyUser = MediaWikiServices::getInstance()
1168 ->getUserFactory()
1169 ->newFromAuthority( $performer );
1170 $this->getHookRunner()->onPageViewUpdates( $this, $legacyUser );
1171 },
1172 DeferredUpdates::PRESEND
1173 );
1174
1175 // Update newtalk and watchlist notification status
1176 MediaWikiServices::getInstance()
1177 ->getWatchlistManager()
1178 ->clearTitleUserNotifications( $performer, $this, $oldid, $oldRev );
1179 }
1180
1181 /**
1182 * Perform the actions of a page purging
1183 * @return bool
1184 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1185 * controlled how much purging was done.
1186 */
1187 public function doPurge() {
1188 if ( !$this->getHookRunner()->onArticlePurge( $this ) ) {
1189 return false;
1190 }
1191
1192 $this->mTitle->invalidateCache();
1193
1194 // Clear file cache and send purge after above page_touched update was committed
1195 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1196 $hcu->purgeTitleUrls( $this->mTitle, $hcu::PURGE_PRESEND );
1197
1198 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1199 MediaWikiServices::getInstance()->getMessageCache()
1200 ->updateMessageOverride( $this->mTitle, $this->getContent() );
1201 }
1202 InfoAction::invalidateCache( $this->mTitle, $this->getLatest() );
1203
1204 return true;
1205 }
1206
1207 /**
1208 * Insert a new empty page record for this article.
1209 * This *must* be followed up by creating a revision
1210 * and running $this->updateRevisionOn( ... );
1211 * or else the record will be left in a funky state.
1212 * Best if all done inside a transaction.
1213 *
1214 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1215 *
1216 * @param IDatabase $dbw
1217 * @param int|null $pageId Custom page ID that will be used for the insert statement
1218 *
1219 * @return int|false The newly created page_id key; false if the row was not
1220 * inserted, e.g. because the title already existed or because the specified
1221 * page ID is already in use.
1222 */
1223 public function insertOn( $dbw, $pageId = null ) {
1224 $pageIdForInsert = $pageId ? [ 'page_id' => $pageId ] : [];
1225 $dbw->newInsertQueryBuilder()
1226 ->insertInto( 'page' )
1227 ->ignore()
1228 ->row( [
1229 'page_namespace' => $this->mTitle->getNamespace(),
1230 'page_title' => $this->mTitle->getDBkey(),
1231 'page_is_redirect' => 0, // Will set this shortly...
1232 'page_is_new' => 1,
1233 'page_random' => wfRandom(),
1234 'page_touched' => $dbw->timestamp(),
1235 'page_latest' => 0, // Fill this in shortly...
1236 'page_len' => 0, // Fill this in shortly...
1237 ] + $pageIdForInsert )
1238 ->caller( __METHOD__ )->execute();
1239
1240 if ( $dbw->affectedRows() > 0 ) {
1241 $newid = $pageId ? (int)$pageId : $dbw->insertId();
1242 $this->mId = $newid;
1243 $this->mTitle->resetArticleID( $newid );
1244
1245 return $newid;
1246 } else {
1247 return false; // nothing changed
1248 }
1249 }
1250
1251 /**
1252 * Update the page record to point to a newly saved revision.
1253 *
1254 * @todo Factor out into a PageStore service, or move into PageUpdater.
1255 *
1256 * @param IDatabase $dbw
1257 * @param RevisionRecord $revision For ID number, and text used to set
1258 * length and redirect status fields.
1259 * @param int|null $lastRevision If given, will not overwrite the page field
1260 * when different from the currently set value.
1261 * Giving 0 indicates the new page flag should be set on.
1262 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1263 * removing rows in redirect table.
1264 * @return bool Success; false if the page row was missing or page_latest changed
1265 */
1266 public function updateRevisionOn(
1267 $dbw,
1268 RevisionRecord $revision,
1269 $lastRevision = null,
1270 $lastRevIsRedirect = null
1271 ) {
1272 // TODO: move into PageUpdater or PageStore
1273 // NOTE: when doing that, make sure cached fields get reset in doUserEditContent,
1274 // and in the compat stub!
1275
1276 $revId = $revision->getId();
1277 Assert::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1278
1279 $content = $revision->getContent( SlotRecord::MAIN );
1280 $len = $content ? $content->getSize() : 0;
1281 $rt = $content ? $content->getRedirectTarget() : null;
1282 $isNew = $lastRevision === 0;
1283 $isRedirect = $rt !== null;
1284
1285 $conditions = [ 'page_id' => $this->getId() ];
1286
1287 if ( $lastRevision !== null ) {
1288 // An extra check against threads stepping on each other
1289 $conditions['page_latest'] = $lastRevision;
1290 }
1291
1292 $model = $revision->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel();
1293
1294 $row = [ /* SET */
1295 'page_latest' => $revId,
1296 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1297 'page_is_new' => $isNew ? 1 : 0,
1298 'page_is_redirect' => $isRedirect ? 1 : 0,
1299 'page_len' => $len,
1300 'page_content_model' => $model,
1301 ];
1302
1303 $dbw->newUpdateQueryBuilder()
1304 ->update( 'page' )
1305 ->set( $row )
1306 ->where( $conditions )
1307 ->caller( __METHOD__ )->execute();
1308
1309 $result = $dbw->affectedRows() > 0;
1310 if ( $result ) {
1311 $insertedRow = $this->pageData( $dbw, [ 'page_id' => $this->getId() ] );
1312
1313 if ( !$insertedRow ) {
1314 throw new RuntimeException( 'Failed to load freshly inserted row' );
1315 }
1316
1317 $this->mTitle->loadFromRow( $insertedRow );
1318 MediaWikiServices::getInstance()->getRedirectStore()
1319 ->updateRedirectTarget( $this, $rt, $lastRevIsRedirect );
1320 $this->setLastEdit( $revision );
1321 $this->mPageIsRedirectField = (bool)$rt;
1322 $this->mIsNew = $isNew;
1323
1324 // Update the LinkCache.
1325 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1326 $linkCache->addGoodLinkObjFromRow(
1327 $this->mTitle,
1328 $insertedRow
1329 );
1330 }
1331
1332 return $result;
1333 }
1334
1335 /**
1336 * Helper method for checking whether two revisions have differences that go
1337 * beyond the main slot.
1338 *
1339 * MCR migration note: this method should go away!
1340 *
1341 * @deprecated since 1.43; Use only as a stop-gap before refactoring to support MCR.
1342 *
1343 * @param RevisionRecord $a
1344 * @param RevisionRecord $b
1345 * @return bool
1346 */
1347 public static function hasDifferencesOutsideMainSlot( RevisionRecord $a, RevisionRecord $b ) {
1348 $aSlots = $a->getSlots();
1349 $bSlots = $b->getSlots();
1350 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1351
1352 return ( $changedRoles !== [ SlotRecord::MAIN ] && $changedRoles !== [] );
1353 }
1354
1355 /**
1356 * Returns true if this page's content model supports sections.
1357 *
1358 * @return bool
1359 *
1360 * @todo The skin should check this and not offer section functionality if
1361 * sections are not supported.
1362 * @todo The EditPage should check this and not offer section functionality
1363 * if sections are not supported.
1364 */
1365 public function supportsSections() {
1366 return $this->getContentHandler()->supportsSections();
1367 }
1368
1369 /**
1370 * @param string|int|null|false $sectionId Section identifier as a number or string
1371 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1372 * or 'new' for a new section.
1373 * @param Content $sectionContent New content of the section.
1374 * @param string $sectionTitle New section's subject, only if $section is "new".
1375 * @param string $edittime Revision timestamp or null to use the current revision.
1376 *
1377 * @return Content|null New complete article content, or null if error.
1378 *
1379 * @since 1.21
1380 * @deprecated since 1.24, use replaceSectionAtRev instead
1381 */
1382 public function replaceSectionContent(
1383 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1384 ) {
1385 $baseRevId = null;
1386 if ( $edittime && $sectionId !== 'new' ) {
1387 $lb = $this->getDBLoadBalancer();
1388 $rev = $this->getRevisionStore()->getRevisionByTimestamp( $this->mTitle, $edittime );
1389 // Try the primary database if this thread may have just added it.
1390 // The logic to fallback to the primary database if the replica is missing
1391 // the revision could be generalized into RevisionStore, but we don't want
1392 // to encourage loading of revisions by timestamp.
1393 if ( !$rev
1394 && $lb->hasReplicaServers()
1395 && $lb->hasOrMadeRecentPrimaryChanges()
1396 ) {
1397 $rev = $this->getRevisionStore()->getRevisionByTimestamp(
1398 $this->mTitle, $edittime, IDBAccessObject::READ_LATEST );
1399 }
1400 if ( $rev ) {
1401 $baseRevId = $rev->getId();
1402 }
1403 }
1404
1405 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1406 }
1407
1408 /**
1409 * @param string|int|null|false $sectionId Section identifier as a number or string
1410 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1411 * or 'new' for a new section.
1412 * @param Content $sectionContent New content of the section.
1413 * @param string $sectionTitle New section's subject, only if $section is "new".
1414 * @param int|null $baseRevId
1415 *
1416 * @return Content|null New complete article content, or null if error.
1417 *
1418 * @since 1.24
1419 */
1420 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1421 $sectionTitle = '', $baseRevId = null
1422 ) {
1423 if ( strval( $sectionId ) === '' ) {
1424 // Whole-page edit; let the whole text through
1425 $newContent = $sectionContent;
1426 } else {
1427 if ( !$this->supportsSections() ) {
1428 throw new BadMethodCallException( "sections not supported for content model " .
1429 $this->getContentHandler()->getModelID() );
1430 }
1431
1432 // T32711: always use current version when adding a new section
1433 if ( $baseRevId === null || $sectionId === 'new' ) {
1434 $oldContent = $this->getContent();
1435 } else {
1436 $revRecord = $this->getRevisionStore()->getRevisionById( $baseRevId );
1437 if ( !$revRecord ) {
1438 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1439 $this->getId() . "; section: $sectionId)" );
1440 return null;
1441 }
1442
1443 $oldContent = $revRecord->getContent( SlotRecord::MAIN );
1444 }
1445
1446 if ( !$oldContent ) {
1447 wfDebug( __METHOD__ . ": no page text" );
1448 return null;
1449 }
1450
1451 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1452 }
1453
1454 return $newContent;
1455 }
1456
1457 /**
1458 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1459 *
1460 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1461 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1462 *
1463 * @param int $flags
1464 * @return int Updated $flags
1465 */
1466 public function checkFlags( $flags ) {
1467 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1468 if ( $this->exists() ) {
1469 $flags |= EDIT_UPDATE;
1470 } else {
1471 $flags |= EDIT_NEW;
1472 }
1473 }
1474
1475 return $flags;
1476 }
1477
1478 /**
1479 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1480 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1481 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1482 * returned matches that caller's expectations, allowing an existing instance to be re-used
1483 * if the given parameters match that instance's internal state according to
1484 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1485 * match the existing one.
1486 *
1487 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1488 * created, replacing any DerivedPageDataUpdater currently cached.
1489 *
1490 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1491 *
1492 * @since 1.32
1493 *
1494 * @param UserIdentity|null $forUser The user that will be used for, or was used for, PST.
1495 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1496 * to perform updates, if the edit was already saved.
1497 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1498 * if the edit was not yet saved.
1499 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1500 * revision as the edit's parent revision. This ensures that the same
1501 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1502 *
1503 * @return DerivedPageDataUpdater
1504 */
1505 private function getDerivedDataUpdater(
1506 ?UserIdentity $forUser = null,
1507 ?RevisionRecord $forRevision = null,
1508 ?RevisionSlotsUpdate $forUpdate = null,
1509 $forEdit = false
1510 ) {
1511 if ( !$forRevision && !$forUpdate ) {
1512 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1513 // going to use it with.
1514 $this->derivedDataUpdater = null;
1515 }
1516
1517 if ( $this->derivedDataUpdater && !$this->derivedDataUpdater->isContentPrepared() ) {
1518 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1519 // to it did not yet initialize it, because we don't know what data it will be
1520 // initialized with.
1521 $this->derivedDataUpdater = null;
1522 }
1523
1524 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1525 // However, there is no good way to construct a cache key. We'd need to check against all
1526 // cached instances.
1527
1528 if ( $this->derivedDataUpdater
1529 && !$this->derivedDataUpdater->isReusableFor(
1530 $forUser,
1531 $forRevision,
1532 $forUpdate,
1533 $forEdit ? $this->getLatest() : null
1534 )
1535 ) {
1536 $this->derivedDataUpdater = null;
1537 }
1538
1539 if ( !$this->derivedDataUpdater ) {
1540 $this->derivedDataUpdater =
1541 $this->getPageUpdaterFactory()->newDerivedPageDataUpdater( $this );
1542 }
1543
1544 return $this->derivedDataUpdater;
1545 }
1546
1547 /**
1548 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1549 *
1550 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1551 * and to protected such conflict resolution from concurrent edits using a check-and-set
1552 * mechanism.
1553 *
1554 * @since 1.32
1555 *
1556 * @note Once extensions no longer rely on WikiPage to get access to the state of an ongoing
1557 * edit via prepareContentForEdit() and WikiPage::getCurrentUpdate(),
1558 * this method should be deprecated and callers should be migrated to using
1559 * PageUpdaterFactory::newPageUpdater() instead.
1560 *
1561 * @param Authority|UserIdentity $performer
1562 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1563 * that may already have been returned via getDerivedDataUpdater to be re-used.
1564 *
1565 * @return PageUpdater
1566 */
1567 public function newPageUpdater( $performer, ?RevisionSlotsUpdate $forUpdate = null ) {
1568 if ( $performer instanceof Authority ) {
1569 // TODO: Deprecate this. But better get rid of this method entirely.
1570 $performer = $performer->getUser();
1571 }
1572
1573 $pageUpdater = $this->getPageUpdaterFactory()->newPageUpdaterForDerivedPageDataUpdater(
1574 $this,
1575 $performer,
1576 $this->getDerivedDataUpdater( $performer, null, $forUpdate, true )
1577 );
1578
1579 return $pageUpdater;
1580 }
1581
1582 /**
1583 * Change an existing article or create a new article. Updates RC and all necessary caches,
1584 * optionally via the deferred update array.
1585 *
1586 * @deprecated since 1.36, use PageUpdater::saveRevision instead. Note that the new method
1587 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1588 * apply the autopatrol right as appropriate.
1589 *
1590 * @param Content $content New content
1591 * @param Authority $performer doing the edit
1592 * @param string|CommentStoreComment $summary Edit summary
1593 * @param int $flags Bitfield:
1594 * EDIT_NEW
1595 * Article is known or assumed to be non-existent, create a new one
1596 * EDIT_UPDATE
1597 * Article is known or assumed to be pre-existing, update it
1598 * EDIT_MINOR
1599 * Mark this edit minor, if the user is allowed to do so
1600 * EDIT_SUPPRESS_RC
1601 * Do not log the change in recentchanges
1602 * EDIT_FORCE_BOT
1603 * Mark the edit a "bot" edit regardless of user rights
1604 * EDIT_AUTOSUMMARY
1605 * Fill in blank summaries with generated text where possible
1606 * EDIT_INTERNAL
1607 * Signal that the page retrieve/save cycle happened entirely in this request.
1608 *
1609 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1610 * article will be detected. If EDIT_UPDATE is specified and the article
1611 * doesn't exist, the function will return an edit-gone-missing error. If
1612 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1613 * error will be returned. These two conditions are also possible with
1614 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1615 *
1616 * @param int|false $originalRevId: The ID of an original revision that the edit
1617 * restores or repeats. The new revision is expected to have the exact same content as
1618 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1619 * which are created to record things like page moves. Default is false, meaning we are not
1620 * making a rollback edit.
1621 * @param array|null $tags Change tags to apply to this edit
1622 * Callers are responsible for permission checks
1623 * (with ChangeTags::canAddTagsAccompanyingChange)
1624 * @param int $undidRevId Id of revision that was undone or 0
1625 *
1626 * @return PageUpdateStatus Possible errors:
1627 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1628 * set the fatal flag of $status.
1629 * edit-gone-missing: In update mode, but the article didn't exist.
1630 * edit-conflict: In update mode, the article changed unexpectedly.
1631 * edit-no-change: Warning that the text was the same as before.
1632 * edit-already-exists: In creation mode, but the article already exists.
1633 *
1634 * Extensions may define additional errors.
1635 *
1636 * $return->value will contain an associative array with members as follows:
1637 * new: Boolean indicating if the function attempted to create a new article.
1638 * revision-record: The revision record object for the inserted revision, or null.
1639 *
1640 * @since 1.36
1641 */
1642 public function doUserEditContent(
1643 Content $content,
1644 Authority $performer,
1645 $summary,
1646 $flags = 0,
1647 $originalRevId = false,
1648 $tags = [],
1649 $undidRevId = 0
1650 ): PageUpdateStatus {
1651 $useNPPatrol = MediaWikiServices::getInstance()->getMainConfig()->get(
1652 MainConfigNames::UseNPPatrol );
1653 $useRCPatrol = MediaWikiServices::getInstance()->getMainConfig()->get(
1654 MainConfigNames::UseRCPatrol );
1655 if ( !( $summary instanceof CommentStoreComment ) ) {
1656 $summary = CommentStoreComment::newUnsavedComment( trim( $summary ) );
1657 }
1658
1659 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1660 // Checking the minoredit right should be done in the same place the 'bot' right is
1661 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1662 if ( ( $flags & EDIT_MINOR ) && !$performer->isAllowed( 'minoredit' ) ) {
1663 $flags &= ~EDIT_MINOR;
1664 }
1665
1666 $slotsUpdate = new RevisionSlotsUpdate();
1667 $slotsUpdate->modifyContent( SlotRecord::MAIN, $content );
1668
1669 // NOTE: while doUserEditContent() executes, callbacks to getDerivedDataUpdater and
1670 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1671 // used by this PageUpdater. However, there is no guarantee for this.
1672 $updater = $this->newPageUpdater( $performer, $slotsUpdate )
1673 ->setContent( SlotRecord::MAIN, $content )
1674 ->setOriginalRevisionId( $originalRevId );
1675 if ( $undidRevId ) {
1676 $updater->markAsRevert(
1677 EditResult::REVERT_UNDO,
1678 $undidRevId,
1679 $originalRevId ?: null
1680 );
1681 }
1682
1683 $needsPatrol = $useRCPatrol || ( $useNPPatrol && !$this->exists() );
1684
1685 // TODO: this logic should not be in the storage layer, it's here for compatibility
1686 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1687 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1688
1689 if ( $needsPatrol && $performer->authorizeWrite( 'autopatrol', $this->getTitle() ) ) {
1690 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
1691 }
1692
1693 $updater->addTags( $tags );
1694
1695 $revRec = $updater->saveRevision(
1696 $summary,
1697 $flags
1698 );
1699
1700 // $revRec will be null if the edit failed, or if no new revision was created because
1701 // the content did not change.
1702 if ( $revRec ) {
1703 // update cached fields
1704 // TODO: this is currently redundant to what is done in updateRevisionOn.
1705 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1706 $this->setLastEdit( $revRec );
1707 }
1708
1709 return $updater->getStatus();
1710 }
1711
1712 /**
1713 * Get parser options suitable for rendering the primary article wikitext
1714 *
1715 * @see ParserOptions::newCanonical
1716 *
1717 * @param IContextSource|UserIdentity|string $context One of the following:
1718 * - IContextSource: Use the User and the Language of the provided
1719 * context
1720 * - UserIdentity: Use the provided UserIdentity object and $wgLang
1721 * for the language, so use an IContextSource object if possible.
1722 * - 'canonical': Canonical options (anonymous user with default
1723 * preferences and content language).
1724 * @return ParserOptions
1725 */
1726 public function makeParserOptions( $context ) {
1727 return self::makeParserOptionsFromTitleAndModel(
1728 $this->getTitle(), $this->getContentModel(), $context
1729 );
1730 }
1731
1732 /**
1733 * Create canonical parser options for a given title and content model.
1734 * @internal
1735 * @param PageReference $pageRef
1736 * @param string $contentModel
1737 * @param IContextSource|UserIdentity|string $context See ::makeParserOptions
1738 * @return ParserOptions
1739 */
1740 public static function makeParserOptionsFromTitleAndModel(
1741 PageReference $pageRef, string $contentModel, $context
1742 ) {
1743 $options = ParserOptions::newCanonical( $context );
1744
1745 $title = Title::newFromPageReference( $pageRef );
1746 if ( $title->isConversionTable() ) {
1747 // @todo ConversionTable should become a separate content model, so
1748 // we don't need special cases like this one, but see T313455.
1749 $options->disableContentConversion();
1750 }
1751
1752 return $options;
1753 }
1754
1755 /**
1756 * Prepare content which is about to be saved.
1757 *
1758 * Prior to 1.30, this returned a stdClass.
1759 *
1760 * @deprecated since 1.32, use newPageUpdater() or getCurrentUpdate() instead.
1761 * @note Calling without a UserIdentity was separately deprecated from 1.37 to 1.39, since
1762 * 1.39 the UserIdentity has been required.
1763 *
1764 * @param Content $content
1765 * @param RevisionRecord|null $revision
1766 * Used with vary-revision or vary-revision-id.
1767 * @param UserIdentity $user
1768 * @param string|null $serialFormat IGNORED
1769 * @param bool $useStash Use prepared edit stash
1770 *
1771 * @return PreparedEdit
1772 *
1773 * @since 1.21
1774 */
1775 public function prepareContentForEdit(
1776 Content $content,
1777 ?RevisionRecord $revision,
1778 UserIdentity $user,
1779 $serialFormat = null,
1780 $useStash = true
1781 ) {
1782 $slots = RevisionSlotsUpdate::newFromContent( [ SlotRecord::MAIN => $content ] );
1783 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
1784
1785 if ( !$updater->isUpdatePrepared() ) {
1786 $updater->prepareContent( $user, $slots, $useStash );
1787
1788 if ( $revision ) {
1789 $updater->prepareUpdate(
1790 $revision,
1791 [
1792 'causeAction' => 'prepare-edit',
1793 'causeAgent' => $user->getName(),
1794 ]
1795 );
1796 }
1797 }
1798
1799 return $updater->getPreparedEdit();
1800 }
1801
1802 /**
1803 * Do standard deferred updates after page edit.
1804 * Update links tables, site stats, search index and message cache.
1805 * Purges pages that include this page if the text was changed here.
1806 * Every 100th edit, prune the recent changes table.
1807 *
1808 * @deprecated since 1.32 (soft), use DerivedPageDataUpdater::doUpdates instead.
1809 *
1810 * @param RevisionRecord $revisionRecord (Switched from the old Revision class to
1811 * RevisionRecord since 1.35)
1812 * @param UserIdentity $user User object that did the revision
1813 * @param array $options Array of options, following indexes are used:
1814 * - changed: bool, whether the revision changed the content (default true)
1815 * - created: bool, whether the revision created the page (default false)
1816 * - moved: bool, whether the page was moved (default false)
1817 * - restored: bool, whether the page was undeleted (default false)
1818 * - oldrevision: RevisionRecord object for the pre-update revision (default null)
1819 * - oldcountable: bool, null, or string 'no-change' (default null):
1820 * - bool: whether the page was counted as an article before that
1821 * revision, only used in changed is true and created is false
1822 * - null: if created is false, don't update the article count; if created
1823 * is true, do update the article count
1824 * - 'no-change': don't update the article count, ever
1825 * - causeAction: an arbitrary string identifying the reason for the update.
1826 * See DataUpdate::getCauseAction(). (default 'edit-page')
1827 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
1828 * (string, defaults to the passed user)
1829 */
1830 public function doEditUpdates(
1831 RevisionRecord $revisionRecord,
1832 UserIdentity $user,
1833 array $options = []
1834 ) {
1835 $options += [
1836 'causeAction' => 'edit-page',
1837 'causeAgent' => $user->getName(),
1838 ];
1839
1840 $updater = $this->getDerivedDataUpdater( $user, $revisionRecord );
1841
1842 $updater->prepareUpdate( $revisionRecord, $options );
1843
1844 $updater->doUpdates();
1845 }
1846
1847 /**
1848 * Update the parser cache.
1849 *
1850 * @note This does not update links tables. Use doSecondaryDataUpdates() for that.
1851 *
1852 * @param array $options
1853 * - causeAction: an arbitrary string identifying the reason for the update.
1854 * See DataUpdate::getCauseAction(). (default 'edit-page')
1855 * - causeAgent: name of the user who caused the update (string, defaults to the
1856 * user who created the revision)
1857 * @since 1.32
1858 */
1859 public function updateParserCache( array $options = [] ) {
1860 $revision = $this->getRevisionRecord();
1861 if ( !$revision || !$revision->getId() ) {
1862 LoggerFactory::getInstance( 'wikipage' )->info(
1863 __METHOD__ . ' called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
1864 );
1865 return;
1866 }
1867 $userIdentity = $revision->getUser( RevisionRecord::RAW );
1868
1869 $updater = $this->getDerivedDataUpdater( $userIdentity, $revision );
1870 $updater->prepareUpdate( $revision, $options );
1871 $updater->doParserCacheUpdate();
1872 }
1873
1874 /**
1875 * Do secondary data updates (such as updating link tables).
1876 * Secondary data updates are only a small part of the updates needed after saving
1877 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
1878 * secondary data updates). This method is provided for partial purges.
1879 *
1880 * @note This does not update the parser cache. Use updateParserCache() for that.
1881 *
1882 * @param array $options
1883 * - recursive (bool, default true): whether to do a recursive update (update pages that
1884 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
1885 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
1886 * was something that did not really change the page, such as a null edit.
1887 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
1888 * user who created the revision)
1889 * - causeAction: an arbitrary string identifying the reason for the update.
1890 * See DataUpdate::getCauseAction(). (default 'unknown')
1891 * - causeAgent: name of the user who caused the update (string, default 'unknown')
1892 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
1893 * Note that even when this is set to false, some updates might still get deferred (as
1894 * some update might directly add child updates to DeferredUpdates).
1895 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
1896 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
1897 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
1898 * for the time until caches have been changed to store RenderedRevision states instead
1899 * of ParserOutput objects. (default: null) (since 1.33)
1900 * @since 1.32
1901 */
1902 public function doSecondaryDataUpdates( array $options = [] ) {
1903 $options['recursive'] ??= true;
1904 $revision = $this->getRevisionRecord();
1905 if ( !$revision || !$revision->getId() ) {
1906 LoggerFactory::getInstance( 'wikipage' )->info(
1907 __METHOD__ . ' called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
1908 );
1909 return;
1910 }
1911 $userIdentity = $revision->getUser( RevisionRecord::RAW );
1912
1913 $updater = $this->getDerivedDataUpdater( $userIdentity, $revision );
1914 $updater->prepareUpdate( $revision, $options );
1915 $updater->doSecondaryDataUpdates( $options );
1916 }
1917
1918 /**
1919 * Update the article's restriction field, and leave a log entry.
1920 * This works for protection both existing and non-existing pages.
1921 *
1922 * @param array $limit Set of restriction keys
1923 * @param array $expiry Per restriction type expiration
1924 * @param bool &$cascade Set to false if cascading protection isn't allowed.
1925 * @param string $reason
1926 * @param UserIdentity $user The user updating the restrictions
1927 * @param string[] $tags Change tags to add to the pages and protection log entries
1928 * ($user should be able to add the specified tags before this is called)
1929 * @return Status Status object; if action is taken, $status->value is the log_id of the
1930 * protection log entry.
1931 */
1932 public function doUpdateRestrictions( array $limit, array $expiry,
1933 &$cascade, $reason, UserIdentity $user, $tags = []
1934 ) {
1935 $services = MediaWikiServices::getInstance();
1936 $readOnlyMode = $services->getReadOnlyMode();
1937 if ( $readOnlyMode->isReadOnly() ) {
1938 return Status::newFatal( wfMessage( 'readonlytext', $readOnlyMode->getReason() ) );
1939 }
1940
1941 $this->loadPageData( 'fromdbmaster' );
1942 $restrictionStore = $services->getRestrictionStore();
1943 $restrictionStore->loadRestrictions( $this->mTitle, IDBAccessObject::READ_LATEST );
1944 $restrictionTypes = $restrictionStore->listApplicableRestrictionTypes( $this->mTitle );
1945 $id = $this->getId();
1946
1947 if ( !$cascade ) {
1948 $cascade = false;
1949 }
1950
1951 // Take this opportunity to purge out expired restrictions
1952 Title::purgeExpiredRestrictions();
1953
1954 // @todo: Same limitations as described in ProtectionForm.php (line 37);
1955 // we expect a single selection, but the schema allows otherwise.
1956 $isProtected = false;
1957 $protect = false;
1958 $changed = false;
1959
1960 $dbw = $services->getConnectionProvider()->getPrimaryDatabase();
1961
1962 foreach ( $restrictionTypes as $action ) {
1963 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
1964 $expiry[$action] = 'infinity';
1965 }
1966 if ( !isset( $limit[$action] ) ) {
1967 $limit[$action] = '';
1968 } elseif ( $limit[$action] != '' ) {
1969 $protect = true;
1970 }
1971
1972 // Get current restrictions on $action
1973 $current = implode( '', $restrictionStore->getRestrictions( $this->mTitle, $action ) );
1974 if ( $current != '' ) {
1975 $isProtected = true;
1976 }
1977
1978 if ( $limit[$action] != $current ) {
1979 $changed = true;
1980 } elseif ( $limit[$action] != '' ) {
1981 // Only check expiry change if the action is actually being
1982 // protected, since expiry does nothing on an not-protected
1983 // action.
1984 if ( $restrictionStore->getRestrictionExpiry( $this->mTitle, $action ) != $expiry[$action] ) {
1985 $changed = true;
1986 }
1987 }
1988 }
1989
1990 if ( !$changed && $protect && $restrictionStore->areRestrictionsCascading( $this->mTitle ) != $cascade ) {
1991 $changed = true;
1992 }
1993
1994 // If nothing has changed, do nothing
1995 if ( !$changed ) {
1996 return Status::newGood();
1997 }
1998
1999 if ( !$protect ) { // No protection at all means unprotection
2000 $revCommentMsg = 'unprotectedarticle-comment';
2001 $logAction = 'unprotect';
2002 } elseif ( $isProtected ) {
2003 $revCommentMsg = 'modifiedarticleprotection-comment';
2004 $logAction = 'modify';
2005 } else {
2006 $revCommentMsg = 'protectedarticle-comment';
2007 $logAction = 'protect';
2008 }
2009
2010 $logRelationsValues = [];
2011 $logRelationsField = null;
2012 $logParamsDetails = [];
2013
2014 // Null revision (used for change tag insertion)
2015 $nullRevisionRecord = null;
2016
2017 if ( $id ) { // Protection of existing page
2018 $legacyUser = $services->getUserFactory()->newFromUserIdentity( $user );
2019 if ( !$this->getHookRunner()->onArticleProtect( $this, $legacyUser, $limit, $reason ) ) {
2020 return Status::newGood();
2021 }
2022
2023 // Only certain restrictions can cascade...
2024 $editrestriction = isset( $limit['edit'] )
2025 ? [ $limit['edit'] ]
2026 : $restrictionStore->getRestrictions( $this->mTitle, 'edit' );
2027 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2028 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2029 }
2030 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2031 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2032 }
2033
2034 $cascadingRestrictionLevels = $services->getMainConfig()
2035 ->get( MainConfigNames::CascadingRestrictionLevels );
2036
2037 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2038 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2039 }
2040 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2041 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2042 }
2043
2044 // The schema allows multiple restrictions
2045 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2046 $cascade = false;
2047 }
2048
2049 // insert null revision to identify the page protection change as edit summary
2050 $latest = $this->getLatest();
2051 $nullRevisionRecord = $this->insertNullProtectionRevision(
2052 $revCommentMsg,
2053 $limit,
2054 $expiry,
2055 $cascade,
2056 $reason,
2057 $user
2058 );
2059
2060 if ( $nullRevisionRecord === null ) {
2061 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2062 }
2063
2064 $logRelationsField = 'pr_id';
2065
2066 // T214035: Avoid deadlock on MySQL.
2067 // Do a DELETE by primary key (pr_id) for any existing protection rows.
2068 // On MySQL and derivatives, unconditionally deleting by page ID (pr_page) would.
2069 // place a gap lock if there are no matching rows. This can deadlock when another
2070 // thread modifies protection settings for page IDs in the same gap.
2071 $existingProtectionIds = $dbw->newSelectQueryBuilder()
2072 ->select( 'pr_id' )
2073 ->from( 'page_restrictions' )
2074 ->where( [ 'pr_page' => $id, 'pr_type' => array_map( 'strval', array_keys( $limit ) ) ] )
2075 ->caller( __METHOD__ )->fetchFieldValues();
2076
2077 if ( $existingProtectionIds ) {
2078 $dbw->newDeleteQueryBuilder()
2079 ->deleteFrom( 'page_restrictions' )
2080 ->where( [ 'pr_id' => $existingProtectionIds ] )
2081 ->caller( __METHOD__ )->execute();
2082 }
2083
2084 // Update restrictions table
2085 foreach ( $limit as $action => $restrictions ) {
2086 if ( $restrictions != '' ) {
2087 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2088 $dbw->newInsertQueryBuilder()
2089 ->insertInto( 'page_restrictions' )
2090 ->row( [
2091 'pr_page' => $id,
2092 'pr_type' => $action,
2093 'pr_level' => $restrictions,
2094 'pr_cascade' => $cascadeValue,
2095 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2096 ] )
2097 ->caller( __METHOD__ )->execute();
2098 $logRelationsValues[] = $dbw->insertId();
2099 $logParamsDetails[] = [
2100 'type' => $action,
2101 'level' => $restrictions,
2102 'expiry' => $expiry[$action],
2103 'cascade' => (bool)$cascadeValue,
2104 ];
2105 }
2106 }
2107
2108 $this->getHookRunner()->onRevisionFromEditComplete(
2109 $this, $nullRevisionRecord, $latest, $user, $tags );
2110
2111 $this->getHookRunner()->onArticleProtectComplete( $this, $legacyUser, $limit, $reason );
2112 } else { // Protection of non-existing page (also known as "title protection")
2113 // Cascade protection is meaningless in this case
2114 $cascade = false;
2115
2116 if ( $limit['create'] != '' ) {
2117 $commentFields = $services->getCommentStore()->insert( $dbw, 'pt_reason', $reason );
2118 $dbw->newReplaceQueryBuilder()
2119 ->table( 'protected_titles' )
2120 ->uniqueIndexFields( [ 'pt_namespace', 'pt_title' ] )
2121 ->rows( [
2122 'pt_namespace' => $this->mTitle->getNamespace(),
2123 'pt_title' => $this->mTitle->getDBkey(),
2124 'pt_create_perm' => $limit['create'],
2125 'pt_timestamp' => $dbw->timestamp(),
2126 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2127 'pt_user' => $user->getId(),
2128 ] + $commentFields )
2129 ->caller( __METHOD__ )->execute();
2130 $logParamsDetails[] = [
2131 'type' => 'create',
2132 'level' => $limit['create'],
2133 'expiry' => $expiry['create'],
2134 ];
2135 } else {
2136 $dbw->newDeleteQueryBuilder()
2137 ->deleteFrom( 'protected_titles' )
2138 ->where( [
2139 'pt_namespace' => $this->mTitle->getNamespace(),
2140 'pt_title' => $this->mTitle->getDBkey()
2141 ] )
2142 ->caller( __METHOD__ )->execute();
2143 }
2144 }
2145
2146 $services->getRestrictionStore()->flushRestrictions( $this->mTitle );
2147
2148 InfoAction::invalidateCache( $this->mTitle );
2149
2150 if ( $logAction == 'unprotect' ) {
2151 $params = [];
2152 } else {
2153 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2154 $params = [
2155 '4::description' => $protectDescriptionLog, // parameter for IRC
2156 '5:bool:cascade' => $cascade,
2157 'details' => $logParamsDetails, // parameter for localize and api
2158 ];
2159 }
2160
2161 // Update the protection log
2162 $logEntry = new ManualLogEntry( 'protect', $logAction );
2163 $logEntry->setTarget( $this->mTitle );
2164 $logEntry->setComment( $reason );
2165 $logEntry->setPerformer( $user );
2166 $logEntry->setParameters( $params );
2167 if ( $nullRevisionRecord !== null ) {
2168 $logEntry->setAssociatedRevId( $nullRevisionRecord->getId() );
2169 }
2170 $logEntry->addTags( $tags );
2171 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2172 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2173 }
2174 $logId = $logEntry->insert();
2175 $logEntry->publish( $logId );
2176
2177 return Status::newGood( $logId );
2178 }
2179
2180 /**
2181 * Get the state of an ongoing update, shortly before or just after it is saved to the database.
2182 * If there is no ongoing edit tracked by this WikiPage instance, this methods throws a
2183 * PreconditionException.
2184 *
2185 * If possible, state is shared with subsequent calls of getPreparedUpdate(),
2186 * prepareContentForEdit(), and newPageUpdater().
2187 *
2188 * @note This method should generally be avoided, since it forces WikiPage to maintain state
2189 * representing ongoing edits. Code that initiates an edit should use newPageUpdater()
2190 * instead. Hooks that interact with the edit should have a the relevant
2191 * information provided as a PageUpdater, PreparedUpdate, or RenderedRevision.
2192 *
2193 * @throws PreconditionException if there is no ongoing update. This method must only be
2194 * called after newPageUpdater() had already been called, typically while executing
2195 * a handler for a hook that is triggered during a page edit.
2196 * @return PreparedUpdate
2197 *
2198 * @since 1.38
2199 */
2200 public function getCurrentUpdate(): PreparedUpdate {
2201 Assert::precondition(
2202 $this->derivedDataUpdater !== null,
2203 'There is no ongoing update tracked by this instance of WikiPage!'
2204 );
2205
2206 return $this->derivedDataUpdater;
2207 }
2208
2209 /**
2210 * Insert a new null revision for this page.
2211 *
2212 * @since 1.35
2213 *
2214 * @param string $revCommentMsg Comment message key for the revision
2215 * @param array $limit Set of restriction keys
2216 * @param array $expiry Per restriction type expiration
2217 * @param bool $cascade Set to false if cascading protection isn't allowed.
2218 * @param string $reason
2219 * @param UserIdentity $user User to attribute to
2220 * @return RevisionRecord|null Null on error
2221 */
2222 public function insertNullProtectionRevision(
2223 string $revCommentMsg,
2224 array $limit,
2225 array $expiry,
2226 bool $cascade,
2227 string $reason,
2228 UserIdentity $user
2229 ): ?RevisionRecord {
2230 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2231
2232 // Prepare a null revision to be added to the history
2233 $editComment = wfMessage(
2234 $revCommentMsg,
2235 $this->mTitle->getPrefixedText(),
2236 $user->getName()
2237 )->inContentLanguage()->text();
2238 if ( $reason ) {
2239 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2240 }
2241 $protectDescription = $this->protectDescription( $limit, $expiry );
2242 if ( $protectDescription ) {
2243 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2244 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2245 ->inContentLanguage()->text();
2246 }
2247 if ( $cascade ) {
2248 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2249 $editComment .= wfMessage( 'brackets' )->params(
2250 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2251 )->inContentLanguage()->text();
2252 }
2253
2254 $revStore = $this->getRevisionStore();
2255 $comment = CommentStoreComment::newUnsavedComment( $editComment );
2256 $nullRevRecord = $revStore->newNullRevision(
2257 $dbw,
2258 $this->getTitle(),
2259 $comment,
2260 true,
2261 $user
2262 );
2263
2264 if ( $nullRevRecord ) {
2265 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2266
2267 // Update page record and touch page
2268 $oldLatest = $inserted->getParentId();
2269
2270 $this->updateRevisionOn( $dbw, $inserted, $oldLatest );
2271
2272 return $inserted;
2273 } else {
2274 return null;
2275 }
2276 }
2277
2278 /**
2279 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2280 * @return string
2281 */
2282 protected function formatExpiry( $expiry ) {
2283 if ( $expiry != 'infinity' ) {
2284 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2285 return wfMessage(
2286 'protect-expiring',
2287 $contLang->timeanddate( $expiry, false, false ),
2288 $contLang->date( $expiry, false, false ),
2289 $contLang->time( $expiry, false, false )
2290 )->inContentLanguage()->text();
2291 } else {
2292 return wfMessage( 'protect-expiry-indefinite' )
2293 ->inContentLanguage()->text();
2294 }
2295 }
2296
2297 /**
2298 * Builds the description to serve as comment for the edit.
2299 *
2300 * @param array $limit Set of restriction keys
2301 * @param array $expiry Per restriction type expiration
2302 * @return string
2303 */
2304 public function protectDescription( array $limit, array $expiry ) {
2305 $protectDescription = '';
2306
2307 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2308 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2309 # All possible message keys are listed here for easier grepping:
2310 # * restriction-create
2311 # * restriction-edit
2312 # * restriction-move
2313 # * restriction-upload
2314 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2315 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2316 # with '' filtered out. All possible message keys are listed below:
2317 # * protect-level-autoconfirmed
2318 # * protect-level-sysop
2319 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2320 ->inContentLanguage()->text();
2321
2322 $expiryText = $this->formatExpiry( $expiry[$action] );
2323
2324 if ( $protectDescription !== '' ) {
2325 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2326 }
2327 $protectDescription .= wfMessage( 'protect-summary-desc' )
2328 ->params( $actionText, $restrictionsText, $expiryText )
2329 ->inContentLanguage()->text();
2330 }
2331
2332 return $protectDescription;
2333 }
2334
2335 /**
2336 * Builds the description to serve as comment for the log entry.
2337 *
2338 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2339 * protect description text. Keep them in old format to avoid breaking compatibility.
2340 * TODO: Fix protection log to store structured description and format it on-the-fly.
2341 *
2342 * @param array $limit Set of restriction keys
2343 * @param array $expiry Per restriction type expiration
2344 * @return string
2345 */
2346 public function protectDescriptionLog( array $limit, array $expiry ) {
2347 $protectDescriptionLog = '';
2348
2349 $dirMark = MediaWikiServices::getInstance()->getContentLanguage()->getDirMark();
2350 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2351 $expiryText = $this->formatExpiry( $expiry[$action] );
2352 $protectDescriptionLog .=
2353 $dirMark .
2354 "[$action=$restrictions] ($expiryText)";
2355 }
2356
2357 return trim( $protectDescriptionLog );
2358 }
2359
2360 /**
2361 * Determines if deletion of this page would be batched (executed over time by the job queue)
2362 * or not (completed in the same request as the delete call).
2363 *
2364 * It is unlikely but possible that an edit from another request could push the page over the
2365 * batching threshold after this function is called, but before the caller acts upon the
2366 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2367 * is provided as an unreliable but situationally useful help for some common cases.
2368 *
2369 * @deprecated since 1.37 Use DeletePage::isBatchedDelete instead.
2370 *
2371 * @param int $safetyMargin Added to the revision count when checking for batching
2372 * @return bool True if deletion would be batched, false otherwise
2373 */
2374 public function isBatchedDelete( $safetyMargin = 0 ) {
2375 $deleteRevisionsBatchSize = MediaWikiServices::getInstance()
2376 ->getMainConfig()->get( MainConfigNames::DeleteRevisionsBatchSize );
2377
2378 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2379 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2380 $revCount += $safetyMargin;
2381
2382 return $revCount >= $deleteRevisionsBatchSize;
2383 }
2384
2385 /**
2386 * Back-end article deletion
2387 * Deletes the article with database consistency, writes logs, purges caches
2388 *
2389 * @since 1.19
2390 * @since 1.35 Signature changed, user moved to second parameter to prepare for requiring
2391 * a user to be passed
2392 * @since 1.36 User second parameter is required
2393 * @deprecated since 1.37 Use DeletePage instead. Calling ::deleteIfAllowed and letting DeletePage handle
2394 * permission checks is preferred over doing permission checks yourself and then calling ::deleteUnsafe.
2395 * Note that DeletePage returns a good status with false value in case of scheduled deletion, instead of
2396 * a status with a warning. Also, the new method doesn't have an $error parameter, since any error is
2397 * added to the returned Status.
2398 *
2399 * @param string $reason Delete reason for deletion log
2400 * @param UserIdentity $deleter The deleting user
2401 * @param bool $suppress Suppress all revisions and log the deletion in
2402 * the suppression log instead of the deletion log
2403 * @param bool|null $u1 Unused
2404 * @param array|string &$error Array of errors to append to
2405 * @param mixed $u2 Unused
2406 * @param string[]|null $tags Tags to apply to the deletion action
2407 * @param string $logsubtype
2408 * @param bool $immediate false allows deleting over time via the job queue
2409 * @return Status Status object; if successful, $status->value is the log_id of the
2410 * deletion log entry. If the page couldn't be deleted because it wasn't
2411 * found, $status is a non-fatal 'cannotdelete' error
2412 */
2413 public function doDeleteArticleReal(
2414 $reason, UserIdentity $deleter, $suppress = false, $u1 = null, &$error = '', $u2 = null,
2415 $tags = [], $logsubtype = 'delete', $immediate = false
2416 ) {
2417 $services = MediaWikiServices::getInstance();
2418 $deletePage = $services->getDeletePageFactory()->newDeletePage(
2419 $this,
2420 $services->getUserFactory()->newFromUserIdentity( $deleter )
2421 );
2422
2423 $status = $deletePage
2424 ->setSuppress( $suppress )
2425 ->setTags( $tags ?: [] )
2426 ->setLogSubtype( $logsubtype )
2427 ->forceImmediate( $immediate )
2428 ->keepLegacyHookErrorsSeparate()
2429 ->deleteUnsafe( $reason );
2430 $error = $deletePage->getLegacyHookErrors();
2431 if ( $status->isGood() ) {
2432 // BC with old return format
2433 if ( $deletePage->deletionsWereScheduled()[DeletePage::PAGE_BASE] ) {
2434 $status->warning( 'delete-scheduled', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2435 } else {
2436 $status->value = $deletePage->getSuccessfulDeletionsIDs()[DeletePage::PAGE_BASE];
2437 }
2438 }
2439 return $status;
2440 }
2441
2442 /**
2443 * Lock the page row for this title+id and return page_latest (or 0)
2444 *
2445 * @return int Returns 0 if no row was found with this title+id
2446 * @since 1.27
2447 */
2448 public function lockAndGetLatest() {
2449 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2450 return (int)$dbw->newSelectQueryBuilder()
2451 ->select( 'page_latest' )
2452 ->forUpdate()
2453 ->from( 'page' )
2454 ->where( [
2455 'page_id' => $this->getId(),
2456 // Typically page_id is enough, but some code might try to do
2457 // updates assuming the title is the same, so verify that
2458 'page_namespace' => $this->getTitle()->getNamespace(),
2459 'page_title' => $this->getTitle()->getDBkey()
2460 ] )
2461 ->caller( __METHOD__ )->fetchField();
2462 }
2463
2464 /**
2465 * The onArticle*() functions are supposed to be a kind of hooks
2466 * which should be called whenever any of the specified actions
2467 * are done.
2468 *
2469 * This is a good place to put code to clear caches, for instance.
2470 *
2471 * This is called on page move and undelete, as well as edit
2472 *
2473 * @param Title $title
2474 * @param bool $maybeIsRedirect True if the page may have been created as a redirect.
2475 * If false, this is used as a hint to skip some unnecessary updates.
2476 */
2477 public static function onArticleCreate( Title $title, $maybeIsRedirect = true ) {
2478 // TODO: move this into a PageEventEmitter service
2479
2480 // Update existence markers on article/talk tabs...
2481 $other = $title->getOtherPage();
2482
2483 $services = MediaWikiServices::getInstance();
2484 $hcu = $services->getHtmlCacheUpdater();
2485 $hcu->purgeTitleUrls( [ $title, $other ], $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2486
2487 $title->touchLinks();
2488 $title->deleteTitleProtection();
2489
2490 $services->getLinkCache()->invalidateTitle( $title );
2491
2492 DeferredUpdates::addCallableUpdate(
2493 static function () use ( $title, $maybeIsRedirect ) {
2494 self::queueBacklinksJobs( $title, true, $maybeIsRedirect, 'create-page' );
2495 }
2496 );
2497
2498 if ( $title->getNamespace() === NS_CATEGORY ) {
2499 // Load the Category object, which will schedule a job to create
2500 // the category table row if necessary. Checking a replica DB is ok
2501 // here, in the worst case it'll run an unnecessary recount job on
2502 // a category that probably doesn't have many members.
2503 Category::newFromTitle( $title )->getID();
2504 }
2505 }
2506
2507 /**
2508 * Clears caches when article is deleted
2509 *
2510 * @param Title $title
2511 */
2512 public static function onArticleDelete( Title $title ) {
2513 // TODO: move this into a PageEventEmitter service
2514
2515 // Update existence markers on article/talk tabs...
2516 $other = $title->getOtherPage();
2517
2518 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2519 $hcu->purgeTitleUrls( [ $title, $other ], $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2520
2521 $title->touchLinks();
2522
2523 $services = MediaWikiServices::getInstance();
2524 $services->getLinkCache()->invalidateTitle( $title );
2525
2526 InfoAction::invalidateCache( $title );
2527
2528 // Messages
2529 if ( $title->getNamespace() === NS_MEDIAWIKI ) {
2530 $services->getMessageCache()->updateMessageOverride( $title, null );
2531 }
2532
2533 // Invalidate caches of articles which include this page
2534 DeferredUpdates::addCallableUpdate( static function () use ( $title ) {
2535 self::queueBacklinksJobs( $title, true, true, 'delete-page' );
2536 } );
2537
2538 // User talk pages
2539 if ( $title->getNamespace() === NS_USER_TALK ) {
2540 $user = User::newFromName( $title->getText(), false );
2541 if ( $user ) {
2542 MediaWikiServices::getInstance()
2543 ->getTalkPageNotificationManager()
2544 ->removeUserHasNewMessages( $user );
2545 }
2546 }
2547
2548 // Image redirects
2549 $services->getRepoGroup()->getLocalRepo()->invalidateImageRedirect( $title );
2550
2551 // Purge cross-wiki cache entities referencing this page
2552 self::purgeInterwikiCheckKey( $title );
2553 }
2554
2555 /**
2556 * Purge caches on page update etc
2557 *
2558 * @param Title $title
2559 * @param RevisionRecord|null $revRecord revision that was just saved, may be null
2560 * @param string[]|null $slotsChanged The role names of the slots that were changed.
2561 * If not given, all slots are assumed to have changed.
2562 * @param bool $maybeRedirectChanged True if the page's redirect target may have changed in the
2563 * latest revision. If false, this is used as a hint to skip some unnecessary updates.
2564 */
2565 public static function onArticleEdit(
2566 Title $title,
2567 ?RevisionRecord $revRecord = null,
2568 $slotsChanged = null,
2569 $maybeRedirectChanged = true
2570 ) {
2571 // TODO: move this into a PageEventEmitter service
2572
2573 DeferredUpdates::addCallableUpdate(
2574 static function () use ( $title, $slotsChanged, $maybeRedirectChanged ) {
2575 self::queueBacklinksJobs(
2576 $title,
2577 $slotsChanged === null || in_array( SlotRecord::MAIN, $slotsChanged ),
2578 $maybeRedirectChanged,
2579 'edit-page'
2580 );
2581 }
2582 );
2583
2584 $services = MediaWikiServices::getInstance();
2585 $services->getLinkCache()->invalidateTitle( $title );
2586
2587 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2588 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2589
2590 // Purge ?action=info cache
2591 $revid = $revRecord ? $revRecord->getId() : null;
2592 DeferredUpdates::addCallableUpdate( static function () use ( $title, $revid ) {
2593 InfoAction::invalidateCache( $title, $revid );
2594 } );
2595
2596 // Purge cross-wiki cache entities referencing this page
2597 self::purgeInterwikiCheckKey( $title );
2598 }
2599
2600 private static function queueBacklinksJobs(
2601 Title $title, $mainSlotChanged, $maybeRedirectChanged, $causeAction
2602 ) {
2603 $services = MediaWikiServices::getInstance();
2604 $backlinkCache = $services->getBacklinkCacheFactory()->getBacklinkCache( $title );
2605
2606 $jobs = [];
2607 if ( $mainSlotChanged
2608 && $backlinkCache->hasLinks( 'templatelinks' )
2609 ) {
2610 // Invalidate caches of articles which include this page.
2611 // Only for the main slot, because only the main slot is transcluded.
2612 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
2613 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2614 $title,
2615 'templatelinks',
2616 [ 'causeAction' => $causeAction ]
2617 );
2618 }
2619 // Images
2620 if ( $maybeRedirectChanged && $title->getNamespace() === NS_FILE
2621 && $backlinkCache->hasLinks( 'imagelinks' )
2622 ) {
2623 // Process imagelinks in case the redirect target has changed
2624 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2625 $title,
2626 'imagelinks',
2627 [ 'causeAction' => $causeAction ]
2628 );
2629 }
2630 // Invalidate the caches of all pages which redirect here
2631 if ( $backlinkCache->hasLinks( 'redirect' ) ) {
2632 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
2633 $title,
2634 'redirect',
2635 [ 'causeAction' => $causeAction ]
2636 );
2637 }
2638 if ( $jobs ) {
2639 $services->getJobQueueGroup()->push( $jobs );
2640 }
2641 }
2642
2643 /**
2644 * Purge the check key for cross-wiki cache entries referencing this page
2645 *
2646 * @param Title $title
2647 */
2648 private static function purgeInterwikiCheckKey( Title $title ) {
2649 $enableScaryTranscluding = MediaWikiServices::getInstance()->getMainConfig()->get(
2650 MainConfigNames::EnableScaryTranscluding );
2651
2652 if ( !$enableScaryTranscluding ) {
2653 return; // @todo: perhaps this wiki is only used as a *source* for content?
2654 }
2655
2656 DeferredUpdates::addCallableUpdate( static function () use ( $title ) {
2657 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2658 $cache->resetCheckKey(
2659 // Do not include the namespace since there can be multiple aliases to it
2660 // due to different namespace text definitions on different wikis. This only
2661 // means that some cache invalidations happen that are not strictly needed.
2662 $cache->makeGlobalKey(
2663 'interwiki-page',
2664 WikiMap::getCurrentWikiDbDomain()->getId(),
2665 $title->getDBkey()
2666 )
2667 );
2668 } );
2669 }
2670
2671 /**
2672 * Returns a list of categories this page is a member of.
2673 * Results will include hidden categories
2674 *
2675 * @return TitleArrayFromResult
2676 */
2677 public function getCategories() {
2678 $services = MediaWikiServices::getInstance();
2679 $id = $this->getId();
2680 if ( $id == 0 ) {
2681 return $services->getTitleFactory()->newTitleArrayFromResult( new FakeResultWrapper( [] ) );
2682 }
2683
2684 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
2685 $res = $dbr->newSelectQueryBuilder()
2686 ->select( [ 'page_title' => 'cl_to', 'page_namespace' => (string)NS_CATEGORY ] )
2687 ->from( 'categorylinks' )
2688 ->where( [ 'cl_from' => $id ] )
2689 ->caller( __METHOD__ )->fetchResultSet();
2690
2691 return $services->getTitleFactory()->newTitleArrayFromResult( $res );
2692 }
2693
2694 /**
2695 * Returns a list of hidden categories this page is a member of.
2696 * Uses the page_props and categorylinks tables.
2697 *
2698 * @return Title[]
2699 */
2700 public function getHiddenCategories() {
2701 $result = [];
2702 $id = $this->getId();
2703
2704 if ( $id == 0 ) {
2705 return [];
2706 }
2707
2708 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2709 $res = $dbr->newSelectQueryBuilder()
2710 ->select( [ 'cl_to' ] )
2711 ->from( 'categorylinks' )
2712 ->join( 'page', null, 'page_title=cl_to' )
2713 ->join( 'page_props', null, 'pp_page=page_id' )
2714 ->where( [ 'cl_from' => $id, 'pp_propname' => 'hiddencat', 'page_namespace' => NS_CATEGORY ] )
2715 ->caller( __METHOD__ )->fetchResultSet();
2716
2717 foreach ( $res as $row ) {
2718 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2719 }
2720
2721 return $result;
2722 }
2723
2724 /**
2725 * Auto-generates a deletion reason
2726 *
2727 * @param bool &$hasHistory Whether the page has a history
2728 * @return string|false String containing deletion reason or empty string, or boolean false
2729 * if no revision occurred
2730 */
2731 public function getAutoDeleteReason( &$hasHistory = false ) {
2732 if ( func_num_args() === 1 ) {
2733 wfDeprecated( __METHOD__ . ': $hasHistory parameter', '1.38' );
2734 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2735 }
2736 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle() );
2737 }
2738
2739 /**
2740 * Update all the appropriate counts in the category table, given that
2741 * we've added the categories $added and deleted the categories $deleted.
2742 *
2743 * This should only be called from deferred updates or jobs to avoid contention.
2744 *
2745 * @param string[] $added The names of categories that were added
2746 * @param string[] $deleted The names of categories that were deleted
2747 * @param int $id Page ID (this should be the original deleted page ID)
2748 */
2749 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
2750 $id = $id ?: $this->getId();
2751 // Guard against data corruption T301433
2752 $added = array_map( 'strval', $added );
2753 $deleted = array_map( 'strval', $deleted );
2754 $type = MediaWikiServices::getInstance()->getNamespaceInfo()->
2755 getCategoryLinkType( $this->getTitle()->getNamespace() );
2756
2757 $addFields = [ 'cat_pages' => new RawSQLValue( 'cat_pages + 1' ) ];
2758 $removeFields = [ 'cat_pages' => new RawSQLValue( 'cat_pages - 1' ) ];
2759 if ( $type !== 'page' ) {
2760 $addFields["cat_{$type}s"] = new RawSQLValue( "cat_{$type}s + 1" );
2761 $removeFields["cat_{$type}s"] = new RawSQLValue( "cat_{$type}s - 1" );
2762 }
2763
2764 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2765 $res = $dbw->newSelectQueryBuilder()
2766 ->select( [ 'cat_id', 'cat_title' ] )
2767 ->from( 'category' )
2768 ->where( [ 'cat_title' => array_merge( $added, $deleted ) ] )
2769 ->caller( __METHOD__ )
2770 ->fetchResultSet();
2771 $existingCategories = [];
2772 foreach ( $res as $row ) {
2773 $existingCategories[$row->cat_id] = $row->cat_title;
2774 }
2775 $existingAdded = array_intersect( $existingCategories, $added );
2776 $existingDeleted = array_intersect( $existingCategories, $deleted );
2777 $missingAdded = array_diff( $added, $existingAdded );
2778
2779 // For category rows that already exist, do a plain
2780 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
2781 // to avoid creating gaps in the cat_id sequence.
2782 if ( $existingAdded ) {
2783 $dbw->newUpdateQueryBuilder()
2784 ->update( 'category' )
2785 ->set( $addFields )
2786 ->where( [ 'cat_id' => array_keys( $existingAdded ) ] )
2787 ->caller( __METHOD__ )->execute();
2788 }
2789
2790 if ( $missingAdded ) {
2791 $queryBuilder = $dbw->newInsertQueryBuilder()
2792 ->insertInto( 'category' )
2793 ->onDuplicateKeyUpdate()
2794 ->uniqueIndexFields( [ 'cat_title' ] )
2795 ->set( $addFields );
2796 foreach ( $missingAdded as $cat ) {
2797 $queryBuilder->row( [
2798 'cat_title' => $cat,
2799 'cat_pages' => 1,
2800 'cat_subcats' => ( $type === 'subcat' ) ? 1 : 0,
2801 'cat_files' => ( $type === 'file' ) ? 1 : 0,
2802 ] );
2803 }
2804 $queryBuilder->caller( __METHOD__ )->execute();
2805 }
2806
2807 if ( $existingDeleted ) {
2808 $dbw->newUpdateQueryBuilder()
2809 ->update( 'category' )
2810 ->set( $removeFields )
2811 ->where( [ 'cat_id' => array_keys( $existingDeleted ) ] )
2812 ->caller( __METHOD__ )->execute();
2813 }
2814
2815 foreach ( $added as $catName ) {
2816 $cat = Category::newFromName( $catName );
2817 $this->getHookRunner()->onCategoryAfterPageAdded( $cat, $this );
2818 }
2819
2820 foreach ( $deleted as $catName ) {
2821 $cat = Category::newFromName( $catName );
2822 $this->getHookRunner()->onCategoryAfterPageRemoved( $cat, $this, $id );
2823 // Refresh counts on categories that should be empty now (after commit, T166757)
2824 DeferredUpdates::addCallableUpdate( static function () use ( $cat ) {
2825 $cat->refreshCountsIfEmpty();
2826 } );
2827 }
2828 }
2829
2830 /**
2831 * Opportunistically enqueue link update jobs after a fresh parser output was generated.
2832 *
2833 * This method should only be called by PoolWorkArticleViewCurrent, after a page view
2834 * experienced a miss from the ParserCache, and a new ParserOutput was generated.
2835 * Specifically, for load reasons, this method must not get called during page views that
2836 * use a cached ParserOutput.
2837 *
2838 * @since 1.25
2839 * @internal For use by PoolWorkArticleViewCurrent
2840 * @param ParserOutput $parserOutput Current version page output
2841 */
2842 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
2843 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2844 return;
2845 }
2846
2847 if ( !$this->getHookRunner()->onOpportunisticLinksUpdate( $this,
2848 $this->mTitle, $parserOutput )
2849 ) {
2850 return;
2851 }
2852
2853 $config = MediaWikiServices::getInstance()->getMainConfig();
2854
2855 $params = [
2856 'isOpportunistic' => true,
2857 'rootJobTimestamp' => $parserOutput->getCacheTime()
2858 ];
2859
2860 if ( MediaWikiServices::getInstance()->getRestrictionStore()->areRestrictionsCascading( $this->mTitle ) ) {
2861 // In general, MediaWiki does not re-run LinkUpdate (e.g. for search index, category
2862 // listings, and backlinks for Whatlinkshere), unless either the page was directly
2863 // edited, or was re-generate following a template edit propagating to an affected
2864 // page. As such, during page views when there is no valid ParserCache entry,
2865 // we re-parse and save, but leave indexes as-is.
2866 //
2867 // We make an exception for pages that have cascading protection (perhaps for a wiki's
2868 // "Main Page"). When such page is re-parsed on-demand after a parser cache miss, we
2869 // queue a high-priority LinksUpdate job, to ensure that we really protect all
2870 // content that is currently transcluded onto the page. This is important, because
2871 // wikitext supports conditional statements based on the current time, which enables
2872 // transcluding of a different subpage based on which day it is, and then show that
2873 // information on the Main Page, without the Main Page itself being edited.
2874 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush(
2875 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
2876 );
2877 } elseif ( !$config->get( MainConfigNames::MiserMode ) &&
2878 $parserOutput->hasReducedExpiry()
2879 ) {
2880 // Assume the output contains "dynamic" time/random based magic words.
2881 // Only update pages that expired due to dynamic content and NOT due to edits
2882 // to referenced templates/files. When the cache expires due to dynamic content,
2883 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
2884 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
2885 // template/file edit already triggered recursive RefreshLinksJob jobs.
2886 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
2887 // If a page is uncacheable, do not keep spamming a job for it.
2888 // Although it would be de-duplicated, it would still waste I/O.
2889 $services = MediaWikiServices::getInstance()->getObjectCacheFactory();
2890 $cache = $services->getLocalClusterInstance();
2891 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
2892 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
2893 if ( $cache->add( $key, time(), $ttl ) ) {
2894 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush(
2895 RefreshLinksJob::newDynamic( $this->mTitle, $params )
2896 );
2897 }
2898 }
2899 }
2900 }
2901
2902 /**
2903 * Whether this content displayed on this page
2904 * comes from the local database
2905 *
2906 * @since 1.28
2907 * @return bool
2908 */
2909 public function isLocal() {
2910 return true;
2911 }
2912
2913 /**
2914 * The display name for the site this content
2915 * come from. If a subclass overrides isLocal(),
2916 * this could return something other than the
2917 * current site name
2918 *
2919 * @since 1.28
2920 * @return string
2921 */
2922 public function getWikiDisplayName() {
2923 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get(
2924 MainConfigNames::Sitename );
2925 return $sitename;
2926 }
2927
2928 /**
2929 * Get the source URL for the content on this page,
2930 * typically the canonical URL, but may be a remote
2931 * link if the content comes from another site
2932 *
2933 * @since 1.28
2934 * @return string
2935 */
2936 public function getSourceURL() {
2937 return $this->getTitle()->getCanonicalURL();
2938 }
2939
2940 /**
2941 * Ensure consistency when unserializing.
2942 * @note WikiPage objects should never be serialized in the first place.
2943 * But some extensions like AbuseFilter did (see T213006),
2944 * and we need to be able to read old data (see T187153).
2945 */
2946 public function __wakeup() {
2947 // Make sure we re-fetch the latest state from the database.
2948 // In particular, the latest revision may have changed.
2949 // As a side-effect, this makes sure mLastRevision doesn't
2950 // end up being an instance of the old Revision class (see T259181),
2951 // especially since that class was removed entirely in 1.37.
2952 $this->clear();
2953 }
2954
2955 /**
2956 * @inheritDoc
2957 * @since 1.36
2958 */
2959 public function getNamespace(): int {
2960 return $this->getTitle()->getNamespace();
2961 }
2962
2963 /**
2964 * @inheritDoc
2965 * @since 1.36
2966 */
2967 public function getDBkey(): string {
2968 return $this->getTitle()->getDBkey();
2969 }
2970
2971 /**
2972 * @return false self::LOCAL
2973 * @since 1.36
2974 */
2975 public function getWikiId() {
2976 return $this->getTitle()->getWikiId();
2977 }
2978
2979 /**
2980 * @return true
2981 * @since 1.36
2982 */
2983 public function canExist(): bool {
2984 return true;
2985 }
2986
2987 /**
2988 * @inheritDoc
2989 * @since 1.36
2990 */
2991 public function __toString(): string {
2992 return $this->mTitle->__toString();
2993 }
2994
2995 /**
2996 * @inheritDoc
2997 * @since 1.36
2998 */
2999 public function isSamePageAs( PageReference $other ): bool {
3000 // NOTE: keep in sync with PageReferenceValue::isSamePageAs()!
3001 return $this->getWikiId() === $other->getWikiId()
3002 && $this->getNamespace() === $other->getNamespace()
3003 && $this->getDBkey() === $other->getDBkey();
3004 }
3005
3006 /**
3007 * Returns the page represented by this WikiPage as a PageStoreRecord.
3008 * The PageRecord returned by this method is guaranteed to be immutable.
3009 *
3010 * It is preferred to use this method rather than using the WikiPage as a PageIdentity directly.
3011 * @since 1.36
3012 *
3013 * @throws PreconditionException if the page does not exist.
3014 *
3015 * @return ExistingPageRecord
3016 */
3017 public function toPageRecord(): ExistingPageRecord {
3018 // TODO: replace individual member fields with a PageRecord instance that is always present
3019
3020 if ( !$this->mDataLoaded ) {
3021 $this->loadPageData();
3022 }
3023
3024 Assert::precondition(
3025 $this->exists(),
3026 'This WikiPage instance does not represent an existing page: ' . $this->mTitle
3027 );
3028
3029 return new PageStoreRecord(
3030 (object)[
3031 'page_id' => $this->getId(),
3032 'page_namespace' => $this->mTitle->getNamespace(),
3033 'page_title' => $this->mTitle->getDBkey(),
3034 'page_latest' => $this->mLatest,
3035 'page_is_new' => $this->mIsNew ? 1 : 0,
3036 'page_is_redirect' => $this->mPageIsRedirectField ? 1 : 0,
3037 'page_touched' => $this->getTouched(),
3038 'page_lang' => $this->getLanguage()
3039 ],
3040 PageIdentity::LOCAL
3041 );
3042 }
3043
3044 }