Debian Codegraph @

extensions/DiscussionTools/includes/Notifications/EventDispatcher.php

raw symbols SCIP
1 <?php
2 /**
3 * DiscussionTools event dispatcher
4 *
5 * @file
6 * @ingroup Extensions
7 * @license MIT
8 */
9
10 namespace MediaWiki\Extension\DiscussionTools\Notifications;
11
12 use DateInterval;
13 use DateTimeImmutable;
14 use DateTimeZone;
15 use Iterator;
16 use MediaWiki\Context\RequestContext;
17 use MediaWiki\Deferred\DeferredUpdates;
18 use MediaWiki\Extension\DiscussionTools\CommentUtils;
19 use MediaWiki\Extension\DiscussionTools\ContentThreadItemSet;
20 use MediaWiki\Extension\DiscussionTools\Hooks\HookUtils;
21 use MediaWiki\Extension\DiscussionTools\SubscriptionItem;
22 use MediaWiki\Extension\DiscussionTools\SubscriptionStore;
23 use MediaWiki\Extension\DiscussionTools\ThreadItem\CommentItem;
24 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
25 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentHeadingItem;
26 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
27 use MediaWiki\Extension\DiscussionTools\ThreadItem\HeadingItem;
28 use MediaWiki\Extension\EventLogging\EventLogging;
29 use MediaWiki\Extension\EventLogging\Libs\UserBucketProvider\UserBucketProvider;
30 use MediaWiki\Extension\Notifications\Model\Event;
31 use MediaWiki\MediaWikiServices;
32 use MediaWiki\Page\PageIdentity;
33 use MediaWiki\Registration\ExtensionRegistry;
34 use MediaWiki\Revision\RevisionRecord;
35 use MediaWiki\Title\Title;
36 use MediaWiki\User\UserIdentity;
37 use Wikimedia\Assert\Assert;
38 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
39 use Wikimedia\Parsoid\Utils\DOMCompat;
40 use Wikimedia\Parsoid\Utils\DOMUtils;
41 use Wikimedia\Rdbms\IDBAccessObject;
42
43 class EventDispatcher {
44 /**
45 * @throws ResourceLimitExceededException
46 */
47 private static function getParsedRevision( RevisionRecord $revRecord ): ContentThreadItemSet {
48 return HookUtils::parseRevisionParsoidHtml( $revRecord, __METHOD__ );
49 }
50
51 /**
52 * @throws ResourceLimitExceededException
53 */
54 public static function generateEventsForRevision( array &$events, RevisionRecord $newRevRecord ): void {
55 $services = MediaWikiServices::getInstance();
56
57 $title = Title::newFromLinkTarget(
58 $newRevRecord->getPageAsLinkTarget()
59 );
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 $dtConfig = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'discussiontools' );
353
354 if (
355 $dtConfig->get( 'DiscussionToolsAutoTopicSubEditor' ) === 'any' &&
356 HookUtils::shouldAddAutoSubscription( $user, $title )
357 ) {
358 /** @var SubscriptionStore $parser */
359 $subscriptionStore = MediaWikiServices::getInstance()->getService( 'DiscussionTools.SubscriptionStore' );
360 $subscriptionStore->addAutoSubscriptionForUser( $user, $title, $itemName );
361 }
362 }
363
364 /**
365 * Return all users subscribed to a comment
366 *
367 * @param Event $event
368 * @param int $batchSize
369 * @return UserIdentity[]|Iterator<UserIdentity>
370 */
371 public static function locateSubscribedUsers( Event $event, $batchSize = 500 ) {
372 $commentName = $event->getExtraParam( 'subscribed-comment-name' );
373
374 /** @var SubscriptionStore $subscriptionStore */
375 $subscriptionStore = MediaWikiServices::getInstance()->getService( 'DiscussionTools.SubscriptionStore' );
376 $subscriptionItems = $subscriptionStore->getSubscriptionItemsForTopic(
377 $commentName,
378 [ SubscriptionStore::STATE_SUBSCRIBED, SubscriptionStore::STATE_AUTOSUBSCRIBED ]
379 );
380
381 // Update notified timestamps
382 $subscriptionStore->updateSubscriptionNotifiedTimestamp(
383 null,
384 $commentName
385 );
386
387 // TODD: Have this return an Iterator instead?
388 $users = array_map( static function ( SubscriptionItem $item ) {
389 return $item->getUserIdentity();
390 }, $subscriptionItems );
391
392 return $users;
393 }
394
395 /**
396 * Log stuff to EventLogging's Schema:TalkPageEvent
397 * If you don't have EventLogging installed, does nothing.
398 *
399 * @param array $addedComments
400 * @param RevisionRecord $newRevRecord
401 * @param PageIdentity $title
402 * @param UserIdentity $identity
403 * @return bool Whether events were logged
404 */
405 protected static function logAddedComments(
406 array $addedComments,
407 RevisionRecord $newRevRecord,
408 PageIdentity $title,
409 UserIdentity $identity
410 ): bool {
411 global $wgDTSchemaEditAttemptStepOversample, $wgDBname;
412 $context = RequestContext::getMain();
413 $request = $context->getRequest();
414 // We've reached here through Echo's post-save deferredupdate, which
415 // might either be after an API request from DiscussionTools or a
416 // regular POST from WikiEditor. Both should have this value snuck
417 // into their request if their session is being logged.
418 if ( !$request->getCheck( 'editingStatsId' ) ) {
419 return false;
420 }
421 $editingStatsId = $request->getVal( 'editingStatsId' );
422 $isDiscussionTools = $request->getCheck( 'dttags' );
423
424 $extensionRegistry = ExtensionRegistry::getInstance();
425 if ( !$extensionRegistry->isLoaded( 'EventLogging' ) ) {
426 return false;
427 }
428 if ( !$extensionRegistry->isLoaded( 'WikimediaEvents' ) ) {
429 return false;
430 }
431 $inSample = static::inEventSample( $editingStatsId );
432 $shouldOversample = ( $isDiscussionTools && $wgDTSchemaEditAttemptStepOversample ) || (
433 // @phan-suppress-next-line PhanUndeclaredClassMethod
434 \WikimediaEvents\WikimediaEventsHooks::shouldSchemaEditAttemptStepOversample( $context )
435 );
436 if ( !$inSample && !$shouldOversample ) {
437 return false;
438 }
439
440 $services = MediaWikiServices::getInstance();
441 $editTracker = $services->getUserEditTracker();
442 $userIdentityUtils = $services->getUserIdentityUtils();
443
444 $commonData = [
445 '$schema' => '/analytics/mediawiki/talk_page_edit/1.2.0',
446 'action' => 'publish',
447 'session_id' => $editingStatsId,
448 'page_id' => $newRevRecord->getPageId(),
449 'page_namespace' => $title->getNamespace(),
450 'revision_id' => $newRevRecord->getId() ?: 0,
451 'performer' => [
452 // Note: we're logging the user who made the edit, not the user who's signed on the comment
453 'user_id' => $identity->getId(),
454 'user_edit_count' => $editTracker->getUserEditCount( $identity ) ?: 0,
455 // Retention-safe values:
456 'user_is_anonymous' => !$identity->isRegistered(),
457 'user_is_temp' => $userIdentityUtils->isTemp( $identity ),
458 'user_edit_count_bucket' => UserBucketProvider::getUserEditCountBucket( $identity ) ?: 'N/A',
459 ],
460 'database' => $wgDBname,
461 // This is unreliable, but sufficient for our purposes; we
462 // mostly just want to see the difference between DT and
463 // everything-else:
464 'integration' => $isDiscussionTools ? 'discussiontools' : 'page',
465 ];
466
467 foreach ( $addedComments as $comment ) {
468 $heading = $comment->getSubscribableHeading();
469 $parent = $comment->getParent();
470 if ( !$heading || !$parent ) {
471 continue;
472 }
473 if ( $parent->getType() === 'heading' ) {
474 if ( count( $heading->getReplies() ) === 1 ) {
475 // A new heading was added when this comment was created
476 $component_type = 'topic';
477 } else {
478 $component_type = 'comment';
479 }
480 } else {
481 $component_type = 'response';
482 }
483 EventLogging::submit( 'mediawiki.talk_page_edit', array_merge( $commonData, [
484 'component_type' => $component_type,
485 'topic_id' => $heading->getId(),
486 'comment_id' => $comment->getId(),
487 'comment_parent_id' => $parent->getId(),
488 ] ) );
489 }
490
491 return true;
492 }
493
494 /**
495 * Should the current session be sampled for EventLogging?
496 *
497 * @param string $sessionId
498 * @return bool Whether to sample the session
499 */
500 protected static function inEventSample( string $sessionId ): bool {
501 global $wgDTSchemaEditAttemptStepSamplingRate, $wgWMESchemaEditAttemptStepSamplingRate;
502 // Sample 6.25%
503 $samplingRate = 0.0625;
504 if ( isset( $wgDTSchemaEditAttemptStepSamplingRate ) ) {
505 $samplingRate = $wgDTSchemaEditAttemptStepSamplingRate;
506 }
507 if ( isset( $wgWMESchemaEditAttemptStepSamplingRate ) ) {
508 $samplingRate = $wgWMESchemaEditAttemptStepSamplingRate;
509 }
510 if ( $samplingRate === 0 ) {
511 return false;
512 }
513 $inSample = EventLogging::sessionInSample(
514 (int)( 1 / $samplingRate ), $sessionId
515 );
516 return $inSample;
517 }
518
519 }