Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.90% covered (warning)
78.90%
172 / 218
68.75% covered (warning)
68.75%
11 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
PageChangeEventSerializer
78.90% covered (warning)
78.90%
172 / 218
68.75% covered (warning)
68.75%
11 / 16
77.40
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toEvent
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 getChangelogKind
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getWikiId
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 toCommonAttrs
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
5.01
 toPageAttrs
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 toPageLinkAttrs
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 toUserAttrs
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 toRevisionAttrs
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 toCreateEvent
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 toEditEvent
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
5
 toRevertAttrs
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
132
 toMoveEvent
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
2
 toDeleteEvent
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
3
 toUndeleteEvent
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 toVisibilityChangeEvent
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
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 * @author Andrew Otto <otto@wikimedia.org>
20 */
21
22namespace MediaWiki\Extension\EventBus\Serializers\MediaWiki;
23
24use MediaWiki\Extension\EventBus\Entity\PageLink;
25use MediaWiki\Extension\EventBus\GlobalEditCountLookup;
26use MediaWiki\Extension\EventBus\Serializers\EventSerializer;
27use MediaWiki\Extension\EventBus\WikibaseItemLookup;
28use MediaWiki\Http\Telemetry;
29use MediaWiki\Page\ProperPageIdentity;
30use MediaWiki\Revision\RevisionRecord;
31use MediaWiki\Revision\RevisionStore;
32use MediaWiki\Storage\EditResult;
33use MediaWiki\User\UserIdentity;
34use MediaWiki\WikiMap\WikiMap;
35use UnexpectedValueException;
36use Wikimedia\Assert\Assert;
37
38/**
39 * Methods to convert from incoming page state changes (via Hooks)
40 * to a mediawiki/page/change event.
41 */
42class PageChangeEventSerializer {
43
44    /**
45     * All page change events will have their $schema URI set to this.
46     * https://phabricator.wikimedia.org/T308017
47     */
48    public const PAGE_CHANGE_SCHEMA_URI = '/mediawiki/page/change/1.12.0';
49
50    /**
51     * The schema version of the user entity used when serializing users.
52     */
53    public const USER_ENTITY_SCHEMA_VERSION = '1.3.0';
54
55    /**
56     * The schema version of the revision entity used when serializing revisions.
57     */
58    public const REVISION_ENTITY_SCHEMA_VERSION = '2.0.0';
59
60    /**
61     * The schema version of the revision slots entity used when serializing revision slots.
62     */
63    public const REVISION_SLOTS_ENTITY_SCHEMA_VERSION = '2.0.1';
64
65    /**
66     * The schema version of the page link entity used when serializing page link entities.
67     */
68    public const PAGE_LINK_ENTITY_SCHEMA_VERSION = '1.0.0';
69
70    /**
71     * The schema version of the page entity used when serializing page entities.
72     */
73    public const PAGE_ENTITY_SCHEMA_VERSION = '2.1.0';
74
75    /**
76     * There are many kinds of changes that can happen to a MediaWiki pages,
77     * but only a few kinds of changes in a 'changelog' stream.
78     * This maps from a MediaWiki page change kind to a changelog kind.
79     */
80    private const PAGE_CHANGE_KIND_TO_CHANGELOG_KIND_MAP = [
81        'create' => 'insert',
82        'edit' => 'update',
83        'move' => 'update',
84        'visibility_change' => 'update',
85        'delete' => 'delete',
86        'undelete' => 'insert',
87    ];
88
89    public function __construct(
90        private readonly EventSerializer $eventSerializer,
91        private readonly PageEntitySerializer $pageEntitySerializer,
92        private readonly PageLinkEntitySerializer $pageLinkEntitySerializer,
93        private readonly UserEntitySerializer $userEntitySerializer,
94        private readonly GlobalEditCountLookup $globalEditCountLookup,
95        private readonly WikibaseItemLookup $wikibaseItemLookup,
96        private readonly RevisionEntitySerializer $revisionEntitySerializer,
97        private readonly RevisionSlotsEntitySerializer $revisionSlotsEntitySerializer,
98        private readonly RevisionStore $revisionStore
99    ) {
100    }
101
102    /**
103     * Uses EventSerializer to create the mediawiki/page/change event for the given $eventAttrs
104     * @param string $stream
105     * @param ProperPageIdentity $page
106     * @param array $eventAttrs
107     * @return array
108     */
109    private function toEvent(
110        string $stream,
111        ProperPageIdentity $page,
112        array $eventAttrs,
113    ): array {
114        // NOTE: It would be better if wiki domain name was fetched and passed into createEvent,
115        // rather than forcing EventSerializer->createEvent to look up the domain itself.
116        // However, this would require changing the createEvent method signature, which is used
117        // by CirrusSearch extension.
118        // See: https://phabricator.wikimedia.org/T392516
119        return $this->eventSerializer->createEvent(
120            self::PAGE_CHANGE_SCHEMA_URI,
121            $stream,
122            $this->pageEntitySerializer->canonicalPageURL( $page ),
123            $eventAttrs,
124            self::getWikiId( $page ),
125            null,
126            // NOTE: This is using a global Telemetry instance, and it might be better to
127            // pass $requestId here as a parameter (obtaining the value of it in
128            // the PageChangeEventIngress handler instead of here in the serializer).
129            // We'd have to make every event handler here also accept $requestId as a parameter.
130            // This might be a good refactor for later, but for now this is fine.
131            Telemetry::getInstance()->getRequestId(),
132        );
133    }
134
135    /**
136     * Returns the appropriate changelog kind given a pageChangeKind.
137     * @param string $pageChangeKind
138     * @return string
139     */
140    private static function getChangelogKind( string $pageChangeKind ): string {
141        Assert::parameter(
142            array_key_exists( $pageChangeKind, self::PAGE_CHANGE_KIND_TO_CHANGELOG_KIND_MAP ),
143            '$pageChangeKind',
144            "Unsupported pageChangeKind '$pageChangeKind'.  Must be one of " .
145            implode( ',', array_keys( self::PAGE_CHANGE_KIND_TO_CHANGELOG_KIND_MAP ) )
146        );
147
148        return self::PAGE_CHANGE_KIND_TO_CHANGELOG_KIND_MAP[$pageChangeKind];
149    }
150
151    /**
152     * Return the page's wikiId, or if that returns false,
153     * return WikiMap::getCurrentWikiId.
154     *
155     * @param ProperPageIdentity $page
156     * @return string
157     */
158    private static function getWikiId( ProperPageIdentity $page ): string {
159        // Get the wikiId.  page's getWikiId can return false.
160        // Fallback to global WikiMap.
161        return $page->getWikiId() ?: WikiMap::getCurrentWikiId();
162    }
163
164    /**
165     * DRY helper to set event fields common to all page change events.
166     * @param string $page_change_kind
167     * @param string $dt
168     * @param ProperPageIdentity $page
169     * @param UserIdentity|null $performer
170     * @param RevisionRecord|null $currentRevision
171     * @param PageLink|null $redirectTarget
172     * @param string|null $comment
173     * @return array
174     */
175    private function toCommonAttrs(
176        string $page_change_kind,
177        string $dt,
178        ProperPageIdentity $page,
179        ?UserIdentity $performer,
180        ?RevisionRecord $currentRevision = null,
181        ?PageLink $redirectTarget = null,
182        ?string $comment = null
183    ): array {
184        $eventAttrs = [
185            'changelog_kind' => self::getChangelogKind( $page_change_kind ),
186            'page_change_kind' => $page_change_kind,
187            'dt' => $dt,
188            'wiki_id' => self::getWikiId( $page ),
189            'page' => $this->toPageAttrs( $page ),
190        ];
191
192        if ( $redirectTarget !== null ) {
193            $eventAttrs['page']['redirect_page_link'] = $this->toPageLinkAttrs( $redirectTarget );
194        }
195
196        if ( $performer !== null ) {
197            $eventAttrs['performer'] = $this->toUserAttrs( $performer );
198        }
199
200        if ( $comment !== null ) {
201            $eventAttrs['comment'] = $comment;
202        }
203
204        if ( $currentRevision !== null ) {
205            $eventAttrs['revision'] = $this->toRevisionAttrs( $currentRevision );
206        }
207
208        return $eventAttrs;
209    }
210
211    /**
212     * DRY helper to serialize the a page entity for page_change events.
213     *
214     * wikibase_item_id, wikibase_wiki_id and wikibase_concept_uri are set here
215     * rather than by PageEntitySerializer because they are fields of the
216     * page_change schema, not of the reusable page entity fragment: resolving
217     * them needs the optional Wikibase Client extension.
218     * See https://phabricator.wikimedia.org/T428176
219     *
220     * NOTE: Wikibase Client writes the wikibase_item page property in the
221     * deferred LinksUpdate that runs after page change events are dispatched, so
222     * on page create the property is usually not set yet.
223     */
224    private function toPageAttrs( ProperPageIdentity $page ): array {
225        $pageAttrs = $this->pageEntitySerializer->toArray( $page, self::PAGE_ENTITY_SCHEMA_VERSION );
226
227        $wikibaseItemId = $this->wikibaseItemLookup->getWikibaseItemIdForPage( $page );
228        if ( $wikibaseItemId !== null ) {
229            $pageAttrs['wikibase_item_id'] = $wikibaseItemId;
230        }
231
232        // Null whenever wikibase_item_id is null, so this never sets
233        // wikibase_wiki_id on its own.
234        $wikibaseWikiId = $this->wikibaseItemLookup->getWikibaseWikiIdForPage( $page );
235        if ( $wikibaseWikiId !== null ) {
236            $pageAttrs['wikibase_wiki_id'] = $wikibaseWikiId;
237        }
238
239        // Likewise null whenever wikibase_item_id is null.
240        $wikibaseConceptUri = $this->wikibaseItemLookup->getWikibaseConceptUriForPage( $page );
241        if ( $wikibaseConceptUri !== null ) {
242            $pageAttrs['wikibase_concept_uri'] = $wikibaseConceptUri;
243        }
244
245        return $pageAttrs;
246    }
247
248    /**
249     * DRY helper to serialize a page link entity in page_change events.
250     *
251     * wikibase_item_id, wikibase_wiki_id and wikibase_concept_uri are set here
252     * for the same reason as in toPageAttrs().
253     */
254    private function toPageLinkAttrs( PageLink $pageLink ): array {
255        $pageLinkAttrs = $this->pageLinkEntitySerializer->toArray(
256            $pageLink,
257            self::PAGE_LINK_ENTITY_SCHEMA_VERSION
258        );
259
260        $wikibaseItemId = $this->wikibaseItemLookup->getWikibaseItemIdForLinkTarget(
261            $pageLink->link
262        );
263        if ( $wikibaseItemId !== null ) {
264            $pageLinkAttrs['wikibase_item_id'] = $wikibaseItemId;
265        }
266
267        $wikibaseWikiId = $this->wikibaseItemLookup->getWikibaseWikiIdForLinkTarget(
268            $pageLink->link
269        );
270        if ( $wikibaseWikiId !== null ) {
271            $pageLinkAttrs['wikibase_wiki_id'] = $wikibaseWikiId;
272        }
273
274        $wikibaseConceptUri = $this->wikibaseItemLookup->getWikibaseConceptUriForLinkTarget(
275            $pageLink->link
276        );
277        if ( $wikibaseConceptUri !== null ) {
278            $pageLinkAttrs['wikibase_concept_uri'] = $wikibaseConceptUri;
279        }
280
281        return $pageLinkAttrs;
282    }
283
284    /**
285     * DRY helper to serialize a user entity for page_change events.
286     *
287     * edit_global_count is set here rather than by UserEntitySerializer because
288     * it is a field of the page_change schema, not of the reusable user entity
289     * fragment: resolving it needs the optional CentralAuth extension.
290     * See https://phabricator.wikimedia.org/T432050
291     */
292    private function toUserAttrs( UserIdentity $user ): array {
293        $userAttrs = $this->userEntitySerializer->toArray( $user, self::USER_ENTITY_SCHEMA_VERSION );
294
295        if ( isset( $userAttrs['user_central_id'] ) ) {
296            $globalEditCount = $this->globalEditCountLookup->getGlobalEditCount(
297                $userAttrs['user_central_id']
298            );
299            if ( $globalEditCount !== null ) {
300                $userAttrs['edit_global_count'] = $globalEditCount;
301            }
302        }
303
304        return $userAttrs;
305    }
306
307    /**
308     * Since mediawiki/page/change 1.3.1, editor is no longer a field of the revision entity schema.
309     * It is added to revision fields in page change schema instead.
310     * So, we DRY setting revision and revision.editor here.
311     * This allows us to control the user entity schema version used for serializing the editor here.
312     */
313    private function toRevisionAttrs( RevisionRecord $revisionRecord ): array {
314        $revisionAttrs = $this->revisionEntitySerializer->toArray(
315            $revisionRecord,
316            self::REVISION_ENTITY_SCHEMA_VERSION,
317        );
318
319        // Add revision.editor
320        if ( $revisionRecord->getUser() ) {
321            $revisionAttrs['editor'] = $this->toUserAttrs( $revisionRecord->getUser() );
322        }
323
324        // Add revision.content_slots as long as slots are not empty.
325        // Note that this DOES NOT include actual content bodies,
326        // just metadata about the content in each slot role.
327        $slotsAttrs = $this->revisionSlotsEntitySerializer->toArray(
328            $revisionRecord->getSlots(),
329            self::REVISION_SLOTS_ENTITY_SCHEMA_VERSION
330        );
331        if ( $slotsAttrs ) {
332            $revisionAttrs['content_slots'] = $slotsAttrs;
333        }
334        return $revisionAttrs;
335    }
336
337    /**
338     * Converts from the given page and RevisionRecord to a page_change_kind: create event.
339     *
340     * @param string $stream
341     * @param ProperPageIdentity $page
342     * @param UserIdentity $performer
343     * @param RevisionRecord $currentRevision
344     * @param PageLink|null $redirectTarget
345     * @return array
346     */
347    public function toCreateEvent(
348        string $stream,
349        ProperPageIdentity $page,
350        UserIdentity $performer,
351        RevisionRecord $currentRevision,
352        ?PageLink $redirectTarget = null
353    ): array {
354        $eventAttrs = $this->toCommonAttrs(
355            'create',
356            $this->eventSerializer->timestampToDt( $currentRevision->getTimestamp() ),
357            $page,
358            $performer,
359            $currentRevision,
360            $redirectTarget,
361            null
362        );
363
364        return $this->toEvent( $stream, $page, $eventAttrs );
365    }
366
367    /**
368     * Converts from the given page and RevisionRecord to a page_change_kind: edit event.
369     *
370     * @param string $stream
371     * @param ProperPageIdentity $page
372     * @param UserIdentity $performer
373     * @param RevisionRecord $currentRevision
374     * @param PageLink|null $redirectTarget
375     * @param RevisionRecord|null $parentRevision
376     * @param EditResult|null $editResult
377     * @return array
378     */
379    public function toEditEvent(
380        string $stream,
381        ProperPageIdentity $page,
382        UserIdentity $performer,
383        RevisionRecord $currentRevision,
384        ?PageLink $redirectTarget = null,
385        ?RevisionRecord $parentRevision = null,
386        ?EditResult $editResult = null
387    ): array {
388        $eventAttrs = $this->toCommonAttrs(
389            'edit',
390            $this->eventSerializer->timestampToDt( $currentRevision->getTimestamp() ),
391            $page,
392            $performer,
393            $currentRevision,
394            $redirectTarget,
395            null
396        );
397
398        // On edit, the prior state is all about the previous revision.
399        if ( $parentRevision !== null ) {
400            $eventAttrs['prior_state'] = [
401                'revision' => $this->toRevisionAttrs( $parentRevision ),
402            ];
403        }
404
405        // If EditResult says the edit was a revert, then add revision.revert details.
406        // https://phabricator.wikimedia.org/T423583
407        if ( $editResult !== null && $editResult->isRevert() ) {
408            $revertAttrs = $this->toRevertAttrs( $editResult );
409            if ( $revertAttrs !== null ) {
410                $eventAttrs['revision']['revert'] = $revertAttrs;
411            }
412        }
413
414        return $this->toEvent( $stream, $page, $eventAttrs );
415    }
416
417    /**
418     * Builds revision.revert attributes from EditResult.
419     * revision.revert was added in mediawiki/page/change 1.4.0.
420     *
421     * @param EditResult $editResult
422     * @return array|null Keyed payload or null if not a revert.
423     * @throws UnexpectedValueException If EditResult reports an unknown revert method.
424     */
425    private function toRevertAttrs( EditResult $editResult ): ?array {
426        if ( !$editResult->isRevert() ) {
427            return null;
428        }
429
430        $revertAttrs = [];
431
432        // If revertMethod is set, then set it as a string name in revert.method.
433        $revertMethod = $editResult->getRevertMethod();
434        if ( $revertMethod !== null ) {
435            switch ( $revertMethod ) {
436                case EditResult::REVERT_ROLLBACK:
437                    $revertAttrs['method'] = 'rollback';
438                    break;
439                case EditResult::REVERT_UNDO:
440                    $revertAttrs['method'] = 'undo';
441                    break;
442                case EditResult::REVERT_MANUAL:
443                    $revertAttrs['method'] = 'manual';
444                    break;
445                default:
446                    // This shouldn't happen.
447                    throw new UnexpectedValueException( "Unexpected revert method $revertMethod." );
448            }
449        }
450
451        $revertAttrs['is_exact'] = $editResult->isExactRevert();
452
453        $originalRevId = $editResult->getOriginalRevisionId();
454        if ( is_int( $originalRevId ) ) {
455            $revertAttrs['rev_original_id'] = $originalRevId;
456            $originalRev = $this->revisionStore->getRevisionById( $originalRevId );
457            if ( $originalRev !== null ) {
458                $revertAttrs['rev_original_dt'] = $this->eventSerializer->timestampToDt(
459                    $originalRev->getTimestamp()
460                );
461            }
462        }
463
464        // EditResult has the oldest and newest revision ids that were reverted
465        // by this revert. These might be useful for calcuting the
466        // full range of reverted revisions later.
467        $oldestRevertedRevId = $editResult->getOldestRevertedRevisionId();
468        if ( $oldestRevertedRevId !== null ) {
469            $revertAttrs['rev_reverted_oldest_id'] = $oldestRevertedRevId;
470        }
471        $newestRevertedRevId = $editResult->getNewestRevertedRevisionId();
472        if ( $newestRevertedRevId !== null ) {
473            $revertAttrs['rev_reverted_newest_id'] = $newestRevertedRevId;
474        }
475
476        return $revertAttrs;
477    }
478
479    /**
480     * Converts from the given page, RevisionRecord
481     * and old title ProperPageIdentity to a page_change_kind: move event.
482     *
483     * @param string $stream
484     * @param ProperPageIdentity $page
485     * @param UserIdentity $performer
486     * @param RevisionRecord $currentRevision
487     * @param RevisionRecord $parentRevision
488     * @param ProperPageIdentity $oldTitle Page identity at the title/namespace before the move
489     * @param string $reason
490     * @param ProperPageIdentity|null $createdRedirectWikiPage
491     * @param PageLink|null $redirectTarget
492     * @return array
493     */
494    public function toMoveEvent(
495        string $stream,
496        ProperPageIdentity $page,
497        UserIdentity $performer,
498        RevisionRecord $currentRevision,
499        RevisionRecord $parentRevision,
500        ProperPageIdentity $oldTitle,
501        string $reason,
502        ?ProperPageIdentity $createdRedirectWikiPage = null,
503        ?PageLink $redirectTarget = null
504    ): array {
505        $eventAttrs = $this->toCommonAttrs(
506            'move',
507            // NOTE: This uses the newly created revision's timestamp as the page move event time,
508            // for lack of a better 'move time'.
509            $this->eventSerializer->timestampToDt( $currentRevision->getTimestamp() ),
510            $page,
511            $performer,
512            $currentRevision,
513            $redirectTarget,
514            // NOTE: the reason for the page move is used to generate the comment
515            // on the revision created by the page move, but it is not the same!
516            $reason
517        );
518
519        // If a new redirect page was created during this move, then include
520        // some information about it.
521        if ( $createdRedirectWikiPage ) {
522            $eventAttrs['created_redirect_page'] = $this->pageEntitySerializer
523                ->toArray( $createdRedirectWikiPage, self::PAGE_ENTITY_SCHEMA_VERSION );
524        }
525
526        // On move, prior_state.page lists only page entity fields that differ from the current page;
527        // prior_state.revision is the revision before the move (a move creates a new revision).
528        $priorStateAttrs = [
529            // Only keep fields that differ from the current page.
530            'page' => array_diff_assoc(
531                $this->pageEntitySerializer->toArray( $oldTitle, self::PAGE_ENTITY_SCHEMA_VERSION ),
532                $eventAttrs['page']
533            ),
534            // add parent revision info in prior_state, since a page move creates a new revision.
535            'revision' => $this->toRevisionAttrs( $parentRevision ),
536        ];
537
538        $eventAttrs['prior_state'] = $priorStateAttrs;
539
540        return $this->toEvent( $stream, $page, $eventAttrs );
541    }
542
543    /**
544     * Converts from the given page, RevisionRecord to a page_change_kind: delete event.
545     *
546     * NOTE: If $isSuppression is true, the current revision info emitted by this even will have
547     * all of its visibility settings set to false.
548     * A consumer of this event probably doesn't care, because they should delete the page
549     * and revision in response to this event anyway.
550     *
551     * @param string $stream
552     * @param ProperPageIdentity $page
553     * @param UserIdentity|null $performer
554     * @param RevisionRecord $currentRevision
555     * @param string $reason
556     * @param string|null $eventTimestamp
557     * @param int|null $archivedRevisionCount
558     * @param PageLink|null $redirectTarget
559     * @param bool $isSuppression
560     *  If true, the current revision info emitted by this even will have
561     *  all of its visibility settings set to false.
562     *  A consumer of this event probably doesn't care, because they should delete the page
563     *  and revision in response to this event anyway.
564     * @return array
565     */
566    public function toDeleteEvent(
567        string $stream,
568        ProperPageIdentity $page,
569        ?UserIdentity $performer,
570        RevisionRecord $currentRevision,
571        string $reason,
572        ?string $eventTimestamp = null,
573        ?int $archivedRevisionCount = null,
574        ?PageLink $redirectTarget = null,
575        bool $isSuppression = false
576    ): array {
577        $eventAttrs = $this->toCommonAttrs(
578            'delete',
579            $this->eventSerializer->timestampToDt( $eventTimestamp ),
580            $page,
581            $performer,
582            $currentRevision,
583            $redirectTarget,
584            $reason
585        );
586
587        // page delete specific fields:
588        if ( $archivedRevisionCount !== null ) {
589            $eventAttrs['page']['revision_count'] = $archivedRevisionCount;
590        }
591
592        // If this is a full page suppression, then we need to represent that fact that
593        // the current revision (and also all revisions of this page) is having its visibility changed
594        // to fully hidden, AKA SUPPRESSED_ALL, and delete any fields that might contain information
595        // that has been suppressed.
596        // NOTE: It would be better if $currentRevision itself had its visibility settings
597        // set to the same as the 'deleted/archived' revision, but it is not because
598        // MediaWiki is pretty weird with archived revisions.
599        // See: https://phabricator.wikimedia.org/T308017#8339347
600        if ( $isSuppression ) {
601            $eventAttrs['revision'] = array_merge(
602                $eventAttrs['revision'],
603                $this->revisionEntitySerializer->bitsToVisibilityAttrs( RevisionRecord::SUPPRESSED_ALL )
604            );
605
606            unset( $eventAttrs['revision']['rev_size'] );
607            unset( $eventAttrs['revision']['rev_sha1'] );
608            unset( $eventAttrs['revision']['comment'] );
609            unset( $eventAttrs['revision']['editor'] );
610            unset( $eventAttrs['revision']['content_slots'] );
611
612            // $currentRevision actually has the prior revision visibility info in the case of page suppression.
613            $eventAttrs['prior_state']['revision'] = $this->revisionEntitySerializer->bitsToVisibilityAttrs(
614                $currentRevision->getVisibility()
615            );
616        }
617
618        return $this->toEvent( $stream, $page, $eventAttrs );
619    }
620
621    /**
622     * Converts from the given page, RevisionRecord to a page_change_kind: undelete event.
623     *
624     * @param string $stream
625     * @param ProperPageIdentity $page
626     * @param UserIdentity $performer
627     * @param RevisionRecord $currentRevision
628     * @param string $reason
629     * @param PageLink|null $redirectTarget
630     * @param string|null $eventTimestamp
631     * @param int|null $oldPageID
632     * @return array
633     */
634    public function toUndeleteEvent(
635        string $stream,
636        ProperPageIdentity $page,
637        UserIdentity $performer,
638        RevisionRecord $currentRevision,
639        string $reason,
640        ?PageLink $redirectTarget = null,
641        ?string $eventTimestamp = null,
642        ?int $oldPageID = null
643    ): array {
644        $eventAttrs = $this->toCommonAttrs(
645            'undelete',
646            $this->eventSerializer->timestampToDt( $eventTimestamp ),
647            $page,
648            $performer,
649            $currentRevision,
650            $redirectTarget,
651            $reason
652        );
653
654        // If this page had a different id in the archive table,
655        // then save it as the prior_state page_id.  This will
656        // be the page_id that the page had before it was deleted,
657        // which is the same as the page_id that it had while it was
658        // in the archive table.
659        // Usually page_id will be the same, but there are some historical
660        // edge cases where a new page_id is created as part of an undelete.
661        if ( $oldPageID && $oldPageID != $page->getId() ) {
662            $eventAttrs['prior_state'] = [
663                'page' => [
664                    'page_id' => $oldPageID
665                ]
666            ];
667        }
668
669        return $this->toEvent( $stream, $page, $eventAttrs );
670    }
671
672    /**
673     * Converts from the given page, RevisionRecord and previous RevisionRecord's visibility (deleted)
674     * bitfield to a page_change_kind: visibility_change event.
675     *
676     * @param string $stream
677     * @param ProperPageIdentity $page
678     * @param UserIdentity|null $performer
679     * @param RevisionRecord $currentRevision
680     * @param int $priorVisibilityBitfield
681     * @param string|null $eventTimestamp
682     * @return array
683     */
684    public function toVisibilityChangeEvent(
685        string $stream,
686        ProperPageIdentity $page,
687        ?UserIdentity $performer,
688        RevisionRecord $currentRevision,
689        int $priorVisibilityBitfield,
690        ?string $eventTimestamp = null
691    ) {
692        $eventAttrs = $this->toCommonAttrs(
693            'visibility_change',
694            $this->eventSerializer->timestampToDt( $eventTimestamp ),
695            $page,
696            $performer,
697            $currentRevision,
698            # NOTE: ArticleRevisionVisibilitySet does not give us the 'reason' (comment)
699            # the visibility has been changed.  This info is provided in the UI by the user,
700            # where does it go?
701            # https://phabricator.wikimedia.org/T321411
702            null
703        );
704
705        // During a visibility change, we are only representing the change to the revision's
706        // visibility. The rev_id that is being modified is at revision.rev_id.
707        // The rev_id has not changed. The prior_state.revision object will not contain
708        // any duplicate information about this revision. It will only contain the
709        // prior visibility fields for this revision that have been changed
710        $priorVisibilityFields = $this->revisionEntitySerializer->bitsToVisibilityAttrs( $priorVisibilityBitfield );
711        $eventAttrs['prior_state']['revision'] = [];
712        foreach ( $priorVisibilityFields as $key => $value ) {
713            // Only set the old visibility field in prior state if it has changed.
714            if ( $eventAttrs['revision'][$key] !== $value ) {
715                $eventAttrs['prior_state']['revision'][$key] = $value;
716            }
717        }
718
719        return $this->toEvent( $stream, $page, $eventAttrs );
720    }
721}