Debian Codegraph @

includes/Storage/DerivedPageDataUpdater.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 namespace MediaWiki\Storage;
22
23 use CategoryMembershipChangeJob;
24 use InvalidArgumentException;
25 use JobQueueGroup;
26 use LogicException;
27 use MediaWiki\Config\ServiceOptions;
28 use MediaWiki\Content\Content;
29 use MediaWiki\Content\ContentHandler;
30 use MediaWiki\Content\IContentHandlerFactory;
31 use MediaWiki\Content\Transform\ContentTransformer;
32 use MediaWiki\Deferred\DeferrableUpdate;
33 use MediaWiki\Deferred\DeferredUpdates;
34 use MediaWiki\Deferred\LinksUpdate\LinksUpdate;
35 use MediaWiki\Deferred\RefreshSecondaryDataUpdate;
36 use MediaWiki\Deferred\SearchUpdate;
37 use MediaWiki\Deferred\SiteStatsUpdate;
38 use MediaWiki\Edit\PreparedEdit;
39 use MediaWiki\HookContainer\HookContainer;
40 use MediaWiki\HookContainer\HookRunner;
41 use MediaWiki\Language\Language;
42 use MediaWiki\MainConfigNames;
43 use MediaWiki\Page\PageIdentity;
44 use MediaWiki\Page\ParserOutputAccess;
45 use MediaWiki\Page\WikiPageFactory;
46 use MediaWiki\Parser\ParserCache;
47 use MediaWiki\Parser\ParserOptions;
48 use MediaWiki\Parser\ParserOutput;
49 use MediaWiki\Permissions\PermissionManager;
50 use MediaWiki\ResourceLoader as RL;
51 use MediaWiki\Revision\MutableRevisionRecord;
52 use MediaWiki\Revision\RenderedRevision;
53 use MediaWiki\Revision\RevisionRecord;
54 use MediaWiki\Revision\RevisionRenderer;
55 use MediaWiki\Revision\RevisionSlots;
56 use MediaWiki\Revision\RevisionStore;
57 use MediaWiki\Revision\SlotRecord;
58 use MediaWiki\Revision\SlotRoleRegistry;
59 use MediaWiki\Title\Title;
60 use MediaWiki\User\TalkPageNotificationManager;
61 use MediaWiki\User\User;
62 use MediaWiki\User\UserIdentity;
63 use MediaWiki\User\UserNameUtils;
64 use MediaWiki\Utils\MWTimestamp;
65 use MessageCache;
66 use MWUnknownContentModelException;
67 use ParsoidCachePrewarmJob;
68 use Psr\Log\LoggerAwareInterface;
69 use Psr\Log\LoggerInterface;
70 use Psr\Log\NullLogger;
71 use RevertedTagUpdateJob;
72 use Wikimedia\Assert\Assert;
73 use Wikimedia\ObjectCache\WANObjectCache;
74 use Wikimedia\Rdbms\IDBAccessObject;
75 use Wikimedia\Rdbms\ILBFactory;
76 use WikiPage;
77
78 /**
79 * A handle for managing updates for derived page data on edit, import, purge, etc.
80 *
81 * @note Avoid direct usage of DerivedPageDataUpdater.
82 *
83 * @todo Define interfaces for the different use cases of DerivedPageDataUpdater, particularly
84 * providing access to post-PST content and ParserOutput to callbacks during revision creation,
85 * which currently use WikiPage::prepareContentForEdit, and allowing updates to be triggered on
86 * purge, import, and undeletion, which currently use WikiPage::doEditUpdates() and
87 * Content::getSecondaryDataUpdates().
88 *
89 * DerivedPageDataUpdater instances are designed to be cached inside a WikiPage instance,
90 * and re-used by callback code over the course of an update operation. It's a stepping stone
91 * on the way to a more complete refactoring of WikiPage.
92 *
93 * When using a DerivedPageDataUpdater, the following life cycle must be observed:
94 * grabCurrentRevision (optional), prepareContent (optional), prepareUpdate (required
95 * for doUpdates). getCanonicalParserOutput, getSlots, and getSecondaryDataUpdates
96 * require prepareContent or prepareUpdate to have been called first, to initialize the
97 * DerivedPageDataUpdater.
98 *
99 * MCR migration note: this replaces the relevant methods in WikiPage, and covers the use cases
100 * of PreparedEdit.
101 *
102 * @see docs/pageupdater.md for more information.
103 *
104 * @internal
105 * @since 1.32
106 * @ingroup Page
107 */
108 class DerivedPageDataUpdater implements LoggerAwareInterface, PreparedUpdate {
109
110 /**
111 * @var UserIdentity|null
112 */
113 private $user = null;
114
115 /**
116 * @var WikiPage
117 */
118 private $wikiPage;
119
120 /**
121 * @var ParserCache
122 */
123 private $parserCache;
124
125 /**
126 * @var RevisionStore
127 */
128 private $revisionStore;
129
130 /**
131 * @var Language
132 */
133 private $contLang;
134
135 /**
136 * @var JobQueueGroup
137 */
138 private $jobQueueGroup;
139
140 /**
141 * @var MessageCache
142 */
143 private $messageCache;
144
145 /**
146 * @var ILBFactory
147 */
148 private $loadbalancerFactory;
149
150 /**
151 * @var HookRunner
152 */
153 private $hookRunner;
154
155 /**
156 * @var LoggerInterface
157 */
158 private $logger;
159
160 /**
161 * @var string see $wgArticleCountMethod
162 */
163 private $articleCountMethod;
164
165 /**
166 * @var bool see $wgRCWatchCategoryMembership
167 */
168 private $rcWatchCategoryMembership = false;
169
170 /**
171 * Stores (most of) the $options parameter of prepareUpdate().
172 * @see prepareUpdate()
173 *
174 * @var array
175 * @phpcs:ignore Generic.Files.LineLength
176 * @phan-var array{changed:bool,created:bool,moved:bool,restored:bool,oldrevision:null|RevisionRecord,triggeringUser:null|UserIdentity,oldredirect:bool|null|string,oldcountable:bool|null|string,causeAction:null|string,causeAgent:null|string,editResult:null|EditResult,approved:bool}
177 */
178 private $options = [
179 'changed' => true,
180 // newrev is true if prepareUpdate is handling the creation of a new revision,
181 // as opposed to a null edit or a forced update.
182 'newrev' => false,
183 'created' => false,
184 'moved' => false,
185 'oldtitle' => null,
186 'restored' => false,
187 'oldrevision' => null,
188 'oldcountable' => null,
189 'oldredirect' => null,
190 'triggeringUser' => null,
191 // causeAction/causeAgent default to 'unknown' but that's handled where it's read,
192 // to make the life of prepareUpdate() callers easier.
193 'causeAction' => null,
194 'causeAgent' => null,
195 'editResult' => null,
196 'approved' => false
197 ];
198
199 /**
200 * The state of the relevant row in page table before the edit.
201 * This is determined by the first call to grabCurrentRevision, prepareContent,
202 * or prepareUpdate (so it is only accessible in 'knows-current' or a later stage).
203 * If pageState was not initialized when prepareUpdate() is called, prepareUpdate() will
204 * attempt to emulate the state of the page table before the edit.
205 *
206 * Contains the following fields:
207 * - oldRevision (RevisionRecord|null): the revision that was current before the change
208 * associated with this update. Might not be set, use getParentRevision().
209 * - oldId (int|null): the id of the above revision. 0 if there is no such revision (the change
210 * was about creating a new page); null if not known (that should not happen).
211 * - oldIsRedirect (bool|null): whether the page was a redirect before the change. Lazy-loaded,
212 * can be null; use wasRedirect() instead of direct access.
213 * - oldCountable (bool|null): whether the page was countable before the change (or null
214 * if we don't have that information)
215 *
216 * @var array
217 */
218 private $pageState = null;
219
220 /**
221 * @var RevisionSlotsUpdate|null
222 */
223 private $slotsUpdate = null;
224
225 /**
226 * @var RevisionRecord|null
227 */
228 private $parentRevision = null;
229
230 /**
231 * @var RevisionRecord|null
232 */
233 private $revision = null;
234
235 /**
236 * @var RenderedRevision
237 */
238 private $renderedRevision = null;
239
240 /**
241 * @var RevisionRenderer
242 */
243 private $revisionRenderer;
244
245 /** @var SlotRoleRegistry */
246 private $slotRoleRegistry;
247
248 /**
249 * @var bool Whether null-edits create a revision.
250 */
251 private $forceEmptyRevision = false;
252
253 /**
254 * A stage identifier for managing the life cycle of this instance.
255 * Possible stages are 'new', 'knows-current', 'has-content', 'has-revision', and 'done'.
256 *
257 * @see docs/pageupdater.md for documentation of the life cycle.
258 *
259 * @var string
260 */
261 private $stage = 'new';
262
263 /**
264 * Transition table for managing the life cycle of DerivedPageDateUpdater instances.
265 *
266 * XXX: Overkill. This is a linear order, we could just count. Names are nice though,
267 * and constants are also overkill...
268 *
269 * @see docs/pageupdater.md for documentation of the life cycle.
270 */
271 private const TRANSITIONS = [
272 'new' => [
273 'new' => true,
274 'knows-current' => true,
275 'has-content' => true,
276 'has-revision' => true,
277 ],
278 'knows-current' => [
279 'knows-current' => true,
280 'has-content' => true,
281 'has-revision' => true,
282 ],
283 'has-content' => [
284 'has-content' => true,
285 'has-revision' => true,
286 ],
287 'has-revision' => [
288 'has-revision' => true,
289 'done' => true,
290 ],
291 ];
292
293 /** @var IContentHandlerFactory */
294 private $contentHandlerFactory;
295
296 /** @var EditResultCache */
297 private $editResultCache;
298
299 /** @var UserNameUtils */
300 private $userNameUtils;
301
302 /** @var ContentTransformer */
303 private $contentTransformer;
304
305 /** @var PageEditStash */
306 private $pageEditStash;
307
308 /** @var TalkPageNotificationManager */
309 private $talkPageNotificationManager;
310
311 /** @var WANObjectCache */
312 private $mainWANObjectCache;
313
314 /** @var PermissionManager */
315 private $permissionManager;
316
317 /** @var bool */
318 private $warmParsoidParserCache;
319
320 /**
321 * @param ServiceOptions $options
322 * @param PageIdentity $page
323 * @param RevisionStore $revisionStore
324 * @param RevisionRenderer $revisionRenderer
325 * @param SlotRoleRegistry $slotRoleRegistry
326 * @param ParserCache $parserCache
327 * @param JobQueueGroup $jobQueueGroup
328 * @param MessageCache $messageCache
329 * @param Language $contLang
330 * @param ILBFactory $loadbalancerFactory
331 * @param IContentHandlerFactory $contentHandlerFactory
332 * @param HookContainer $hookContainer
333 * @param EditResultCache $editResultCache
334 * @param UserNameUtils $userNameUtils
335 * @param ContentTransformer $contentTransformer
336 * @param PageEditStash $pageEditStash
337 * @param TalkPageNotificationManager $talkPageNotificationManager
338 * @param WANObjectCache $mainWANObjectCache
339 * @param PermissionManager $permissionManager
340 * @param WikiPageFactory $wikiPageFactory
341 */
342 public function __construct(
343 ServiceOptions $options,
344 PageIdentity $page,
345 RevisionStore $revisionStore,
346 RevisionRenderer $revisionRenderer,
347 SlotRoleRegistry $slotRoleRegistry,
348 ParserCache $parserCache,
349 JobQueueGroup $jobQueueGroup,
350 MessageCache $messageCache,
351 Language $contLang,
352 ILBFactory $loadbalancerFactory,
353 IContentHandlerFactory $contentHandlerFactory,
354 HookContainer $hookContainer,
355 EditResultCache $editResultCache,
356 UserNameUtils $userNameUtils,
357 ContentTransformer $contentTransformer,
358 PageEditStash $pageEditStash,
359 TalkPageNotificationManager $talkPageNotificationManager,
360 WANObjectCache $mainWANObjectCache,
361 PermissionManager $permissionManager,
362 WikiPageFactory $wikiPageFactory
363 ) {
364 // TODO: Remove this cast eventually
365 $this->wikiPage = $wikiPageFactory->newFromTitle( $page );
366
367 $this->parserCache = $parserCache;
368 $this->revisionStore = $revisionStore;
369 $this->revisionRenderer = $revisionRenderer;
370 $this->slotRoleRegistry = $slotRoleRegistry;
371 $this->jobQueueGroup = $jobQueueGroup;
372 $this->messageCache = $messageCache;
373 $this->contLang = $contLang;
374 // XXX only needed for waiting for replicas to catch up; there should be a narrower
375 // interface for that.
376 $this->loadbalancerFactory = $loadbalancerFactory;
377 $this->contentHandlerFactory = $contentHandlerFactory;
378 $this->hookRunner = new HookRunner( $hookContainer );
379 $this->editResultCache = $editResultCache;
380 $this->userNameUtils = $userNameUtils;
381 $this->contentTransformer = $contentTransformer;
382 $this->pageEditStash = $pageEditStash;
383 $this->talkPageNotificationManager = $talkPageNotificationManager;
384 $this->mainWANObjectCache = $mainWANObjectCache;
385 $this->permissionManager = $permissionManager;
386
387 $this->logger = new NullLogger();
388 $this->warmParsoidParserCache = $options
389 ->get( MainConfigNames::ParsoidCacheConfig )['WarmParsoidParserCache'];
390 }
391
392 public function setLogger( LoggerInterface $logger ) {
393 $this->logger = $logger;
394 }
395
396 /**
397 * Set the cause action and cause agent, for logging and debugging.
398 * If $causeAction or $causeAgent is null, any previously set value is preserved.
399 *
400 * @param ?string $causeAction
401 * @param ?string $causeAgent
402 *
403 * @return void
404 */
405 public function setCause( ?string $causeAction, ?string $causeAgent ) {
406 if ( $causeAction ) {
407 $this->options['causeAction'] = $causeAction;
408 }
409
410 if ( $causeAgent ) {
411 $this->options['causeAgent'] = $causeAgent;
412 }
413 }
414
415 /**
416 * @return string[] [ $causeAction, $causeAgent ]
417 */
418 private function getCause(): array {
419 return [
420 $this->options['causeAction'] ?? 'unknown',
421 $this->options['causeAgent'] ?? 'unknown',
422 ];
423 }
424
425 /**
426 * Transition function for managing the life cycle of this instances.
427 *
428 * @see docs/pageupdater.md for documentation of the life cycle.
429 *
430 * @param string $newStage
431 * @return string the previous stage
432 */
433 private function doTransition( $newStage ) {
434 $this->assertTransition( $newStage );
435
436 $oldStage = $this->stage;
437 $this->stage = $newStage;
438
439 return $oldStage;
440 }
441
442 /**
443 * Asserts that a transition to the given stage is possible, without performing it.
444 *
445 * @see docs/pageupdater.md for documentation of the life cycle.
446 *
447 * @param string $newStage
448 */
449 private function assertTransition( $newStage ) {
450 if ( empty( self::TRANSITIONS[$this->stage][$newStage] ) ) {
451 throw new LogicException( "Cannot transition from {$this->stage} to $newStage" );
452 }
453 }
454
455 /**
456 * Checks whether this DerivedPageDataUpdater can be re-used for running updates targeting
457 * the given revision.
458 *
459 * @param UserIdentity|null $user The user creating the revision in question
460 * @param RevisionRecord|null $revision New revision (after save, if already saved)
461 * @param RevisionSlotsUpdate|null $slotsUpdate New content (before PST)
462 * @param null|int $parentId Parent revision of the edit (use 0 for page creation)
463 *
464 * @return bool
465 */
466 public function isReusableFor(
467 ?UserIdentity $user = null,
468 ?RevisionRecord $revision = null,
469 ?RevisionSlotsUpdate $slotsUpdate = null,
470 $parentId = null
471 ) {
472 if ( $revision
473 && $parentId
474 && $revision->getParentId() !== $parentId
475 ) {
476 throw new InvalidArgumentException( '$parentId should match the parent of $revision' );
477 }
478
479 // NOTE: For null revisions, $user may be different from $this->revision->getUser
480 // and also from $revision->getUser.
481 // But $user should always match $this->user.
482 if ( $user && $this->user && $user->getName() !== $this->user->getName() ) {
483 return false;
484 }
485
486 if ( $revision && $this->revision && $this->revision->getId()
487 && $this->revision->getId() !== $revision->getId()
488 ) {
489 return false;
490 }
491
492 if ( $this->pageState
493 && $revision
494 && $revision->getParentId() !== null
495 && $this->pageState['oldId'] !== $revision->getParentId()
496 ) {
497 return false;
498 }
499
500 if ( $this->pageState
501 && $parentId !== null
502 && $this->pageState['oldId'] !== $parentId
503 ) {
504 return false;
505 }
506
507 // NOTE: this check is the primary reason for having the $this->slotsUpdate field!
508 if ( $this->slotsUpdate
509 && $slotsUpdate
510 && !$this->slotsUpdate->hasSameUpdates( $slotsUpdate )
511 ) {
512 return false;
513 }
514
515 if ( $revision
516 && $this->revision
517 && !$this->revision->getSlots()->hasSameContent( $revision->getSlots() )
518 ) {
519 return false;
520 }
521
522 return true;
523 }
524
525 /**
526 * Set whether null-edits should create a revision. Enabling this allows the creation of dummy
527 * revisions ("null revisions") to mark events such as renaming in the page history.
528 *
529 * Must not be called once prepareContent() or prepareUpdate() have been called.
530 *
531 * @since 1.38
532 * @see PageUpdater setForceEmptyRevision
533 *
534 * @param bool $forceEmptyRevision
535 */
536 public function setForceEmptyRevision( bool $forceEmptyRevision ) {
537 if ( $this->revision ) {
538 throw new LogicException( 'prepareContent() or prepareUpdate() was already called.' );
539 }
540
541 $this->forceEmptyRevision = $forceEmptyRevision;
542 }
543
544 /**
545 * @param string $articleCountMethod "any" or "link".
546 * @see $wgArticleCountMethod
547 */
548 public function setArticleCountMethod( $articleCountMethod ) {
549 $this->articleCountMethod = $articleCountMethod;
550 }
551
552 /**
553 * @param bool $rcWatchCategoryMembership
554 * @see $wgRCWatchCategoryMembership
555 */
556 public function setRcWatchCategoryMembership( $rcWatchCategoryMembership ) {
557 $this->rcWatchCategoryMembership = $rcWatchCategoryMembership;
558 }
559
560 /**
561 * @return Title
562 */
563 private function getTitle() {
564 // NOTE: eventually, this won't use WikiPage any more
565 return $this->wikiPage->getTitle();
566 }
567
568 /**
569 * @return WikiPage
570 */
571 private function getWikiPage() {
572 // NOTE: eventually, this won't use WikiPage any more
573 return $this->wikiPage;
574 }
575
576 /**
577 * Returns the page being updated.
578 * @since 1.37
579 * @return PageIdentity
580 */
581 public function getPage(): PageIdentity {
582 return $this->wikiPage;
583 }
584
585 /**
586 * Determines whether the page being edited already existed.
587 * Only defined after calling grabCurrentRevision() or prepareContent() or prepareUpdate()!
588 *
589 * @return bool
590 * @throws LogicException if called before grabCurrentRevision
591 */
592 public function pageExisted() {
593 $this->assertHasPageState( __METHOD__ );
594
595 return $this->pageState['oldId'] > 0;
596 }
597
598 /**
599 * Returns the parent revision of the new revision wrapped by this update.
600 * If the update is a null-edit, this will return the parent of the current (and new) revision.
601 * This will return null if the revision wrapped by this update created the page.
602 * Only defined after calling prepareContent() or prepareUpdate()!
603 *
604 * @return RevisionRecord|null the parent revision of the new revision, or null if
605 * the update created the page.
606 */
607 private function getParentRevision() {
608 $this->assertPrepared( __METHOD__ );
609
610 if ( $this->parentRevision ) {
611 return $this->parentRevision;
612 }
613
614 if ( !$this->pageState['oldId'] ) {
615 // If there was no current revision, there is no parent revision,
616 // since the page didn't exist.
617 return null;
618 }
619
620 $oldId = $this->revision->getParentId();
621 $flags = $this->usePrimary() ? IDBAccessObject::READ_LATEST : 0;
622 $this->parentRevision = $oldId
623 ? $this->revisionStore->getRevisionById( $oldId, $flags )
624 : null;
625
626 return $this->parentRevision;
627 }
628
629 /**
630 * Returns the revision that was the page's current revision when grabCurrentRevision()
631 * was first called.
632 *
633 * During an edit, that revision will act as the logical parent of the new revision.
634 *
635 * Some updates are performed based on the difference between the database state at the
636 * moment this method is first called, and the state after the edit.
637 *
638 * @see docs/pageupdater.md for more information on when thie method can and should be called.
639 *
640 * @note After prepareUpdate() was called, grabCurrentRevision() will throw an exception
641 * to avoid confusion, since the page's current revision is then the new revision after
642 * the edit, which was presumably passed to prepareUpdate() as the $revision parameter.
643 * Use getParentRevision() instead to access the revision that is the parent of the
644 * new revision.
645 *
646 * @return RevisionRecord|null the page's current revision, or null if the page does not
647 * yet exist.
648 */
649 public function grabCurrentRevision() {
650 if ( $this->pageState ) {
651 return $this->pageState['oldRevision'];
652 }
653
654 $this->assertTransition( 'knows-current' );
655
656 // NOTE: eventually, this won't use WikiPage any more
657 $wikiPage = $this->getWikiPage();
658
659 // Do not call WikiPage::clear(), since the caller may already have caused page data
660 // to be loaded with SELECT FOR UPDATE. Just assert it's loaded now.
661 $wikiPage->loadPageData( IDBAccessObject::READ_LATEST );
662 $current = $wikiPage->getRevisionRecord();
663
664 $this->pageState = [
665 'oldRevision' => $current,
666 'oldId' => $current ? $current->getId() : 0,
667 'oldIsRedirect' => $wikiPage->isRedirect(), // NOTE: uses page table
668 'oldCountable' => $wikiPage->isCountable(), // NOTE: uses pagelinks table
669 ];
670
671 $this->doTransition( 'knows-current' );
672
673 return $this->pageState['oldRevision'];
674 }
675
676 /**
677 * Whether prepareUpdate() or prepareContent() have been called on this instance.
678 *
679 * @return bool
680 */
681 public function isContentPrepared() {
682 return $this->revision !== null;
683 }
684
685 /**
686 * Whether prepareUpdate() has been called on this instance.
687 *
688 * @note will also return null in case of a null-edit!
689 *
690 * @return bool
691 */
692 public function isUpdatePrepared() {
693 return $this->revision !== null && $this->revision->getId() !== null;
694 }
695
696 /**
697 * @return int
698 */
699 private function getPageId() {
700 // NOTE: eventually, this won't use WikiPage any more
701 return $this->wikiPage->getId();
702 }
703
704 /**
705 * Whether the content is deleted and thus not visible to the public.
706 *
707 * @return bool
708 */
709 public function isContentDeleted() {
710 if ( $this->revision ) {
711 return $this->revision->isDeleted( RevisionRecord::DELETED_TEXT );
712 } else {
713 // If the content has not been saved yet, it cannot have been deleted yet.
714 return false;
715 }
716 }
717
718 /**
719 * Returns the slot, modified or inherited, after PST, with no audience checks applied.
720 *
721 * @param string $role slot role name
722 *
723 * @throws PageUpdateException If the slot is neither set for update nor inherited from the
724 * parent revision.
725 * @return SlotRecord
726 */
727 public function getRawSlot( $role ) {
728 return $this->getSlots()->getSlot( $role );
729 }
730
731 /**
732 * Returns the content of the given slot, with no audience checks.
733 *
734 * @throws PageUpdateException If the slot is neither set for update nor inherited from the
735 * parent revision.
736 * @param string $role slot role name
737 * @return Content
738 */
739 public function getRawContent( string $role ): Content {
740 return $this->getRawSlot( $role )->getContent();
741 }
742
743 /**
744 * @param string $role slot role name
745 * @return ContentHandler
746 * @throws MWUnknownContentModelException
747 */
748 private function getContentHandler( $role ): ContentHandler {
749 return $this->contentHandlerFactory
750 ->getContentHandler( $this->getRawSlot( $role )->getModel() );
751 }
752
753 private function usePrimary() {
754 // TODO: can we just set a flag to true in prepareContent()?
755 return $this->wikiPage->wasLoadedFrom( IDBAccessObject::READ_LATEST );
756 }
757
758 /**
759 * @return bool
760 */
761 public function isCountable(): bool {
762 // NOTE: Keep in sync with WikiPage::isCountable.
763
764 if ( !$this->getTitle()->isContentPage() ) {
765 return false;
766 }
767
768 if ( $this->isContentDeleted() ) {
769 // This should be irrelevant: countability only applies to the current revision,
770 // and the current revision is never suppressed.
771 return false;
772 }
773
774 if ( $this->isRedirect() ) {
775 return false;
776 }
777
778 $hasLinks = null;
779
780 if ( $this->articleCountMethod === 'link' ) {
781 // NOTE: it would be more appropriate to determine for each slot separately
782 // whether it has links, and use that information with that slot's
783 // isCountable() method. However, that would break parity with
784 // WikiPage::isCountable, which uses the pagelinks table to determine
785 // whether the current revision has links.
786 $hasLinks = (bool)count( $this->getParserOutputForMetaData()->getLinks() );
787 }
788
789 foreach ( $this->getSlots()->getSlotRoles() as $role ) {
790 $roleHandler = $this->slotRoleRegistry->getRoleHandler( $role );
791 if ( $roleHandler->supportsArticleCount() ) {
792 $content = $this->getRawContent( $role );
793
794 if ( $content->isCountable( $hasLinks ) ) {
795 return true;
796 }
797 }
798 }
799
800 return false;
801 }
802
803 /**
804 * @return bool
805 */
806 public function isRedirect(): bool {
807 // NOTE: main slot determines redirect status
808 // TODO: MCR: this should be controlled by a PageTypeHandler
809 $mainContent = $this->getRawContent( SlotRecord::MAIN );
810
811 return $mainContent->isRedirect();
812 }
813
814 /**
815 * @param RevisionRecord $rev
816 *
817 * @return bool
818 */
819 private function revisionIsRedirect( RevisionRecord $rev ) {
820 // NOTE: main slot determines redirect status
821 $mainContent = $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
822
823 return $mainContent->isRedirect();
824 }
825
826 /**
827 * Prepare updates based on an update which has not yet been saved.
828 *
829 * This may be used to create derived data that is needed when creating a new revision;
830 * particularly, this makes available the slots of the new revision via the getSlots()
831 * method, after applying PST and slot inheritance.
832 *
833 * The derived data prepared for revision creation may then later be re-used by doUpdates(),
834 * without the need to re-calculate.
835 *
836 * @see docs/pageupdater.md for more information on when thie method can and should be called.
837 *
838 * @note Calling this method more than once with the same $slotsUpdate
839 * has no effect. Calling this method multiple times with different content will cause
840 * an exception.
841 *
842 * @note Calling this method after prepareUpdate() has been called will cause an exception.
843 *
844 * @param UserIdentity $user The user to act as context for pre-save transformation (PST).
845 * @param RevisionSlotsUpdate $slotsUpdate The new content of the slots to be updated
846 * by this edit, before PST.
847 * @param bool $useStash Whether to use stashed ParserOutput
848 */
849 public function prepareContent(
850 UserIdentity $user,
851 RevisionSlotsUpdate $slotsUpdate,
852 $useStash = true
853 ) {
854 if ( $this->slotsUpdate ) {
855 if ( !$this->user ) {
856 throw new LogicException(
857 'Unexpected state: $this->slotsUpdate was initialized, '
858 . 'but $this->user was not.'
859 );
860 }
861
862 if ( $this->user->getName() !== $user->getName() ) {
863 throw new LogicException( 'Can\'t call prepareContent() again for different user! '
864 . 'Expected ' . $this->user->getName() . ', got ' . $user->getName()
865 );
866 }
867
868 if ( !$this->slotsUpdate->hasSameUpdates( $slotsUpdate ) ) {
869 throw new LogicException(
870 'Can\'t call prepareContent() again with different slot content!'
871 );
872 }
873
874 return; // prepareContent() already done, nothing to do
875 }
876
877 $this->assertTransition( 'has-content' );
878
879 $wikiPage = $this->getWikiPage(); // TODO: use only for legacy hooks!
880 $title = $this->getTitle();
881
882 $parentRevision = $this->grabCurrentRevision();
883
884 // The edit may have already been prepared via api.php?action=stashedit
885 $stashedEdit = false;
886
887 // TODO: MCR: allow output for all slots to be stashed.
888 if ( $useStash && $slotsUpdate->isModifiedSlot( SlotRecord::MAIN ) ) {
889 $stashedEdit = $this->pageEditStash->checkCache(
890 $title,
891 $slotsUpdate->getModifiedSlot( SlotRecord::MAIN )->getContent(),
892 $user
893 );
894 }
895
896 $userPopts = ParserOptions::newFromUserAndLang( $user, $this->contLang );
897 $userPopts->setRenderReason( $this->options['causeAgent'] ?? 'unknown' );
898
899 $this->hookRunner->onArticlePrepareTextForEdit( $wikiPage, $userPopts );
900
901 $this->user = $user;
902 $this->slotsUpdate = $slotsUpdate;
903
904 if ( $parentRevision ) {
905 $this->revision = MutableRevisionRecord::newFromParentRevision( $parentRevision );
906 } else {
907 $this->revision = new MutableRevisionRecord( $title );
908 }
909
910 // NOTE: user and timestamp must be set, so they can be used for
911 // {{subst:REVISIONUSER}} and {{subst:REVISIONTIMESTAMP}} in PST!
912 $this->revision->setTimestamp( MWTimestamp::now( TS_MW ) );
913 $this->revision->setUser( $user );
914
915 // Set up ParserOptions to operate on the new revision
916 $oldCallback = $userPopts->getCurrentRevisionRecordCallback();
917 $userPopts->setCurrentRevisionRecordCallback(
918 function ( Title $parserTitle, $parser = null ) use ( $title, $oldCallback ) {
919 if ( $parserTitle->equals( $title ) ) {
920 return $this->revision;
921 } else {
922 return call_user_func( $oldCallback, $parserTitle, $parser );
923 }
924 }
925 );
926
927 $pstContentSlots = $this->revision->getSlots();
928
929 foreach ( $slotsUpdate->getModifiedRoles() as $role ) {
930 $slot = $slotsUpdate->getModifiedSlot( $role );
931
932 if ( $slot->isInherited() ) {
933 // No PST for inherited slots! Note that "modified" slots may still be inherited
934 // from an earlier version, e.g. for rollbacks.
935 $pstSlot = $slot;
936 } elseif ( $role === SlotRecord::MAIN && $stashedEdit ) {
937 // TODO: MCR: allow PST content for all slots to be stashed.
938 $pstSlot = SlotRecord::newUnsaved( $role, $stashedEdit->pstContent );
939 } else {
940 $pstContent = $this->contentTransformer->preSaveTransform(
941 $slot->getContent(),
942 $title,
943 $user,
944 $userPopts
945 );
946
947 $pstSlot = SlotRecord::newUnsaved( $role, $pstContent );
948 }
949
950 $pstContentSlots->setSlot( $pstSlot );
951 }
952
953 foreach ( $slotsUpdate->getRemovedRoles() as $role ) {
954 $pstContentSlots->removeSlot( $role );
955 }
956
957 $this->options['created'] = ( $parentRevision === null );
958 $this->options['changed'] = ( $parentRevision === null
959 || !$pstContentSlots->hasSameContent( $parentRevision->getSlots() ) );
960
961 $this->doTransition( 'has-content' );
962
963 if ( !$this->options['changed'] ) {
964 if ( $this->forceEmptyRevision ) {
965 // dummy revision, inherit all slots
966 foreach ( $parentRevision->getSlotRoles() as $role ) {
967 $this->revision->inheritSlot( $parentRevision->getSlot( $role ) );
968 }
969 } else {
970 // null-edit, the new revision *is* the old revision.
971
972 // TODO: move this into MutableRevisionRecord
973 $this->revision->setId( $parentRevision->getId() );
974 $this->revision->setTimestamp( $parentRevision->getTimestamp() );
975 $this->revision->setPageId( $parentRevision->getPageId() );
976 $this->revision->setParentId( $parentRevision->getParentId() );
977 $this->revision->setUser( $parentRevision->getUser( RevisionRecord::RAW ) );
978 $this->revision->setComment( $parentRevision->getComment( RevisionRecord::RAW ) );
979 $this->revision->setMinorEdit( $parentRevision->isMinor() );
980 $this->revision->setVisibility( $parentRevision->getVisibility() );
981
982 // prepareUpdate() is redundant for null-edits (but not for dummy revisions)
983 $this->doTransition( 'has-revision' );
984 }
985 } else {
986 $this->parentRevision = $parentRevision;
987 }
988
989 $renderHints = [ 'use-master' => $this->usePrimary(), 'audience' => RevisionRecord::RAW ];
990
991 if ( $stashedEdit ) {
992 /** @var ParserOutput $output */
993 $output = $stashedEdit->output;
994 // TODO: this should happen when stashing the ParserOutput, not now!
995 $output->setCacheTime( $stashedEdit->timestamp );
996
997 $renderHints['known-revision-output'] = $output;
998
999 $this->logger->debug( __METHOD__ . ': using stashed edit output...' );
1000 }
1001
1002 $renderHints['generate-html'] = $this->shouldGenerateHTMLOnEdit();
1003
1004 [ $causeAction, ] = $this->getCause();
1005 $renderHints['causeAction'] = $causeAction;
1006
1007 // NOTE: we want a canonical rendering, so don't pass $this->user or ParserOptions
1008 // NOTE: the revision is either new or current, so we can bypass audience checks.
1009 $this->renderedRevision = $this->revisionRenderer->getRenderedRevision(
1010 $this->revision,
1011 null,
1012 null,
1013 $renderHints
1014 );
1015 }
1016
1017 /**
1018 * Returns the update's target revision - that is, the revision that will be the current
1019 * revision after the update.
1020 *
1021 * @note Callers must treat the returned RevisionRecord's content as immutable, even
1022 * if it is a MutableRevisionRecord instance. Other aspects of a MutableRevisionRecord
1023 * returned from here, such as the user or the comment, may be changed, but may not
1024 * be reflected in ParserOutput until after prepareUpdate() has been called.
1025 *
1026 * @todo This is currently used by PageUpdater::makeNewRevision() to construct an unsaved
1027 * MutableRevisionRecord instance. Introduce something like an UnsavedRevisionFactory service
1028 * for that purpose instead!
1029 *
1030 * @return RevisionRecord
1031 */
1032 public function getRevision(): RevisionRecord {
1033 $this->assertPrepared( __METHOD__ );
1034 return $this->revision;
1035 }
1036
1037 /**
1038 * @return RenderedRevision
1039 */
1040 public function getRenderedRevision(): RenderedRevision {
1041 $this->assertPrepared( __METHOD__ );
1042
1043 return $this->renderedRevision;
1044 }
1045
1046 private function assertHasPageState( $method ) {
1047 if ( !$this->pageState ) {
1048 throw new LogicException(
1049 'Must call grabCurrentRevision() or prepareContent() '
1050 . 'or prepareUpdate() before calling ' . $method
1051 );
1052 }
1053 }
1054
1055 private function assertPrepared( $method ) {
1056 if ( !$this->revision ) {
1057 throw new LogicException(
1058 'Must call prepareContent() or prepareUpdate() before calling ' . $method
1059 );
1060 }
1061 }
1062
1063 private function assertHasRevision( $method ) {
1064 if ( !$this->revision->getId() ) {
1065 throw new LogicException(
1066 'Must call prepareUpdate() before calling ' . $method
1067 );
1068 }
1069 }
1070
1071 /**
1072 * Whether the edit creates the page.
1073 *
1074 * @return bool
1075 */
1076 public function isCreation() {
1077 $this->assertPrepared( __METHOD__ );
1078 return $this->options['created'];
1079 }
1080
1081 /**
1082 * Whether the content of the current revision after the edit is different from the content of the
1083 * current revision before the edit. This will return false for a null-edit (no revision created),
1084 * as well as for a dummy revision (a "null-revision" that has the same content as its parent).
1085 *
1086 * @warning at present, dummy revision would return false after prepareContent(),
1087 * but true after prepareUpdate()!
1088 *
1089 * @todo This should probably be fixed.
1090 *
1091 * @return bool
1092 */
1093 public function isChange() {
1094 $this->assertPrepared( __METHOD__ );
1095 return $this->options['changed'];
1096 }
1097
1098 /**
1099 * Whether the page was a redirect before the edit.
1100 *
1101 * @return bool
1102 */
1103 public function wasRedirect() {
1104 $this->assertHasPageState( __METHOD__ );
1105
1106 if ( $this->pageState['oldIsRedirect'] === null ) {
1107 /** @var RevisionRecord $rev */
1108 $rev = $this->pageState['oldRevision'];
1109 if ( $rev ) {
1110 $this->pageState['oldIsRedirect'] = $this->revisionIsRedirect( $rev );
1111 } else {
1112 $this->pageState['oldIsRedirect'] = false;
1113 }
1114 }
1115
1116 return $this->pageState['oldIsRedirect'];
1117 }
1118
1119 /**
1120 * Returns the slots of the target revision, after PST.
1121 *
1122 * @note Callers must treat the returned RevisionSlots instance as immutable, even
1123 * if it is a MutableRevisionSlots instance.
1124 *
1125 * @return RevisionSlots
1126 */
1127 public function getSlots() {
1128 $this->assertPrepared( __METHOD__ );
1129 return $this->revision->getSlots();
1130 }
1131
1132 /**
1133 * Returns the RevisionSlotsUpdate for this updater.
1134 *
1135 * @return RevisionSlotsUpdate
1136 */
1137 private function getRevisionSlotsUpdate() {
1138 $this->assertPrepared( __METHOD__ );
1139
1140 if ( !$this->slotsUpdate ) {
1141 $old = $this->getParentRevision();
1142 $this->slotsUpdate = RevisionSlotsUpdate::newFromRevisionSlots(
1143 $this->revision->getSlots(),
1144 $old ? $old->getSlots() : null
1145 );
1146 }
1147 return $this->slotsUpdate;
1148 }
1149
1150 /**
1151 * Returns the role names of the slots touched by the new revision,
1152 * including removed roles.
1153 *
1154 * @return string[]
1155 */
1156 public function getTouchedSlotRoles() {
1157 return $this->getRevisionSlotsUpdate()->getTouchedRoles();
1158 }
1159
1160 /**
1161 * Returns the role names of the slots modified by the new revision,
1162 * not including removed roles.
1163 *
1164 * @return string[]
1165 */
1166 public function getModifiedSlotRoles(): array {
1167 return $this->getRevisionSlotsUpdate()->getModifiedRoles();
1168 }
1169
1170 /**
1171 * Returns the role names of the slots removed by the new revision.
1172 *
1173 * @return string[]
1174 */
1175 public function getRemovedSlotRoles(): array {
1176 return $this->getRevisionSlotsUpdate()->getRemovedRoles();
1177 }
1178
1179 /**
1180 * Prepare derived data updates targeting the given RevisionRecord.
1181 *
1182 * Calling this method requires the given revision to be present in the database.
1183 * This may be right after a new revision has been created, or when re-generating
1184 * derived data e.g. in ApiPurge, RefreshLinksJob, and the refreshLinks
1185 * script.
1186 *
1187 * @see docs/pageupdater.md for more information on when thie method can and should be called.
1188 *
1189 * @note Calling this method more than once with the same revision has no effect.
1190 * $options are only used for the first call. Calling this method multiple times with
1191 * different revisions will cause an exception.
1192 *
1193 * @note If grabCurrentRevision() (or prepareContent()) has been called before
1194 * calling this method, $revision->getParentRevision() has to refer to the revision that
1195 * was the current revision at the time grabCurrentRevision() was called.
1196 *
1197 * @param RevisionRecord $revision
1198 * @param array $options Array of options, following indexes are used:
1199 * - changed: bool, whether the revision changed the content (default true)
1200 * - created: bool, whether the revision created the page (default false)
1201 * - moved: bool, whether the page was moved (default false)
1202 * - oldtitle: PageIdentity, if the page was moved this is the source title (default null)
1203 * - restored: bool, whether the page was undeleted (default false)
1204 * - oldrevision: RevisionRecord object for the pre-update revision (default null)
1205 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
1206 * user who created the revision)
1207 * - oldredirect: bool, null, or string 'no-change' (default null):
1208 * - bool: whether the page was counted as a redirect before that
1209 * revision, only used in changed is true and created is false
1210 * - null or 'no-change': don't update the redirect status.
1211 * - oldcountable: bool, null, or string 'no-change' (default null):
1212 * - bool: whether the page was counted as an article before that
1213 * revision, only used in changed is true and created is false
1214 * - null: if created is false, don't update the article count; if created
1215 * is true, do update the article count
1216 * - 'no-change': don't update the article count, ever
1217 * When set to null, pageState['oldCountable'] will be used instead if available.
1218 * - causeAction: an arbitrary string identifying the reason for the update.
1219 * See DataUpdate::getCauseAction(). (default 'unknown')
1220 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
1221 * (string, default 'unknown')
1222 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
1223 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
1224 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
1225 * for the time until caches have been changed to store RenderedRevision states instead
1226 * of ParserOutput objects. (default: null) (since 1.33)
1227 * - editResult: EditResult object created during the update. Required to perform reverted
1228 * tag update using RevertedTagUpdateJob. (default: null) (since 1.36)
1229 * - approved: whether the edit is somehow "approved" and the RevertedTagUpdateJob should
1230 * be scheduled right away. Required only if EditResult::isRevert() is true. (boolean,
1231 * default: false) (since 1.36)
1232 */
1233 public function prepareUpdate( RevisionRecord $revision, array $options = [] ) {
1234 Assert::parameter(
1235 !isset( $options['oldrevision'] )
1236 || $options['oldrevision'] instanceof RevisionRecord,
1237 '$options["oldrevision"]',
1238 'must be a RevisionRecord'
1239 );
1240 Assert::parameter(
1241 !isset( $options['triggeringUser'] )
1242 || $options['triggeringUser'] instanceof UserIdentity,
1243 '$options["triggeringUser"]',
1244 'must be a UserIdentity'
1245 );
1246 Assert::parameter(
1247 !isset( $options['editResult'] )
1248 || $options['editResult'] instanceof EditResult,
1249 '$options["editResult"]',
1250 'must be an EditResult'
1251 );
1252
1253 if ( !$revision->getId() ) {
1254 throw new InvalidArgumentException(
1255 'Revision must have an ID set for it to be used with prepareUpdate()!'
1256 );
1257 }
1258
1259 if ( $this->revision && $this->revision->getId() ) {
1260 if ( $this->revision->getId() === $revision->getId() ) {
1261 return; // nothing to do!
1262 } else {
1263 throw new LogicException(
1264 'Trying to re-use DerivedPageDataUpdater with revision '
1265 . $revision->getId()
1266 . ', but it\'s already bound to revision '
1267 . $this->revision->getId()
1268 );
1269 }
1270 }
1271
1272 if ( $this->revision
1273 && !$this->revision->getSlots()->hasSameContent( $revision->getSlots() )
1274 ) {
1275 throw new LogicException(
1276 'The revision provided has mismatching content!'
1277 );
1278 }
1279
1280 // Override fields defined in $this->options with values from $options.
1281 $this->options = array_intersect_key( $options, $this->options ) + $this->options;
1282
1283 if ( $this->revision ) {
1284 $oldId = $this->pageState['oldId'] ?? 0;
1285 $this->options['newrev'] = ( $revision->getId() !== $oldId );
1286 } elseif ( isset( $this->options['oldrevision'] ) ) {
1287 /** @var RevisionRecord $oldRev */
1288 $oldRev = $this->options['oldrevision'];
1289 $oldId = $oldRev->getId();
1290 $this->options['newrev'] = ( $revision->getId() !== $oldId );
1291 } else {
1292 $oldId = $revision->getParentId();
1293 }
1294
1295 if ( $oldId !== null ) {
1296 // XXX: what if $options['changed'] disagrees?
1297 // MovePage creates a dummy revision with changed = false!
1298 // We may want to explicitly distinguish between "no new revision" (null-edit)
1299 // and "new revision without new content" (dummy revision).
1300
1301 if ( $oldId === $revision->getParentId() ) {
1302 // NOTE: this may still be a NullRevision!
1303 // New revision!
1304 $this->options['changed'] = true;
1305 } elseif ( $oldId === $revision->getId() ) {
1306 // Null-edit!
1307 $this->options['changed'] = false;
1308 } else {
1309 // This indicates that calling code has given us the wrong RevisionRecord object
1310 throw new LogicException(
1311 'The RevisionRecord mismatches old revision ID: '
1312 . 'Old ID is ' . $oldId
1313 . ', parent ID is ' . $revision->getParentId()
1314 . ', revision ID is ' . $revision->getId()
1315 );
1316 }
1317 }
1318
1319 // If prepareContent() was used to generate the PST content (which is indicated by
1320 // $this->slotsUpdate being set), and this is not a null-edit, then the given
1321 // revision must have the acting user as the revision author. Otherwise, user
1322 // signatures generated by PST would mismatch the user in the revision record.
1323 if ( $this->user !== null && $this->options['changed'] && $this->slotsUpdate ) {
1324 $user = $revision->getUser();
1325 if ( !$this->user->equals( $user ) ) {
1326 throw new LogicException(
1327 'The RevisionRecord provided has a mismatching actor: expected '
1328 . $this->user->getName()
1329 . ', got '
1330 . $user->getName()
1331 );
1332 }
1333 }
1334
1335 // If $this->pageState was not yet initialized by grabCurrentRevision or prepareContent,
1336 // emulate the state of the page table before the edit, as good as we can.
1337 if ( !$this->pageState ) {
1338 $this->pageState = [
1339 'oldIsRedirect' => isset( $this->options['oldredirect'] )
1340 && is_bool( $this->options['oldredirect'] )
1341 ? $this->options['oldredirect']
1342 : null,
1343 'oldCountable' => isset( $this->options['oldcountable'] )
1344 && is_bool( $this->options['oldcountable'] )
1345 ? $this->options['oldcountable']
1346 : null,
1347 ];
1348
1349 if ( $this->options['changed'] ) {
1350 // The edit created a new revision
1351 $this->pageState['oldId'] = $revision->getParentId();
1352 // Old revision is null if this is a page creation
1353 $this->pageState['oldRevision'] = $this->options['oldrevision'] ?? null;
1354 } else {
1355 // This is a null-edit, so the old revision IS the new revision!
1356 $this->pageState['oldId'] = $revision->getId();
1357 $this->pageState['oldRevision'] = $revision;
1358 }
1359 }
1360
1361 // "created" is forced here
1362 $this->options['created'] = ( $this->options['created'] ||
1363 ( $this->pageState['oldId'] === 0 ) );
1364
1365 $this->revision = $revision;
1366
1367 $this->doTransition( 'has-revision' );
1368
1369 // NOTE: in case we have a User object, don't override with a UserIdentity.
1370 // We already checked that $revision->getUser() matches $this->user;
1371 if ( !$this->user ) {
1372 $this->user = $revision->getUser( RevisionRecord::RAW );
1373 }
1374
1375 // Prune any output that depends on the revision ID.
1376 if ( $this->renderedRevision ) {
1377 $this->renderedRevision->updateRevision( $revision );
1378 } else {
1379 [ $causeAction, ] = $this->getCause();
1380 // NOTE: we want a canonical rendering, so don't pass $this->user or ParserOptions
1381 // NOTE: the revision is either new or current, so we can bypass audience checks.
1382 $this->renderedRevision = $this->revisionRenderer->getRenderedRevision(
1383 $this->revision,
1384 null,
1385 null,
1386 [
1387 'use-master' => $this->usePrimary(),
1388 'audience' => RevisionRecord::RAW,
1389 'known-revision-output' => $options['known-revision-output'] ?? null,
1390 'causeAction' => $causeAction
1391 ]
1392 );
1393
1394 // XXX: Since we presumably are dealing with the current revision,
1395 // we could try to get the ParserOutput from the parser cache.
1396 }
1397
1398 // TODO: optionally get ParserOutput from the ParserCache here.
1399 // Move the logic used by RefreshLinksJob here!
1400 }
1401
1402 /**
1403 * @deprecated since 1.43; This only exists for B/C, use the getters on DerivedPageDataUpdater directly!
1404 * @return PreparedEdit
1405 */
1406 public function getPreparedEdit() {
1407 $this->assertPrepared( __METHOD__ );
1408
1409 $slotsUpdate = $this->getRevisionSlotsUpdate();
1410 $preparedEdit = new PreparedEdit();
1411
1412 $preparedEdit->popts = $this->getCanonicalParserOptions();
1413 $preparedEdit->parserOutputCallback = [ $this, 'getCanonicalParserOutput' ];
1414 $preparedEdit->pstContent = $this->revision->getContent( SlotRecord::MAIN );
1415 $preparedEdit->newContent =
1416 $slotsUpdate->isModifiedSlot( SlotRecord::MAIN )
1417 ? $slotsUpdate->getModifiedSlot( SlotRecord::MAIN )->getContent()
1418 : $this->revision->getContent( SlotRecord::MAIN ); // XXX: can we just remove this?
1419 $preparedEdit->oldContent = null; // unused. // XXX: could get this from the parent revision
1420 $preparedEdit->revid = $this->revision ? $this->revision->getId() : null;
1421 $preparedEdit->format = $preparedEdit->pstContent->getDefaultFormat();
1422
1423 return $preparedEdit;
1424 }
1425
1426 /**
1427 * @param string $role
1428 * @param bool $generateHtml
1429 * @return ParserOutput
1430 */
1431 public function getSlotParserOutput( $role, $generateHtml = true ) {
1432 return $this->getRenderedRevision()->getSlotParserOutput(
1433 $role,
1434 [ 'generate-html' => $generateHtml ]
1435 );
1436 }
1437
1438 /**
1439 * @since 1.37
1440 * @return ParserOutput
1441 */
1442 public function getParserOutputForMetaData(): ParserOutput {
1443 return $this->getRenderedRevision()->getRevisionParserOutput( [ 'generate-html' => false ] );
1444 }
1445
1446 /**
1447 * @inheritDoc
1448 * @return ParserOutput
1449 */
1450 public function getCanonicalParserOutput(): ParserOutput {
1451 return $this->getRenderedRevision()->getRevisionParserOutput();
1452 }
1453
1454 /**
1455 * @return ParserOptions
1456 */
1457 public function getCanonicalParserOptions(): ParserOptions {
1458 return $this->getRenderedRevision()->getOptions();
1459 }
1460
1461 /**
1462 * @param bool $recursive
1463 *
1464 * @return DeferrableUpdate[]
1465 */
1466 public function getSecondaryDataUpdates( $recursive = false ) {
1467 if ( $this->isContentDeleted() ) {
1468 // This shouldn't happen, since the current content is always public,
1469 // and DataUpdates are only needed for current content.
1470 return [];
1471 }
1472
1473 $wikiPage = $this->getWikiPage();
1474 $wikiPage->loadPageData( IDBAccessObject::READ_LATEST );
1475 if ( !$wikiPage->exists() ) {
1476 // page deleted while deferring the update
1477 return [];
1478 }
1479
1480 $title = $wikiPage->getTitle();
1481 $allUpdates = [];
1482 $parserOutput = $this->shouldGenerateHTMLOnEdit() ?
1483 $this->getCanonicalParserOutput() : $this->getParserOutputForMetaData();
1484
1485 // Construct a LinksUpdate for the combined canonical output.
1486 $linksUpdate = new LinksUpdate(
1487 $title,
1488 $parserOutput,
1489 $recursive,
1490 // Redirect target may have changed if the page is or was a redirect.
1491 // (We can't check if it was definitely changed without additional queries.)
1492 $this->isRedirect() || $this->wasRedirect()
1493 );
1494 if ( $this->options['moved'] ) {
1495 // @phan-suppress-next-line PhanTypeMismatchArgument Oldtitle is set along with moved
1496 $linksUpdate->setMoveDetails( $this->options['oldtitle'] );
1497 }
1498
1499 $allUpdates[] = $linksUpdate;
1500 // NOTE: Run updates for all slots, not just the modified slots! Otherwise,
1501 // info for an inherited slot may end up being removed. This is also needed
1502 // to ensure that purges are effective.
1503 $renderedRevision = $this->getRenderedRevision();
1504
1505 foreach ( $this->getSlots()->getSlotRoles() as $role ) {
1506 $slot = $this->getRawSlot( $role );
1507 $content = $slot->getContent();
1508 $handler = $content->getContentHandler();
1509
1510 $updates = $handler->getSecondaryDataUpdates(
1511 $title,
1512 $content,
1513 $role,
1514 $renderedRevision
1515 );
1516
1517 $allUpdates = array_merge( $allUpdates, $updates );
1518 }
1519
1520 // XXX: if a slot was removed by an earlier edit, but deletion updates failed to run at
1521 // that time, we don't know for which slots to run deletion updates when purging a page.
1522 // We'd have to examine the entire history of the page to determine that. Perhaps there
1523 // could be a "try extra hard" mode for that case that would run a DB query to find all
1524 // roles/models ever used on the page. On the other hand, removing slots should be quite
1525 // rare, so perhaps this isn't worth the trouble.
1526
1527 // TODO: consolidate with similar logic in WikiPage::getDeletionUpdates()
1528 $parentRevision = $this->getParentRevision();
1529 foreach ( $this->getRemovedSlotRoles() as $role ) {
1530 // HACK: we should get the content model of the removed slot from a SlotRoleHandler!
1531 // For now, find the slot in the parent revision - if the slot was removed, it should
1532 // always exist in the parent revision.
1533 $parentSlot = $parentRevision->getSlot( $role, RevisionRecord::RAW );
1534 $content = $parentSlot->getContent();
1535 $handler = $content->getContentHandler();
1536
1537 $updates = $handler->getDeletionUpdates(
1538 $title,
1539 $role
1540 );
1541
1542 $allUpdates = array_merge( $allUpdates, $updates );
1543 }
1544
1545 // TODO: hard deprecate SecondaryDataUpdates in favor of RevisionDataUpdates in 1.33!
1546 $this->hookRunner->onRevisionDataUpdates( $title, $renderedRevision, $allUpdates );
1547
1548 return $allUpdates;
1549 }
1550
1551 /**
1552 * @return bool true if at least one of slots require rendering HTML on edit, false otherwise.
1553 * This is needed for example in populating ParserCache.
1554 */
1555 private function shouldGenerateHTMLOnEdit(): bool {
1556 foreach ( $this->getSlots()->getSlotRoles() as $role ) {
1557 $slot = $this->getRawSlot( $role );
1558 $contentHandler = $this->contentHandlerFactory->getContentHandler( $slot->getModel() );
1559 if ( $contentHandler->generateHTMLOnEdit() ) {
1560 return true;
1561 }
1562 }
1563 return false;
1564 }
1565
1566 /**
1567 * Do standard updates after page edit, purge, or import.
1568 * Update links tables, site stats, search index, title cache, message cache, etc.
1569 * Purges pages that depend on this page when appropriate.
1570 * With a 10% chance, triggers pruning the recent changes table.
1571 *
1572 * @note prepareUpdate() must be called before calling this method!
1573 *
1574 * MCR migration note: this replaces WikiPage::doEditUpdates.
1575 */
1576 public function doUpdates() {
1577 $this->assertTransition( 'done' );
1578
1579 // TODO: move logic into a PageEventEmitter service
1580
1581 $wikiPage = $this->getWikiPage(); // TODO: use only for legacy hooks!
1582
1583 if ( $this->shouldGenerateHTMLOnEdit() ) {
1584 $this->triggerParserCacheUpdate();
1585 }
1586
1587 $this->doSecondaryDataUpdates( [
1588 // T52785 do not update any other pages on a null edit
1589 'recursive' => $this->options['changed'],
1590 // Defer the getCanonicalParserOutput() call made by getSecondaryDataUpdates()
1591 'defer' => DeferredUpdates::POSTSEND
1592 ] );
1593
1594 // TODO: MCR: check if *any* changed slot supports categories!
1595 if ( $this->rcWatchCategoryMembership
1596 && $this->getContentHandler( SlotRecord::MAIN )->supportsCategories() === true
1597 && ( $this->options['changed'] || $this->options['created'] )
1598 && !$this->options['restored']
1599 ) {
1600 // Note: jobs are pushed after deferred updates, so the job should be able to see
1601 // the recent change entry (also done via deferred updates) and carry over any
1602 // bot/deletion/IP flags, ect.
1603 $this->jobQueueGroup->lazyPush(
1604 CategoryMembershipChangeJob::newSpec(
1605 $this->getTitle(),
1606 $this->revision->getTimestamp(),
1607 $this->options['causeAction'] === 'import-page'
1608 )
1609 );
1610 }
1611
1612 $id = $this->getPageId();
1613 $title = $this->getTitle();
1614 $shortTitle = $title->getDBkey();
1615
1616 if ( !$title->exists() ) {
1617 wfDebug( __METHOD__ . ": Page doesn't exist any more, bailing out" );
1618
1619 $this->doTransition( 'done' );
1620 return;
1621 }
1622
1623 DeferredUpdates::addCallableUpdate( function () {
1624 if (
1625 $this->options['oldcountable'] === 'no-change' ||
1626 ( !$this->options['changed'] && !$this->options['moved'] )
1627 ) {
1628 $good = 0;
1629 } elseif ( $this->options['created'] ) {
1630 $good = (int)$this->isCountable();
1631 } elseif ( $this->options['oldcountable'] !== null ) {
1632 $good = (int)$this->isCountable()
1633 - (int)$this->options['oldcountable'];
1634 } elseif ( isset( $this->pageState['oldCountable'] ) ) {
1635 $good = (int)$this->isCountable()
1636 - (int)$this->pageState['oldCountable'];
1637 } else {
1638 $good = 0;
1639 }
1640 $edits = $this->options['changed'] ? 1 : 0;
1641 $pages = $this->options['created'] ? 1 : 0;
1642
1643 DeferredUpdates::addUpdate( SiteStatsUpdate::factory(
1644 [ 'edits' => $edits, 'articles' => $good, 'pages' => $pages ]
1645 ) );
1646 } );
1647
1648 // TODO: make search infrastructure aware of slots!
1649 $mainSlot = $this->revision->getSlot( SlotRecord::MAIN );
1650 if ( !$mainSlot->isInherited() && !$this->isContentDeleted() ) {
1651 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $mainSlot->getContent() ) );
1652 }
1653
1654 // If this is another user's talk page, update newtalk.
1655 // Don't do this if $options['changed'] = false (null-edits) nor if
1656 // it's a minor edit and the user making the edit doesn't generate notifications for those.
1657 // TODO: the permission check should be performed by the callers, see T276181.
1658 if ( $this->options['changed']
1659 && $title->getNamespace() === NS_USER_TALK
1660 && $title->getText() != $this->user->getName()
1661 && !( $this->revision->isMinor() && $this->permissionManager
1662 ->userHasRight( $this->user, 'nominornewtalk' )
1663 )
1664 ) {
1665 $recipient = User::newFromName( $shortTitle, false );
1666 if ( !$recipient ) {
1667 wfDebug( __METHOD__ . ": invalid username" );
1668 } else {
1669 // Allow extensions to prevent user notification
1670 // when a new message is added to their talk page
1671 // TODO: replace legacy hook! Use a listener on PageEventEmitter instead!
1672 if ( $this->hookRunner->onArticleEditUpdateNewTalk( $wikiPage, $recipient ) ) {
1673 $revRecord = $this->revision;
1674 if ( $this->userNameUtils->isIP( $shortTitle ) ) {
1675 // An anonymous user
1676 $this->talkPageNotificationManager->setUserHasNewMessages( $recipient, $revRecord );
1677 } elseif ( $recipient->isRegistered() ) {
1678 $this->talkPageNotificationManager->setUserHasNewMessages( $recipient, $revRecord );
1679 } else {
1680 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user" );
1681 }
1682 }
1683 }
1684 }
1685
1686 if ( $title->getNamespace() === NS_MEDIAWIKI
1687 && $this->getRevisionSlotsUpdate()->isModifiedSlot( SlotRecord::MAIN )
1688 ) {
1689 $mainContent = $this->isContentDeleted() ? null : $this->getRawContent( SlotRecord::MAIN );
1690
1691 $this->messageCache->updateMessageOverride( $title, $mainContent );
1692 }
1693
1694 // TODO: move onArticleCreate and onArticleEdit into a PageEventEmitter service
1695 if ( $this->options['created'] ) {
1696 WikiPage::onArticleCreate( $title, $this->isRedirect() );
1697 } elseif ( $this->options['changed'] ) { // T52785
1698 WikiPage::onArticleEdit(
1699 $title,
1700 $this->revision,
1701 $this->getTouchedSlotRoles(),
1702 // Redirect target may have changed if the page is or was a redirect.
1703 // (We can't check if it was definitely changed without additional queries.)
1704 $this->isRedirect() || $this->wasRedirect()
1705 );
1706 } elseif ( $this->options['restored'] ) {
1707 $this->mainWANObjectCache->touchCheckKey(
1708 "DerivedPageDataUpdater:restore:page:$id"
1709 );
1710 }
1711
1712 $oldRevisionRecord = $this->getParentRevision();
1713
1714 // TODO: In the wiring, register a listener for this on the new PageEventEmitter
1715 RL\WikiModule::invalidateModuleCache(
1716 $title,
1717 $oldRevisionRecord,
1718 $this->revision,
1719 $this->loadbalancerFactory->getLocalDomainID()
1720 );
1721
1722 // Schedule a deferred update for marking reverted edits if applicable.
1723 $this->maybeEnqueueRevertedTagUpdateJob();
1724
1725 $this->doTransition( 'done' );
1726 }
1727
1728 private function triggerParserCacheUpdate() {
1729 $this->assertHasRevision( __METHOD__ );
1730
1731 $userParserOptions = ParserOptions::newFromUser( $this->user );
1732
1733 // Decide whether to save the final canonical parser output based on the fact that
1734 // users are typically redirected to viewing pages right after they edit those pages.
1735 // Due to vary-revision-id, getting/saving that output here might require a reparse.
1736 if ( $userParserOptions->matchesForCacheKey( $this->getCanonicalParserOptions() ) ) {
1737 // Whether getting the final output requires a reparse or not, the user will
1738 // need canonical output anyway, since that is what their parser options use.
1739 // A reparse now at least has the benefit of various warm process caches.
1740 $this->doParserCacheUpdate();
1741 } else {
1742 // If the user does not have canonical parse options, then don't risk another parse
1743 // to make output they cannot use on the page refresh that typically occurs after
1744 // editing. Doing the parser output save post-send will still benefit *other* users.
1745 DeferredUpdates::addCallableUpdate( function () {
1746 $this->doParserCacheUpdate();
1747 } );
1748 }
1749 }
1750
1751 /**
1752 * If the edit was a revert and it is considered "approved", enqueues the
1753 * RevertedTagUpdateJob for it. If the edit is not yet approved, the EditResult is
1754 * persisted in cache for later use.
1755 */
1756 private function maybeEnqueueRevertedTagUpdateJob() {
1757 if ( $this->options['editResult'] === null ) {
1758 return;
1759 }
1760
1761 $editResult = $this->options['editResult'];
1762 if ( !$editResult->isRevert() ) {
1763 return;
1764 }
1765
1766 if ( $this->options['approved'] ) {
1767 // Enqueue the job
1768 $this->jobQueueGroup->lazyPush(
1769 RevertedTagUpdateJob::newSpec(
1770 $this->revision->getId(),
1771 $this->options['editResult']
1772 )
1773 );
1774 } else {
1775 // Cache EditResult for later use
1776 $this->editResultCache->set(
1777 $this->revision->getId(),
1778 $this->options['editResult']
1779 );
1780 }
1781 }
1782
1783 /**
1784 * Do secondary data updates (e.g. updating link tables) or schedule them as deferred updates
1785 *
1786 * @note This does not update the parser cache. Use doParserCacheUpdate() for that.
1787 * @note Application logic should use Wikipage::doSecondaryDataUpdates instead.
1788 *
1789 * @param array $options
1790 * - recursive: make the update recursive, i.e. also update pages which transclude the
1791 * current page or otherwise depend on it (default: false)
1792 * - defer: one of the DeferredUpdates constants, or false to run immediately after waiting
1793 * for replication of the changes from the SecondaryDataUpdates hooks (default: false)
1794 * - freshness: used with 'defer'; forces an update if the last update was before the given timestamp,
1795 * even if the page and its dependencies didn't change since then (TS_MW; default: false)
1796 * @since 1.32
1797 */
1798 public function doSecondaryDataUpdates( array $options = [] ) {
1799 $this->assertHasRevision( __METHOD__ );
1800 $options += [ 'recursive' => false, 'defer' => false, 'freshness' => false ];
1801 $deferValues = [ false, DeferredUpdates::PRESEND, DeferredUpdates::POSTSEND ];
1802 if ( !in_array( $options['defer'], $deferValues, true ) ) {
1803 throw new InvalidArgumentException( 'Invalid value for defer: ' . $options['defer'] );
1804 }
1805
1806 $triggeringUser = $this->options['triggeringUser'] ?? $this->user;
1807 [ $causeAction, $causeAgent ] = $this->getCause();
1808 if ( isset( $options['known-revision-output'] ) ) {
1809 $this->getRenderedRevision()->setRevisionParserOutput( $options['known-revision-output'] );
1810 }
1811
1812 // Bundle all of the data updates into a single deferred update wrapper so that
1813 // any failure will cause at most one refreshLinks job to be enqueued by
1814 // DeferredUpdates::doUpdates(). This is hard to do when there are many separate
1815 // updates that are not defined as being related.
1816 $update = new RefreshSecondaryDataUpdate(
1817 $this->loadbalancerFactory,
1818 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Already checked
1819 $triggeringUser,
1820 $this->wikiPage,
1821 $this->revision,
1822 $this,
1823 [ 'recursive' => $options['recursive'], 'freshness' => $options['freshness'] ]
1824 );
1825 $update->setCause( $causeAction, $causeAgent );
1826
1827 if ( $options['defer'] === false ) {
1828 DeferredUpdates::attemptUpdate( $update );
1829 } else {
1830 DeferredUpdates::addUpdate( $update, $options['defer'] );
1831 }
1832 }
1833
1834 /**
1835 * Causes parser cache entries to be updated.
1836 *
1837 * @note This does not update links tables. Use doSecondaryDataUpdates() for that.
1838 * @note Application logic should use Wikipage::updateParserCache instead.
1839 */
1840 public function doParserCacheUpdate() {
1841 $this->assertHasRevision( __METHOD__ );
1842
1843 $wikiPage = $this->getWikiPage(); // TODO: ParserCache should accept a RevisionRecord instead
1844
1845 // NOTE: this may trigger the first parsing of the new content after an edit (when not
1846 // using pre-generated stashed output).
1847 // XXX: we may want to use the PoolCounter here. This would perhaps allow the initial parse
1848 // to be performed post-send. The client could already follow a HTTP redirect to the
1849 // page view, but would then have to wait for a response until rendering is complete.
1850 $output = $this->getCanonicalParserOutput();
1851
1852 // Save it to the parser cache. Use the revision timestamp in the case of a
1853 // freshly saved edit, as that matches page_touched and a mismatch would trigger an
1854 // unnecessary reparse.
1855 $timestamp = $this->options['newrev'] ? $this->revision->getTimestamp()
1856 : $output->getCacheTime();
1857 $this->parserCache->save(
1858 $output, $wikiPage, $this->getCanonicalParserOptions(),
1859 $timestamp, $this->revision->getId()
1860 );
1861
1862 // If we enable cache warming with parsoid outputs, let's do it at the same
1863 // time we're populating the parser cache with pre-generated HTML.
1864 // Use OPT_FORCE_PARSE to avoid a useless cache lookup.
1865 if ( $this->warmParsoidParserCache ) {
1866 $cacheWarmingParams = $this->getCause();
1867 $cacheWarmingParams['options'] = ParserOutputAccess::OPT_FORCE_PARSE;
1868
1869 $this->jobQueueGroup->lazyPush(
1870 ParsoidCachePrewarmJob::newSpec(
1871 $this->revision->getId(),
1872 $wikiPage->toPageRecord(),
1873 $cacheWarmingParams
1874 )
1875 );
1876 }
1877 }
1878
1879 }