Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
48.48% covered (danger)
48.48%
112 / 231
16.67% covered (danger)
16.67%
2 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
EventDispatcher
48.48% covered (danger)
48.48%
112 / 231
16.67% covered (danger)
16.67%
2 / 12
801.54
0.00% covered (danger)
0.00%
0 / 1
 setAutosubscribe
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getParsedRevision
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 generateEventsForRevision
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 groupCommentsByThreadAndName
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
9
 groupSubscribableHeadings
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 findAddedItems
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
8.23
 generateEventsFromItemSets
84.54% covered (warning)
84.54%
82 / 97
0.00% covered (danger)
0.00%
0 / 1
21.48
 addCommentChangeTag
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 addAutoSubscription
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 locateSubscribedUsers
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 logAddedComments
7.41% covered (danger)
7.41%
4 / 54
0.00% covered (danger)
0.00%
0 / 1
246.42
 inEventSample
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * DiscussionTools event dispatcher
4 *
5 * @file
6 * @ingroup Extensions
7 * @license MIT
8 */
9
10namespace MediaWiki\Extension\DiscussionTools\Notifications;
11
12use DateInterval;
13use DateTimeImmutable;
14use DateTimeZone;
15use Iterator;
16use MediaWiki\Context\RequestContext;
17use MediaWiki\Deferred\DeferredUpdates;
18use MediaWiki\Extension\DiscussionTools\CommentUtils;
19use MediaWiki\Extension\DiscussionTools\ContentThreadItemSet;
20use MediaWiki\Extension\DiscussionTools\Hooks\HookUtils;
21use MediaWiki\Extension\DiscussionTools\SubscriptionItem;
22use MediaWiki\Extension\DiscussionTools\SubscriptionStore;
23use MediaWiki\Extension\DiscussionTools\ThreadItem\CommentItem;
24use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
25use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentHeadingItem;
26use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
27use MediaWiki\Extension\DiscussionTools\ThreadItem\HeadingItem;
28use MediaWiki\Extension\EventLogging\EventLogging;
29use MediaWiki\Extension\EventLogging\Libs\UserBucketProvider\UserBucketProvider;
30use MediaWiki\Extension\Notifications\Model\Event;
31use MediaWiki\MediaWikiServices;
32use MediaWiki\Page\PageIdentity;
33use MediaWiki\Registration\ExtensionRegistry;
34use MediaWiki\Revision\RevisionRecord;
35use MediaWiki\Title\Title;
36use MediaWiki\User\UserIdentity;
37use Wikimedia\Assert\Assert;
38use Wikimedia\Parsoid\Core\DOMCompat;
39use Wikimedia\Parsoid\Ext\DOMUtils;
40use Wikimedia\Rdbms\IDBAccessObject;
41
42class EventDispatcher {
43    protected static string $autosubscribe = 'preferences';
44
45    /**
46     * Set the autosubscribe preference from an API call
47     */
48    public static function setAutosubscribe( string $autosubscribe ): void {
49        self::$autosubscribe = $autosubscribe;
50    }
51
52    private static function getParsedRevision( RevisionRecord $revRecord ): ContentThreadItemSet {
53        return HookUtils::parseRevisionParsoidHtml( $revRecord, __METHOD__ )->getValueOrThrow();
54    }
55
56    public static function generateEventsForRevision( array &$events, RevisionRecord $newRevRecord ): void {
57        $services = MediaWikiServices::getInstance();
58
59        $title = Title::newFromPageIdentity( $newRevRecord->getPage() );
60        if ( !HookUtils::isAvailableForTitle( $title ) ) {
61            // Not a talk page
62            return;
63        }
64
65        $user = $newRevRecord->getUser();
66        if ( !$user ) {
67            // User can be null if the user is deleted, but this is unlikely
68            // to be the case if the user just made an edit
69            return;
70        }
71
72        $revisionStore = $services->getRevisionStore();
73        $oldRevRecord = $revisionStore->getPreviousRevision( $newRevRecord, IDBAccessObject::READ_LATEST );
74
75        if ( $oldRevRecord !== null ) {
76            $oldItemSet = static::getParsedRevision( $oldRevRecord );
77        } else {
78            // Page creation
79            $doc = DOMUtils::parseHTML( '' );
80            $container = DOMCompat::getBody( $doc );
81            $oldItemSet = $services->getService( 'DiscussionTools.CommentParser' )
82                ->parse( $container, $title->getTitleValue() );
83        }
84        $newItemSet = static::getParsedRevision( $newRevRecord );
85
86        static::generateEventsFromItemSets( $events, $oldItemSet, $newItemSet, $newRevRecord, $title, $user );
87    }
88
89    /**
90     * For each level 2 heading, get a list of comments in the thread grouped by names, then IDs.
91     * (Compare by name first, as ID could be changed by a parent comment being moved/deleted.)
92     * Comments in level 3+ sub-threads are grouped together with the parent thread.
93     *
94     * For any other headings (including level 3+ before the first level 2 heading, level 1, and
95     * section zero placeholder headings), ignore comments in those threads.
96     *
97     * @param ContentThreadItem[] $items
98     * @return ContentCommentItem[][][]
99     */
100    private static function groupCommentsByThreadAndName( array $items ): array {
101        $comments = [];
102        $threadName = null;
103        foreach ( $items as $item ) {
104            if ( $item instanceof HeadingItem && ( $item->getHeadingLevel() < 2 || $item->isPlaceholderHeading() ) ) {
105                $threadName = null;
106            } elseif ( $item instanceof HeadingItem && $item->getHeadingLevel() === 2 ) {
107                $threadName = $item->getName();
108            } elseif ( $item instanceof CommentItem && $threadName !== null ) {
109                $comments[ $threadName ][ $item->getName() ][ $item->getId() ] = $item;
110            }
111        }
112        return $comments;
113    }
114
115    /**
116     * Get a list of all subscribable headings, grouped by name in case there are duplicates.
117     *
118     * @param ContentHeadingItem[] $items
119     * @return ContentHeadingItem[][]
120     */
121    private static function groupSubscribableHeadings( array $items ): array {
122        $headings = [];
123        foreach ( $items as $item ) {
124            if ( $item->isSubscribable() ) {
125                $headings[ $item->getName() ][ $item->getId() ] = $item;
126            }
127        }
128        return $headings;
129    }
130
131    /**
132     * Compare two lists of thread items, return those in $new but not $old.
133     *
134     * @param ContentThreadItem[][] $old
135     * @param ContentThreadItem[][] $new
136     * @return iterable<ContentThreadItem>
137     */
138    private static function findAddedItems( array $old, array $new ) {
139        foreach ( $new as $itemName => $nameNewItems ) {
140            // Usually, there will be 0 or 1 $nameNewItems, and 0 $nameOldItems,
141            // and $addedCount will be 0 or 1.
142            //
143            // But when multiple replies are added in one edit, or in multiple edits within the same
144            // minute, there may be more, and the complex logic below tries to make the best guess
145            // as to which items are actually new. See the 'multiple' and 'sametime' test cases.
146            //
147            $nameOldItems = $old[ $itemName ] ?? [];
148            $addedCount = count( $nameNewItems ) - count( $nameOldItems );
149
150            if ( $addedCount > 0 ) {
151                // For any name that occurs more times in new than old, report that many new items,
152                // preferring IDs that did not occur in old, then preferring items lower on the page.
153                foreach ( array_reverse( $nameNewItems ) as $itemId => $newItem ) {
154                    if ( $addedCount > 0 && !isset( $nameOldItems[ $itemId ] ) ) {
155                        yield $newItem;
156                        $addedCount--;
157                    }
158                }
159                foreach ( array_reverse( $nameNewItems ) as $itemId => $newItem ) {
160                    if ( $addedCount > 0 ) {
161                        yield $newItem;
162                        $addedCount--;
163                    }
164                }
165                Assert::postcondition( $addedCount === 0, 'Reported expected number of items' );
166            }
167        }
168    }
169
170    /**
171     * Helper for generateEventsForRevision(), separated out for easier testing.
172     */
173    protected static function generateEventsFromItemSets(
174        array &$events,
175        ContentThreadItemSet $oldItemSet,
176        ContentThreadItemSet $newItemSet,
177        RevisionRecord $newRevRecord,
178        PageIdentity $title,
179        UserIdentity $user
180    ): void {
181        $newComments = static::groupCommentsByThreadAndName( $newItemSet->getThreadItems() );
182        $oldComments = static::groupCommentsByThreadAndName( $oldItemSet->getThreadItems() );
183        $addedComments = [];
184        foreach ( $newComments as $threadName => $threadNewComments ) {
185            $threadOldComments = $oldComments[ $threadName ] ?? [];
186            foreach ( static::findAddedItems( $threadOldComments, $threadNewComments ) as $newComment ) {
187                Assert::precondition( $newComment instanceof ContentCommentItem, 'Must be ContentCommentItem' );
188                $addedComments[] = $newComment;
189            }
190        }
191
192        $newHeadings = static::groupSubscribableHeadings( $newItemSet->getThreads() );
193        $oldHeadings = static::groupSubscribableHeadings( $oldItemSet->getThreads() );
194
195        $addedHeadings = [];
196        foreach ( static::findAddedItems( $oldHeadings, $newHeadings ) as $newHeading ) {
197            Assert::precondition( $newHeading instanceof ContentHeadingItem, 'Must be ContentHeadingItem' );
198            $addedHeadings[] = $newHeading;
199        }
200
201        $removedHeadings = [];
202        // Pass swapped parameters to findAddedItems() to find *removed* items
203        foreach ( static::findAddedItems( $newHeadings, $oldHeadings ) as $oldHeading ) {
204            Assert::precondition( $oldHeading instanceof ContentHeadingItem, 'Must be ContentHeadingItem' );
205            $removedHeadings[] = $oldHeading;
206        }
207
208        $mentionedUsers = [];
209        foreach ( $events as &$event ) {
210            if ( $event['type'] === 'mention' || $event['type'] === 'mention-summary' ) {
211                // Save mentioned users in our events, so that we can exclude them from our notification,
212                // to avoid duplicate notifications for a single comment.
213                // Array is keyed by user id so we can do a simple array merge.
214                $mentionedUsers += $event['extra']['mentioned-users'];
215            }
216
217            if ( count( $addedComments ) === 1 ) {
218                // If this edit was a new user talk message according to Echo,
219                // and we also found exactly one new comment,
220                // add some extra information to the edit-user-talk event.
221                if ( $event['type'] === 'edit-user-talk' ) {
222                    $event['extra'] += [
223                        'comment-id' => $addedComments[0]->getId(),
224                        'comment-name' => $addedComments[0]->getName(),
225                        'content' => $addedComments[0]->getBodyText( true ),
226                    ];
227                }
228
229                // Similarly for mentions.
230                // We don't handle 'content' in this case, as Echo makes its own snippets.
231                if ( $event['type'] === 'mention' ) {
232                    $event['extra'] += [
233                        'comment-id' => $addedComments[0]->getId(),
234                        'comment-name' => $addedComments[0]->getName(),
235                    ];
236                }
237            }
238        }
239
240        if ( $addedComments ) {
241            // It's a bit weird to do this here, in the middle of the hook handler for Echo. However:
242            // * Echo calls this from a PageSaveComplete hook handler as a DeferredUpdate,
243            //   which is exactly how we would do this otherwise
244            // * It allows us to reuse the generated comment trees without any annoying caching
245            static::addCommentChangeTag( $newRevRecord );
246            // For very similar reasons, we do logging here
247            static::logAddedComments( $addedComments, $newRevRecord, $title, $user );
248        }
249
250        foreach ( $addedComments as $newComment ) {
251            // Ignore comments by other users, e.g. in case of reverts or a discussion being moved.
252            // TODO: But what about someone signing another's comment?
253            if ( $newComment->getAuthor() !== $user->getName() ) {
254                continue;
255            }
256            // Ignore comments which are more than 10 minutes old, as this may be a user archiving
257            // their own comment. (T290803)
258            $revTimestamp = new DateTimeImmutable( $newRevRecord->getTimestamp(), new DateTimeZone( 'UTC' ) );
259            $threshold = $revTimestamp->sub( new DateInterval( 'PT10M' ) );
260            if ( $newComment->getTimestamp() <= $threshold ) {
261                continue;
262            }
263            $heading = $newComment->getSubscribableHeading();
264            if ( !$heading ) {
265                continue;
266            }
267            $events[] = [
268                // This probably should've been called "dt-new-comment": this code is
269                // unaware if there are any subscriptions to the containing topic and
270                // an event is generated for every comment posted.
271                // However, changing this would require a complex migration.
272                'type' => 'dt-subscribed-new-comment',
273                'title' => $title,
274                'extra' => [
275                    'subscribed-comment-name' => $heading->getName(),
276                    'comment-id' => $newComment->getId(),
277                    'comment-name' => $newComment->getName(),
278                    'content' => $newComment->getBodyText( true ),
279                    'section-title' => $heading->getLinkableTitle(),
280                    'revid' => $newRevRecord->getId(),
281                    'mentioned-users' => $mentionedUsers,
282                ],
283                'agent' => $user,
284            ];
285
286            $titleForSubscriptions = Title::castFromPageIdentity( $title )->createFragmentTarget( $heading->getText() );
287            static::addAutoSubscription( $user, $titleForSubscriptions, $heading->getName() );
288        }
289
290        foreach ( $removedHeadings as $oldHeading ) {
291            $events[] = [
292                'type' => 'dt-removed-topic',
293                'title' => $title,
294                'extra' => [
295                    'subscribed-comment-name' => $oldHeading->getName(),
296                    'heading-id' => $oldHeading->getId(),
297                    'heading-name' => $oldHeading->getName(),
298                    'section-title' => $oldHeading->getLinkableTitle(),
299                    'revid' => $newRevRecord->getId(),
300                ],
301                'agent' => $user,
302            ];
303        }
304
305        $titleObj = Title::castFromPageIdentity( $title );
306        if ( $titleObj ) {
307            foreach ( $addedHeadings as $newHeading ) {
308                // Don't use $event here as that already exists as a reference from above
309                $addTopicEvent = [
310                    'type' => 'dt-added-topic',
311                    'title' => $title,
312                    'extra' => [
313                        // As no one can be subscribed to a topic before it has been created,
314                        // we will notify users who have subscribed to the whole page.
315                        'subscribed-comment-name' => CommentUtils::getNewTopicsSubscriptionId( $titleObj ),
316                        'heading-id' => $newHeading->getId(),
317                        'heading-name' => $newHeading->getName(),
318                        'section-title' => $newHeading->getLinkableTitle(),
319                        'revid' => $newRevRecord->getId(),
320                    ],
321                    'agent' => $user,
322                ];
323                // Add metadata about the accompanying comment
324                $firstComment = $newHeading->getOldestReply();
325                if ( $firstComment ) {
326                    $addTopicEvent['extra']['comment-id'] = $firstComment->getId();
327                    $addTopicEvent['extra']['comment-name'] = $firstComment->getName();
328                    $addTopicEvent['extra']['content'] = $firstComment->getBodyText( true );
329                }
330                $events[] = $addTopicEvent;
331            }
332        }
333    }
334
335    /**
336     * Add our change tag for a revision that adds new comments.
337     */
338    protected static function addCommentChangeTag( RevisionRecord $newRevRecord ): void {
339        // Unclear if DeferredUpdates::addCallableUpdate() is needed,
340        // but every extension does it that way.
341        DeferredUpdates::addCallableUpdate( static function () use ( $newRevRecord ) {
342            MediaWikiServices::getInstance()->getChangeTagsStore()
343                ->addTags( [ 'discussiontools-added-comment' ], null, $newRevRecord->getId() );
344        } );
345    }
346
347    /**
348     * Add an automatic subscription to the given item, assuming the user has automatic subscriptions
349     * enabled.
350     */
351    protected static function addAutoSubscription( UserIdentity $user, Title $title, string $itemName ): void {
352        if (
353            ( self::$autosubscribe === 'preferences' && HookUtils::shouldAddAutoSubscription( $user, $title ) ) ||
354            self::$autosubscribe === 'yes'
355        ) {
356            /** @var SubscriptionStore $subscriptionStore */
357            $subscriptionStore = MediaWikiServices::getInstance()->getService( 'DiscussionTools.SubscriptionStore' );
358            $subscriptionStore->addAutoSubscriptionForUser( $user, $title, $itemName );
359        }
360    }
361
362    /**
363     * Return all users subscribed to a comment
364     *
365     * @param Event $event
366     * @param int $batchSize
367     * @return UserIdentity[]|Iterator<UserIdentity>
368     */
369    public static function locateSubscribedUsers( Event $event, $batchSize = 500 ) {
370        $commentName = $event->getExtraParam( 'subscribed-comment-name' );
371
372        /** @var SubscriptionStore $subscriptionStore */
373        $subscriptionStore = MediaWikiServices::getInstance()->getService( 'DiscussionTools.SubscriptionStore' );
374        $subscriptionItems = $subscriptionStore->getSubscriptionItemsForTopic(
375            $commentName,
376            [ SubscriptionStore::STATE_SUBSCRIBED, SubscriptionStore::STATE_AUTOSUBSCRIBED ]
377        );
378
379        // Update notified timestamps
380        $subscriptionStore->updateSubscriptionNotifiedTimestamp(
381            null,
382            $commentName
383        );
384
385        // TODD: Have this return an Iterator instead?
386        $users = array_map( static function ( SubscriptionItem $item ) {
387            return $item->getUserIdentity();
388        }, $subscriptionItems );
389
390        return $users;
391    }
392
393    /**
394     * Log stuff to EventLogging's Schema:TalkPageEvent
395     * If you don't have EventLogging installed, does nothing.
396     *
397     * @return bool Whether events were logged
398     */
399    protected static function logAddedComments(
400        array $addedComments,
401        RevisionRecord $newRevRecord,
402        PageIdentity $title,
403        UserIdentity $identity
404    ): bool {
405        global $wgDTSchemaEditAttemptStepOversample, $wgDBname;
406        $context = RequestContext::getMain();
407        $request = $context->getRequest();
408        // We've reached here through Echo's post-save deferredupdate, which
409        // might either be after an API request from DiscussionTools or a
410        // regular POST from WikiEditor. Both should have this value snuck
411        // into their request if their session is being logged.
412        if ( !$request->getCheck( 'editingStatsId' ) ) {
413            return false;
414        }
415        $editingStatsId = $request->getVal( 'editingStatsId' );
416        $isDiscussionTools = $request->getCheck( 'dttags' );
417
418        $extensionRegistry = ExtensionRegistry::getInstance();
419        if ( !$extensionRegistry->isLoaded( 'EventLogging' ) ) {
420            return false;
421        }
422        if ( !$extensionRegistry->isLoaded( 'WikimediaEvents' ) ) {
423            return false;
424        }
425        $inSample = static::inEventSample( $editingStatsId );
426        $shouldOversample = ( $isDiscussionTools && $wgDTSchemaEditAttemptStepOversample ) || (
427                // @phan-suppress-next-line PhanUndeclaredClassMethod
428                \WikimediaEvents\WikimediaEventsHooks::shouldSchemaEditAttemptStepOversample( $context )
429            );
430        if ( !$inSample && !$shouldOversample ) {
431            return false;
432        }
433
434        $services = MediaWikiServices::getInstance();
435        $editTracker = $services->getUserEditTracker();
436        $userIdentityUtils = $services->getUserIdentityUtils();
437
438        $commonData = [
439            '$schema' => '/analytics/mediawiki/talk_page_edit/1.2.0',
440            'action' => 'publish',
441            'session_id' => $editingStatsId,
442            'page_id' => $newRevRecord->getPageId(),
443            'page_namespace' => $title->getNamespace(),
444            'revision_id' => $newRevRecord->getId() ?: 0,
445            'performer' => [
446                // Note: we're logging the user who made the edit, not the user who's signed on the comment
447                'user_id' => $identity->getId(),
448                'user_edit_count' => $editTracker->getUserEditCount( $identity ) ?: 0,
449                // Retention-safe values:
450                'user_is_anonymous' => !$identity->isRegistered(),
451                'user_is_temp' => $userIdentityUtils->isTemp( $identity ),
452                'user_edit_count_bucket' => UserBucketProvider::getUserEditCountBucket( $identity ) ?: 'N/A',
453            ],
454            'database' => $wgDBname,
455            // This is unreliable, but sufficient for our purposes; we
456            // mostly just want to see the difference between DT and
457            // everything-else:
458            'integration' => $isDiscussionTools ? 'discussiontools' : 'page',
459        ];
460
461        foreach ( $addedComments as $comment ) {
462            $heading = $comment->getSubscribableHeading();
463            $parent = $comment->getParent();
464            if ( !$heading || !$parent ) {
465                continue;
466            }
467            if ( $parent->getType() === 'heading' ) {
468                if ( count( $heading->getReplies() ) === 1 ) {
469                    // A new heading was added when this comment was created
470                    $component_type = 'topic';
471                } else {
472                    $component_type = 'comment';
473                }
474            } else {
475                $component_type = 'response';
476            }
477            EventLogging::submit( 'mediawiki.talk_page_edit', array_merge( $commonData, [
478                'component_type' => $component_type,
479                'topic_id' => $heading->getId(),
480                'comment_id' => $comment->getId(),
481                'comment_parent_id' => $parent->getId(),
482            ] ) );
483        }
484
485        return true;
486    }
487
488    /**
489     * Should the current session be sampled for EventLogging?
490     *
491     * @return bool Whether to sample the session
492     */
493    protected static function inEventSample( string $sessionId ): bool {
494        global $wgDTSchemaEditAttemptStepSamplingRate, $wgWMESchemaEditAttemptStepSamplingRate;
495        // Sample 6.25%
496        $samplingRate = 0.0625;
497        if ( $wgDTSchemaEditAttemptStepSamplingRate !== null ) {
498            $samplingRate = $wgDTSchemaEditAttemptStepSamplingRate;
499        }
500        if ( $wgWMESchemaEditAttemptStepSamplingRate !== null ) {
501            $samplingRate = $wgWMESchemaEditAttemptStepSamplingRate;
502        }
503        if ( $samplingRate === 0 ) {
504            return false;
505        }
506        $inSample = EventLogging::sessionInSample(
507            (int)( 1 / $samplingRate ), $sessionId
508        );
509        return $inSample;
510    }
511
512}