Debian Codegraph @

extensions/Echo/includes/Hooks.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications;
4
5 use EmailNotification;
6 use LogEntry;
7 use LogicException;
8 use MailAddress;
9 use MediaWiki\Api\ApiModuleManager;
10 use MediaWiki\Api\Hook\ApiMain__moduleManagerHook;
11 use MediaWiki\Auth\AuthManager;
12 use MediaWiki\Auth\Hook\LocalUserCreatedHook;
13 use MediaWiki\Config\Config;
14 use MediaWiki\Content\Content;
15 use MediaWiki\DAO\WikiAwareEntity;
16 use MediaWiki\Deferred\DeferredUpdates;
17 use MediaWiki\Deferred\LinksUpdate\LinksTable;
18 use MediaWiki\Deferred\LinksUpdate\LinksUpdate;
19 use MediaWiki\Extension\Notifications\Controller\ModerationController;
20 use MediaWiki\Extension\Notifications\Controller\NotificationController;
21 use MediaWiki\Extension\Notifications\Formatters\EchoEventPresentationModel;
22 use MediaWiki\Extension\Notifications\Hooks\HookRunner;
23 use MediaWiki\Extension\Notifications\Mapper\EventMapper;
24 use MediaWiki\Extension\Notifications\Mapper\NotificationMapper;
25 use MediaWiki\Extension\Notifications\Model\Event;
26 use MediaWiki\Extension\Notifications\Model\Notification;
27 use MediaWiki\Extension\Notifications\Push\Api\ApiEchoPushSubscriptions;
28 use MediaWiki\Hook\AbortTalkPageEmailNotificationHook;
29 use MediaWiki\Hook\EmailUserCompleteHook;
30 use MediaWiki\Hook\GetNewMessagesAlertHook;
31 use MediaWiki\Hook\LinksUpdateCompleteHook;
32 use MediaWiki\Hook\LoginFormValidErrorMessagesHook;
33 use MediaWiki\Hook\PreferencesGetIconHook;
34 use MediaWiki\Hook\RecentChange_saveHook;
35 use MediaWiki\Hook\SendWatchlistEmailNotificationHook;
36 use MediaWiki\Hook\SkinTemplateNavigation__UniversalHook;
37 use MediaWiki\Hook\SpecialMuteModifyFormFieldsHook;
38 use MediaWiki\HookContainer\HookContainer;
39 use MediaWiki\HTMLForm\Field\HTMLCheckMatrix;
40 use MediaWiki\Language\Language;
41 use MediaWiki\Linker\LinkRenderer;
42 use MediaWiki\Logger\LoggerFactory;
43 use MediaWiki\MainConfigNames;
44 use MediaWiki\MediaWikiServices;
45 use MediaWiki\Output\Hook\BeforePageDisplayHook;
46 use MediaWiki\Output\Hook\OutputPageCheckLastModifiedHook;
47 use MediaWiki\Output\OutputPage;
48 use MediaWiki\Page\Hook\ArticleDeleteCompleteHook;
49 use MediaWiki\Page\Hook\ArticleUndeleteHook;
50 use MediaWiki\Page\Hook\RollbackCompleteHook;
51 use MediaWiki\Permissions\PermissionManager;
52 use MediaWiki\Preferences\Hook\GetPreferencesHook;
53 use MediaWiki\Preferences\MultiTitleFilter;
54 use MediaWiki\Preferences\MultiUsernameFilter;
55 use MediaWiki\Registration\ExtensionRegistry;
56 use MediaWiki\Request\WebRequest;
57 use MediaWiki\ResourceLoader as RL;
58 use MediaWiki\ResourceLoader\Hook\ResourceLoaderRegisterModulesHook;
59 use MediaWiki\ResourceLoader\ResourceLoader;
60 use MediaWiki\Revision\RevisionRecord;
61 use MediaWiki\Revision\RevisionStore;
62 use MediaWiki\SpecialPage\SpecialPage;
63 use MediaWiki\Storage\EditResult;
64 use MediaWiki\Storage\Hook\PageSaveCompleteHook;
65 use MediaWiki\Title\NamespaceInfo;
66 use MediaWiki\Title\Title;
67 use MediaWiki\User\CentralId\CentralIdLookup;
68 use MediaWiki\User\Hook\UserClearNewTalkNotificationHook;
69 use MediaWiki\User\Hook\UserGetDefaultOptionsHook;
70 use MediaWiki\User\Hook\UserGroupsChangedHook;
71 use MediaWiki\User\Hook\UserSaveSettingsHook;
72 use MediaWiki\User\Options\Hook\LoadUserOptionsHook;
73 use MediaWiki\User\Options\Hook\SaveUserOptionsHook;
74 use MediaWiki\User\Options\UserOptionsManager;
75 use MediaWiki\User\TalkPageNotificationManager;
76 use MediaWiki\User\User;
77 use MediaWiki\User\UserEditTracker;
78 use MediaWiki\User\UserFactory;
79 use MediaWiki\User\UserIdentity;
80 use MediaWiki\WikiMap\WikiMap;
81 use RecentChange;
82 use Skin;
83 use SkinTemplate;
84 use Wikimedia\Stats\StatsFactory;
85 use WikiPage;
86
87 class Hooks implements
88 AbortTalkPageEmailNotificationHook,
89 ApiMain__moduleManagerHook,
90 ArticleDeleteCompleteHook,
91 ArticleUndeleteHook,
92 BeforePageDisplayHook,
93 EmailUserCompleteHook,
94 GetNewMessagesAlertHook,
95 GetPreferencesHook,
96 LinksUpdateCompleteHook,
97 LoadUserOptionsHook,
98 LocalUserCreatedHook,
99 LoginFormValidErrorMessagesHook,
100 OutputPageCheckLastModifiedHook,
101 PageSaveCompleteHook,
102 PreferencesGetIconHook,
103 RecentChange_saveHook,
104 ResourceLoaderRegisterModulesHook,
105 RollbackCompleteHook,
106 SaveUserOptionsHook,
107 SendWatchlistEmailNotificationHook,
108 SkinTemplateNavigation__UniversalHook,
109 UserClearNewTalkNotificationHook,
110 UserGetDefaultOptionsHook,
111 UserGroupsChangedHook,
112 UserSaveSettingsHook,
113 SpecialMuteModifyFormFieldsHook
114 {
115 private AuthManager $authManager;
116 private CentralIdLookup $centralIdLookup;
117 private Config $config;
118 private AttributeManager $attributeManager;
119 private HookContainer $hookContainer;
120 private Language $contentLanguage;
121 private LinkRenderer $linkRenderer;
122 private NamespaceInfo $namespaceInfo;
123 private PermissionManager $permissionManager;
124 private RevisionStore $revisionStore;
125 private StatsFactory $statsFactory;
126 private TalkPageNotificationManager $talkPageNotificationManager;
127 private UserEditTracker $userEditTracker;
128 private UserFactory $userFactory;
129 private UserOptionsManager $userOptionsManager;
130
131 private static array $revertedRevIds = [];
132
133 public function __construct(
134 AuthManager $authManager,
135 CentralIdLookup $centralIdLookup,
136 Config $config,
137 AttributeManager $attributeManager,
138 HookContainer $hookContainer,
139 Language $contentLanguage,
140 LinkRenderer $linkRenderer,
141 NamespaceInfo $namespaceInfo,
142 PermissionManager $permissionManager,
143 RevisionStore $revisionStore,
144 StatsFactory $statsFactory,
145 TalkPageNotificationManager $talkPageNotificationManager,
146 UserEditTracker $userEditTracker,
147 UserFactory $userFactory,
148 UserOptionsManager $userOptionsManager
149 ) {
150 $this->authManager = $authManager;
151 $this->centralIdLookup = $centralIdLookup;
152 $this->config = $config;
153 $this->attributeManager = $attributeManager;
154 $this->hookContainer = $hookContainer;
155 $this->contentLanguage = $contentLanguage;
156 $this->linkRenderer = $linkRenderer;
157 $this->namespaceInfo = $namespaceInfo;
158 $this->permissionManager = $permissionManager;
159 $this->revisionStore = $revisionStore;
160 $this->statsFactory = $statsFactory->withComponent( 'Echo' );
161 $this->talkPageNotificationManager = $talkPageNotificationManager;
162 $this->userEditTracker = $userEditTracker;
163 $this->userFactory = $userFactory;
164 $this->userOptionsManager = $userOptionsManager;
165 }
166
167 /**
168 * @param array &$defaults
169 */
170 public function onUserGetDefaultOptions( &$defaults ) {
171 if ( $this->config->get( MainConfigNames::AllowHTMLEmail ) ) {
172 $defaults['echo-email-format'] = 'html';
173 } else {
174 $defaults['echo-email-format'] = 'plain-text';
175 }
176
177 $presets = [
178 // Set all of the events to notify by web but not email by default
179 // (won't affect events that don't email)
180 'default' => [
181 'email' => false,
182 'web' => true,
183 ],
184 // most settings default to web on, email off, but override these
185 'system' => [
186 'email' => true,
187 ],
188 'user-rights' => [
189 'email' => true,
190 ],
191 'article-linked' => [
192 'web' => false,
193 ],
194 'mention-failure' => [
195 'web' => false,
196 ],
197 'mention-success' => [
198 'web' => false,
199 ],
200 'watchlist' => [
201 'web' => false,
202 ],
203 'minor-watchlist' => [
204 'web' => false,
205 ],
206 'api-triggered' => [
207 // emails are sent only if sender also sets the API option, which is disabled by default
208 'email' => true,
209 ],
210 ];
211
212 $echoPushEnabled = $this->config->get( ConfigNames::EnablePush );
213 if ( $echoPushEnabled ) {
214 $presets['default']['push'] = true;
215 $presets['article-linked']['push'] = false;
216 $presets['mention-failure']['push'] = false;
217 $presets['mention-success']['push'] = false;
218 $presets['watchlist']['push'] = false;
219 $presets['minor-watchlist']['push'] = false;
220 }
221
222 foreach ( $this->config->get( ConfigNames::NotificationCategories ) as $category => $categoryData ) {
223 if ( !isset( $defaults["echo-subscriptions-email-{$category}"] ) ) {
224 $defaults["echo-subscriptions-email-{$category}"] = $presets[$category]['email']
225 ?? $presets['default']['email'];
226 }
227 if ( !isset( $defaults["echo-subscriptions-web-{$category}"] ) ) {
228 $defaults["echo-subscriptions-web-{$category}"] = $presets[$category]['web']
229 ?? $presets['default']['web'];
230 }
231 if ( $echoPushEnabled && !isset( $defaults["echo-subscriptions-push-{$category}"] ) ) {
232 $defaults["echo-subscriptions-push-{$category}"] = $presets[$category]['push']
233 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
234 ?? $presets['default']['push'];
235 }
236 }
237 }
238
239 /**
240 * Initialize Echo extension with necessary data, this function is invoked
241 * from $wgExtensionFunctions
242 */
243 public static function initEchoExtension() {
244 global $wgEchoNotifications, $wgEchoNotificationCategories, $wgEchoNotificationIcons,
245 $wgEchoMentionStatusNotifications, $wgAllowArticleReminderNotification, $wgAPIModules,
246 $wgEchoWatchlistNotifications, $wgEchoSeenTimeCacheType, $wgMainStash, $wgEnableEmail,
247 $wgEnableUserEmail, $wgEchoEnableApiEvents;
248
249 // allow extensions to define their own event
250 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onBeforeCreateEchoEvent(
251 $wgEchoNotifications, $wgEchoNotificationCategories, $wgEchoNotificationIcons );
252
253 // Only allow mention status notifications when enabled
254 if ( !$wgEchoMentionStatusNotifications ) {
255 unset( $wgEchoNotificationCategories['mention-failure'] );
256 unset( $wgEchoNotificationCategories['mention-success'] );
257 }
258
259 // Only allow article reminder notifications when enabled
260 if ( !$wgAllowArticleReminderNotification ) {
261 unset( $wgEchoNotificationCategories['article-reminder'] );
262 unset( $wgAPIModules['echoarticlereminder'] );
263 }
264
265 // Only allow watchlist notifications when enabled
266 if ( !$wgEchoWatchlistNotifications ) {
267 unset( $wgEchoNotificationCategories['watchlist'] );
268 unset( $wgEchoNotificationCategories['minor-watchlist'] );
269 }
270
271 // Only allow user email notifications when enabled
272 if ( !$wgEnableEmail || !$wgEnableUserEmail ) {
273 unset( $wgEchoNotificationCategories['emailuser'] );
274 }
275
276 // Only allow API-triggered notifications when enabled
277 if ( !$wgEchoEnableApiEvents ) {
278 unset( $wgEchoNotificationCategories['api-triggered'] );
279 }
280
281 // Default $wgEchoSeenTimeCacheType to $wgMainStash
282 if ( $wgEchoSeenTimeCacheType === null ) {
283 $wgEchoSeenTimeCacheType = $wgMainStash;
284 }
285 }
286
287 /**
288 * Handler for ResourceLoaderRegisterModules hook
289 * @param ResourceLoader $resourceLoader
290 */
291 public function onResourceLoaderRegisterModules( ResourceLoader $resourceLoader ): void {
292 $resourceLoader->register( 'ext.echo.emailicons', [
293 'class' => ResourceLoaderEchoImageModule::class,
294 'icons' => $this->config->get( ConfigNames::NotificationIcons ),
295 'selector' => '.mw-echo-icon-{name}',
296 'localBasePath' => $this->config->get( MainConfigNames::ExtensionDirectory ),
297 'remoteExtPath' => 'Echo/modules'
298 ] );
299 $resourceLoader->register( 'ext.echo.secondaryicons', [
300 'class' => ResourceLoaderEchoImageModule::class,
301 'icons' => $this->config->get( ConfigNames::SecondaryIcons ),
302 'selector' => '.mw-echo-icon-{name}',
303 'localBasePath' => $this->config->get( MainConfigNames::ExtensionDirectory ),
304 'remoteExtPath' => 'Echo/modules'
305 ] );
306 }
307
308 /**
309 * Handler for GetPreferences hook.
310 * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetPreferences
311 *
312 * @param User $user User to get preferences for
313 * @param array &$preferences Preferences array
314 */
315 public function onGetPreferences( $user, &$preferences ) {
316 // The following messages are generated upstrem:
317 // * prefs-echo
318 // * prefs-description-echo
319
320 // Show email frequency options
321 $freqOptions = [
322 'echo-pref-email-frequency-never' => EmailFrequency::NEVER,
323 'echo-pref-email-frequency-immediately' => EmailFrequency::IMMEDIATELY,
324 ];
325 // Only show digest options if email batch is enabled
326 if ( $this->config->get( ConfigNames::EnableEmailBatch ) ) {
327 $freqOptions += [
328 'echo-pref-email-frequency-daily' => EmailFrequency::DAILY_DIGEST,
329 'echo-pref-email-frequency-weekly' => EmailFrequency::WEEKLY_DIGEST,
330 ];
331 }
332 $preferences['echo-email-frequency'] = [
333 'type' => 'select',
334 'label-message' => 'echo-pref-send-me',
335 // The following message is generated upstrem:
336 // * prefs-emailsettings
337 'section' => 'echo/emailsettings',
338 'options-messages' => $freqOptions
339 ];
340
341 $preferences['echo-dont-email-read-notifications'] = [
342 'type' => 'toggle',
343 'label-message' => 'echo-pref-dont-email-read-notifications',
344 // The following message is generated upstrem:
345 // * prefs-emailsettings
346 'section' => 'echo/emailsettings',
347 'hide-if' => [ 'OR', [ '===', 'echo-email-frequency', '-1' ], [ '===', 'echo-email-frequency', '0' ] ]
348 ];
349
350 // Display information about the user's currently set email address
351 $prefsTitle = SpecialPage::getTitleFor( 'Preferences', false, 'mw-prefsection-echo' );
352 $link = $this->linkRenderer->makeLink(
353 SpecialPage::getTitleFor( 'ChangeEmail' ),
354 wfMessage( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->text(),
355 [],
356 [ 'returnto' => $prefsTitle->getFullText() ]
357 );
358 $emailAddress = $user->getEmail() && $this->permissionManager->userHasRight( $user, 'viewmyprivateinfo' )
359 ? htmlspecialchars( $user->getEmail() ) : '';
360 if ( $this->permissionManager->userHasRight( $user, 'editmyprivateinfo' ) && $this->isEmailChangeAllowed() ) {
361 if ( $emailAddress === '' ) {
362 $emailAddress .= $link;
363 } else {
364 $emailAddress .= wfMessage( 'word-separator' )->escaped()
365 . wfMessage( 'parentheses' )->rawParams( $link )->escaped();
366 }
367 }
368 $preferences['echo-emailaddress'] = [
369 'type' => 'info',
370 'raw' => true,
371 'default' => $emailAddress,
372 'label-message' => 'echo-pref-send-to',
373 // The following message is generated upstrem:
374 // * prefs-emailsettings
375 'section' => 'echo/emailsettings'
376 ];
377
378 // Only show this option if html email is allowed, otherwise it is always plain text format
379 if ( $this->config->get( MainConfigNames::AllowHTMLEmail ) ) {
380 // Email format
381 $preferences['echo-email-format'] = [
382 'type' => 'select',
383 'label-message' => 'echo-pref-email-format',
384 // The following message is generated upstrem:
385 // * prefs-emailsettings
386 'section' => 'echo/emailsettings',
387 'options-messages' => [
388 'echo-pref-email-format-html' => EmailFormat::HTML,
389 'echo-pref-email-format-plain-text' => EmailFormat::PLAIN_TEXT,
390 ]
391 ];
392 }
393
394 // Sort notification categories by priority
395 $categoriesAndPriorities = [];
396 foreach ( $this->attributeManager->getInternalCategoryNames() as $category ) {
397 // See if the category should be hidden from preferences.
398 if ( !$this->attributeManager->isCategoryDisplayedInPreferences( $category ) ) {
399 continue;
400 }
401
402 // See if user is eligible to receive this notification (per user group restrictions)
403 if ( $this->attributeManager->getCategoryEligibility( $user, $category ) ) {
404 $categoriesAndPriorities[$category] = $this->attributeManager->getCategoryPriority( $category );
405 }
406 }
407 asort( $categoriesAndPriorities );
408 $validSortedCategories = array_keys( $categoriesAndPriorities );
409
410 // Show subscription options. IMPORTANT: 'echo-subscriptions-email-edit-user-talk',
411 // 'echo-subscriptions-email-watchlist', and 'echo-subscriptions-email-minor-watchlist' are
412 // virtual options, their values are saved to existing notification options 'enotifusertalkpages',
413 // 'enotifwatchlistpages', and 'enotifminoredits', see onLoadUserOptions() and onSaveUserOptions()
414 // for more information on how it is handled. Doing it in this way, we can avoid keeping running
415 // massive data migration script to keep these two options synced when echo is enabled on
416 // new wikis or Echo is disabled and re-enabled for some reason. We can update the name
417 // if Echo is ever merged to core
418
419 // Build the columns (notify types)
420 $columns = [];
421 foreach ( $this->config->get( ConfigNames::Notifiers ) as $notifierType => $notifierData ) {
422 // The following messages are generated here
423 // * echo-pref-web
424 // * echo-pref-email
425 // * echo-pref-push
426 $formatMessage = wfMessage( 'echo-pref-' . $notifierType )->escaped();
427 $columns[$formatMessage] = $notifierType;
428 }
429
430 // Build the rows (notification categories)
431 $rows = [];
432 $tooltips = [];
433 $notificationCategories = $this->config->get( ConfigNames::NotificationCategories );
434 foreach ( $validSortedCategories as $category ) {
435 $categoryMessage = wfMessage( 'echo-category-title-' . $category )->numParams( 1 )->escaped();
436 $rows[$categoryMessage] = $category;
437 if ( isset( $notificationCategories[$category]['tooltip'] ) ) {
438 $tooltips[$categoryMessage] = wfMessage( $notificationCategories[$category]['tooltip'] )->text();
439 }
440 }
441
442 // Figure out the individual exceptions in the matrix and make them disabled
443 $forceOptionsOff = $forceOptionsOn = [];
444 foreach ( $this->config->get( ConfigNames::Notifiers ) as $notifierType => $notifierData ) {
445 foreach ( $validSortedCategories as $category ) {
446 // See if this notify type is non-dismissable
447 if ( !$this->attributeManager->isNotifyTypeDismissableForCategory( $category, $notifierType ) ) {
448 $forceOptionsOn[] = "$notifierType-$category";
449 }
450
451 if ( !$this->attributeManager->isNotifyTypeAvailableForCategory( $category, $notifierType ) ) {
452 $forceOptionsOff[] = "$notifierType-$category";
453 }
454 }
455 }
456
457 $invalid = array_intersect( $forceOptionsOff, $forceOptionsOn );
458 if ( $invalid ) {
459 throw new LogicException( sprintf(
460 'The following notifications are both forced and removed: %s',
461 implode( ', ', $invalid )
462 ) );
463 }
464 $preferences['echo-subscriptions'] = [
465 'class' => HTMLCheckMatrix::class,
466 // The following message is generated upstrem:
467 // * prefs-echosubscriptions
468 'section' => 'echo/echosubscriptions',
469 'rows' => $rows,
470 'columns' => $columns,
471 'prefix' => 'echo-subscriptions-',
472 'force-options-off' => $forceOptionsOff,
473 'force-options-on' => $forceOptionsOn,
474 'tooltips' => $tooltips,
475 ];
476
477 if ( $this->config->get( ConfigNames::CrossWikiNotifications ) ) {
478 $preferences['echo-cross-wiki-notifications'] = [
479 'type' => 'toggle',
480 'label-message' => 'echo-pref-cross-wiki-notifications',
481 // The following message is generated upstrem:
482 // * prefs-echocrosswiki
483 'section' => 'echo/echocrosswiki'
484 ];
485 }
486
487 if ( $this->config->get( ConfigNames::PollForUpdates ) ) {
488 $preferences['echo-show-poll-updates'] = [
489 'type' => 'toggle',
490 'label-message' => 'echo-pref-show-poll-updates',
491 'help-message' => 'echo-pref-show-poll-updates-help',
492 // The following message is generated upstrem:
493 // * prefs-echopollupdates
494 'section' => 'echo/echopollupdates'
495 ];
496 }
497
498 // If we're using Echo to handle user talk page post or watchlist notifications,
499 // hide the old (non-Echo) preferences for them. If Echo is moved to core
500 // we'll want to remove the old user options entirely. For now, though,
501 // we need to keep it defined in case Echo is ever uninstalled.
502 // Otherwise, that preference could be lost entirely. This hiding logic
503 // is not abstracted since there are only three preferences in core
504 // that are potentially made obsolete by Echo.
505 $notifications = $this->config->get( ConfigNames::Notifications );
506 if ( isset( $notifications['edit-user-talk'] ) ) {
507 $preferences['enotifusertalkpages']['type'] = 'hidden';
508 unset( $preferences['enotifusertalkpages']['section'] );
509 }
510 if ( $this->config->get( ConfigNames::WatchlistNotifications ) &&
511 isset( $notifications['watchlist-change'] )
512 ) {
513 $preferences['enotifwatchlistpages']['type'] = 'hidden';
514 unset( $preferences['enotifusertalkpages']['section'] );
515 $preferences['enotifminoredits']['type'] = 'hidden';
516 unset( $preferences['enotifminoredits']['section'] );
517 }
518
519 if ( $this->config->get( ConfigNames::PerUserBlacklist ) ) {
520 $preferences['echo-notifications-blacklist'] = [
521 'type' => 'usersmultiselect',
522 'label-message' => 'echo-pref-notifications-blacklist',
523 // The following message is generated upstrem:
524 // * prefs-blocknotificationslist
525 'section' => 'echo/blocknotificationslist',
526 'filter' => MultiUsernameFilter::class,
527 ];
528 $preferences['echo-notifications-page-linked-title-muted-list'] = [
529 'type' => 'titlesmultiselect',
530 'label-message' => 'echo-pref-notifications-page-linked-title-muted-list',
531 // The following message is generated upstrem:
532 // * prefs-mutedpageslist
533 'section' => 'echo/mutedpageslist',
534 'showMissing' => false,
535 'excludeDynamicNamespaces' => true,
536 'filter' => new MultiTitleFilter()
537 ];
538 }
539 }
540
541 /**
542 * Add icon for Special:Preferences mobile layout
543 *
544 * @param array &$iconNames Array of icon names for their respective sections.
545 */
546 public function onPreferencesGetIcon( &$iconNames ) {
547 $iconNames[ 'echo' ] = 'bell';
548 }
549
550 /**
551 * Test whether email address change is supposed to be allowed
552 * @return bool
553 */
554 private function isEmailChangeAllowed() {
555 return $this->authManager->allowsPropertyChange( 'emailaddress' );
556 }
557
558 /**
559 * Handler for PageSaveComplete hook
560 * @see https://www.mediawiki.org/wiki/Manual:Hooks/PageSaveComplete
561 *
562 * @param WikiPage $wikiPage modified WikiPage
563 * @param UserIdentity $userIdentity User who edited
564 * @param string $summary Edit summary
565 * @param int $flags Edit flags
566 * @param RevisionRecord $revisionRecord RevisionRecord for the revision that was created
567 * @param EditResult $editResult
568 */
569 public function onPageSaveComplete(
570 $wikiPage,
571 $userIdentity,
572 $summary,
573 $flags,
574 $revisionRecord,
575 $editResult
576 ) {
577 if ( $editResult->isNullEdit() ) {
578 return;
579 }
580
581 $title = $wikiPage->getTitle();
582 $isRevert = $editResult->getRevertMethod() === EditResult::REVERT_UNDO ||
583 $editResult->getRevertMethod() === EditResult::REVERT_ROLLBACK;
584
585 // Save the revert status for the LinksUpdateComplete hook
586 if ( $isRevert ) {
587 self::$revertedRevIds[$revisionRecord->getId()] = true;
588 }
589
590 // Try to do this after the HTTP response
591 DeferredUpdates::addCallableUpdate( static function () use ( $revisionRecord, $isRevert ) {
592 DiscussionParser::generateEventsForRevision( $revisionRecord, $isRevert );
593 } );
594
595 // If the user is not an IP and this is not a null edit,
596 // test for them reaching a congratulatory threshold
597 $thresholds = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 ];
598 if ( $userIdentity->isRegistered() ) {
599 $thresholdCount = $this->getEditCount( $userIdentity );
600 if ( in_array( $thresholdCount, $thresholds ) ) {
601 DeferredUpdates::addCallableUpdate( static function () use (
602 $revisionRecord, $userIdentity, $title, $thresholdCount
603 ) {
604 $notificationMapper = new NotificationMapper();
605 $notifications = $notificationMapper->fetchByUser( $userIdentity, 10, null, [ 'thank-you-edit' ] );
606 /** @var Notification $notification */
607 foreach ( $notifications as $notification ) {
608 if ( $notification->getEvent()->getExtraParam( 'editCount' ) === $thresholdCount ) {
609 LoggerFactory::getInstance( 'Echo' )->debug(
610 '{user} (id: {id}) has already been thanked for their {count} edit',
611 [
612 'user' => $userIdentity->getName(),
613 'id' => $userIdentity->getId(),
614 'count' => $thresholdCount,
615 ]
616 );
617 return;
618 }
619 }
620
621 Event::create( [
622 'type' => 'thank-you-edit',
623 'title' => $title,
624 'agent' => $userIdentity,
625 // Edit threshold notifications are sent to the agent
626 'extra' => [
627 'editCount' => $thresholdCount,
628 'revid' => $revisionRecord->getId(),
629 ]
630 ] );
631 } );
632 }
633 }
634
635 // Handle the case of someone undoing an edit, either through the
636 // 'undo' link in the article history or via the API.
637 // Reverts through the 'rollback' link (EditResult::REVERT_ROLLBACK)
638 // are handled in ::onRollbackComplete().
639 if ( $editResult->getRevertMethod() === EditResult::REVERT_UNDO ) {
640 $undidRevId = $editResult->getUndidRevId();
641 $undidRevision = $this->revisionStore->getRevisionById( $undidRevId );
642 if (
643 $undidRevision &&
644 Title::newFromLinkTarget( $undidRevision->getPageAsLinkTarget() )->equals( $title )
645 ) {
646 $revertedUser = $undidRevision->getUser();
647 // No notifications for anonymous users
648 if ( $revertedUser && $revertedUser->getId() ) {
649 Event::create( [
650 'type' => 'reverted',
651 'title' => $title,
652 'extra' => [
653 'revid' => $revisionRecord->getId(),
654 'reverted-user-id' => $revertedUser->getId(),
655 'reverted-revision-id' => $undidRevId,
656 'method' => 'undo',
657 'summary' => $summary,
658 ],
659 'agent' => $userIdentity,
660 ] );
661 }
662 }
663 }
664 }
665
666 /**
667 * @param UserIdentity $user
668 * @return int
669 */
670 private function getEditCount( UserIdentity $user ) {
671 $editCount = $this->userEditTracker->getUserEditCount( $user ) ?: 0;
672 // When this code runs from a maintenance script or unit tests
673 // the deferred update incrementing edit count runs right away
674 // so the edit count is right. Otherwise it lags by one.
675 if ( wfIsCLI() ) {
676 return $editCount;
677 }
678 return $editCount + 1;
679 }
680
681 /**
682 * Handler for LocalUserCreated hook.
683 * @see https://www.mediawiki.org/wiki/Manual:Hooks/LocalUserCreated
684 * @param User $user User object that was created.
685 * @param bool $autocreated True when account was auto-created
686 */
687 public function onLocalUserCreated( $user, $autocreated ) {
688 if ( !$autocreated ) {
689 Event::create( [
690 'type' => 'welcome',
691 'agent' => $user,
692 ] );
693 }
694
695 $seenTime = SeenTime::newFromUser( $user );
696
697 // Set seen time to UNIX epoch, so initially all notifications are unseen.
698 $seenTime->setTime( wfTimestamp( TS_MW, 1 ), 'all' );
699 }
700
701 /**
702 * Handler for UserGroupsChanged hook.
703 * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserGroupsChanged
704 *
705 * @param UserIdentity $userId user that was changed
706 * @param string[] $add strings corresponding to groups added
707 * @param string[] $remove strings corresponding to groups removed
708 * @param User|bool $performer
709 * @param string|bool $reason Reason given by the user changing the rights
710 * @param array $oldUGMs
711 * @param array $newUGMs
712 */
713 public function onUserGroupsChanged( $userId, $add, $remove, $performer, $reason, $oldUGMs, $newUGMs ) {
714 if ( !$performer ) {
715 // TODO: Implement support for autopromotion
716 return;
717 }
718
719 if ( $userId->getWikiId() !== WikiAwareEntity::LOCAL ) {
720 // TODO: Support external users
721 return;
722 }
723
724 $user = $this->userFactory->newFromUserIdentity( $userId );
725
726 if ( $user->equals( $performer ) ) {
727 // Don't notify for self changes
728 return;
729 }
730
731 // If any old groups are in $add, those groups are having their expiry
732 // changed, not actually being added
733 $expiryChanged = [];
734 $reallyAdded = [];
735 foreach ( $add as $group ) {
736 if ( isset( $oldUGMs[$group] ) ) {
737 $expiryChanged[] = $group;
738 } else {
739 $reallyAdded[] = $group;
740 }
741 }
742
743 if ( $expiryChanged ) {
744 // use a separate notification for these, so the notification text doesn't
745 // get too long
746 Event::create(
747 [
748 'type' => 'user-rights',
749 'extra' => [
750 'user' => $user->getId(),
751 'expiry-changed' => $expiryChanged,
752 'reason' => $reason,
753 ],
754 'agent' => $performer,
755 ]
756 );
757 }
758
759 if ( $reallyAdded || $remove ) {
760 Event::create(
761 [
762 'type' => 'user-rights',
763 'extra' => [
764 'user' => $user->getId(),
765 'add' => $reallyAdded,
766 'remove' => $remove,
767 'reason' => $reason,
768 ],
769 'agent' => $performer,
770 ]
771 );
772 }
773 }
774
775 /**
776 * Handler for LinksUpdateComplete hook.
777 * @see https://www.mediawiki.org/wiki/Manual:Hooks/LinksUpdateComplete
778 * @param LinksUpdate $linksUpdate
779 * @param mixed $ticket
780 */
781 public function onLinksUpdateComplete( $linksUpdate, $ticket ) {
782 // Rollback or undo should not trigger link notification
783 if ( $linksUpdate->getRevisionRecord() ) {
784 $revId = $linksUpdate->getRevisionRecord()->getId();
785 if ( isset( self::$revertedRevIds[$revId] ) ) {
786 return;
787 }
788 }
789
790 // Handle only
791 // 1. content namespace pages &&
792 // 2. non-transcluding pages &&
793 // 3. non-redirect pages
794 if ( !$this->namespaceInfo->isContent( $linksUpdate->getTitle()->getNamespace() )
795 || !$linksUpdate->isRecursive() || $linksUpdate->getTitle()->isRedirect()
796 ) {
797 return;
798 }
799
800 $revRecord = $linksUpdate->getRevisionRecord();
801 $revid = $revRecord ? $revRecord->getId() : null;
802 $user = $revRecord ? $revRecord->getUser() : null;
803
804 // link notification is boundless as you can include infinite number of links in a page
805 // db insert is expensive, limit it to a reasonable amount, we can increase this limit
806 // once the storage is on Redis
807 $max = 10;
808 // Only create notifications for links to content namespace pages
809 // @Todo - use one big insert instead of individual insert inside foreach loop
810 foreach ( $linksUpdate->getPageReferenceIterator( 'pagelinks', LinksTable::INSERTED ) as $pageReference ) {
811 if ( $this->namespaceInfo->isContent( $pageReference->getNamespace() ) ) {
812 $title = Title::newFromPageReference( $pageReference );
813 if ( $title->isRedirect() ) {
814 continue;
815 }
816
817 $linkFromPageId = $linksUpdate->getTitle()->getArticleID();
818 // T318523: Don't send page-linked notifications for pages created by bot users.
819 $articleAuthor = UserLocator::getArticleAuthorByArticleId( $title->getArticleID() );
820 if ( $articleAuthor && $articleAuthor->isBot() ) {
821 continue;
822 }
823 Event::create( [
824 'type' => 'page-linked',
825 'title' => $title,
826 'agent' => $user,
827 'extra' => [
828 'target-page' => $linkFromPageId,
829 'link-from-page-id' => $linkFromPageId,
830 'revid' => $revid,
831 ]
832 ] );
833 $max--;
834 }
835 if ( $max < 0 ) {
836 break;
837 }
838 }
839 }
840
841 /**
842 * Handler for BeforePageDisplay hook.
843 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay
844 * @param OutputPage $out
845 * @param Skin $skin Skin being used.
846 */
847 public function onBeforePageDisplay( $out, $skin ): void {
848 $user = $out->getUser();
849
850 if ( !$user->isRegistered() ) {
851 if ( ExtensionRegistry::getInstance()->isLoaded( 'CentralAuth' ) ) {
852 $out->addModules( [ 'ext.echo.centralauth' ] );
853 }
854 return;
855 }
856
857 if ( $this->shouldDisplayTalkAlert( $user, $out->getTitle() ) ) {
858 // Load the module for the Orange alert
859 $out->addModuleStyles( 'ext.echo.styles.alert' );
860 }
861
862 // Load the module for the Notifications flyout
863 $out->addModules( [ 'ext.echo.init' ] );
864 // Load the styles for the Notifications badge
865 $out->addModuleStyles( [
866 'ext.echo.styles.badge',
867 'oojs-ui.styles.icons-alerts'
868 ] );
869 }
870
871 private function processMarkAsRead( User $user, WebRequest $request, Title $title ) {
872 $subtractions = [
873 AttributeManager::ALERT => 0,
874 AttributeManager::MESSAGE => 0
875 ];
876
877 // Attempt to mark a notification as read when visiting a page
878 $eventIds = [];
879 if ( $title->getArticleID() ) {
880 $eventMapper = new EventMapper();
881 $events = $eventMapper->fetchUnreadByUserAndPage( $user, $title->getArticleID() );
882
883 foreach ( $events as $event ) {
884 $subtractions[$event->getSection()]++;
885 $eventIds[] = $event->getId();
886 }
887 }
888
889 // Attempt to mark as read the event IDs in the ?markasread= parameter, if present
890 $markAsReadIds = array_filter( explode( '|', $request->getText( 'markasread' ) ) );
891 $markAsReadWiki = $request->getText( 'markasreadwiki', WikiMap::getCurrentWikiId() );
892 $markAsReadLocal = !$this->config->get( ConfigNames::CrossWikiNotifications ) ||
893 $markAsReadWiki === WikiMap::getCurrentWikiId();
894 if ( $markAsReadIds ) {
895 if ( $markAsReadLocal ) {
896 // gather the IDs that we didn't already find with target_pages
897 $eventsToMarkAsRead = [];
898 foreach ( $markAsReadIds as $markAsReadId ) {
899 $markAsReadId = intval( $markAsReadId );
900 if ( $markAsReadId !== 0 && !in_array( $markAsReadId, $eventIds ) ) {
901 $eventsToMarkAsRead[] = $markAsReadId;
902 }
903 }
904
905 if ( $eventsToMarkAsRead ) {
906 // fetch the notifications to adjust the counters
907 $notifMapper = new NotificationMapper();
908 $notifs = $notifMapper->fetchByUserEvents( $user, $eventsToMarkAsRead );
909
910 foreach ( $notifs as $notif ) {
911 if ( !$notif->getReadTimestamp() ) {
912 $subtractions[$notif->getEvent()->getSection()]++;
913 $eventIds[] = intval( $notif->getEvent()->getId() );
914 }
915 }
916 }
917 } else {
918 $markAsReadIds = array_map( 'intval', $markAsReadIds );
919 // Look up the notifications on the foreign wiki
920 $notifUser = NotifUser::newFromUser( $user );
921 $notifInfo = $notifUser->getForeignNotificationInfo( $markAsReadIds, $markAsReadWiki, $request );
922 foreach ( $notifInfo as $id => $info ) {
923 $subtractions[$info['section']]++;
924 }
925
926 // Schedule a deferred update to mark these notifications as read on the foreign wiki
927 DeferredUpdates::addCallableUpdate(
928 static function () use ( $user, $markAsReadIds, $markAsReadWiki, $request ) {
929 $notifUser = NotifUser::newFromUser( $user );
930 $notifUser->markReadForeign( $markAsReadIds, $markAsReadWiki, $request );
931 }
932 );
933 }
934 }
935
936 // Schedule a deferred update to mark local target_page and ?markasread= notifications as read
937 if ( $eventIds ) {
938 DeferredUpdates::addCallableUpdate( static function () use ( $user, $eventIds ) {
939 $notifUser = NotifUser::newFromUser( $user );
940 $notifUser->markRead( $eventIds );
941 } );
942 }
943
944 return $subtractions;
945 }
946
947 /**
948 * Determine if a talk page alert should be displayed.
949 * We need to check:
950 * - User actually has new messages
951 * - User is not viewing their user talk page, as user_newtalk will not have been cleared yet.
952 * (bug T107655).
953 *
954 * @param User $user
955 * @param Title $title
956 * @return bool
957 */
958 private function shouldDisplayTalkAlert( $user, $title ) {
959 $userHasNewMessages = $this->talkPageNotificationManager->userHasNewMessages( $user );
960
961 return $userHasNewMessages && !$user->getTalkPage()->equals( $title );
962 }
963
964 /**
965 * Handler for SkinTemplateNavigation::Universal hook.
966 * Adds "Notifications" items to the notifications content navigation.
967 * SkinTemplate automatically merges these into the personal tools for older skins.
968 * @see https://www.mediawiki.org/wiki/Manual:Hooks/SkinTemplateNavigation::Universal
969 * @param SkinTemplate $skinTemplate
970 * @param array &$links Array of URLs to append to.
971 */
972 public function onSkinTemplateNavigation__Universal( $skinTemplate, &$links ): void {
973 if ( !$skinTemplate->getAuthority()->isRegistered() ) {
974 return;
975 }
976 if ( !$skinTemplate->getAuthority()->isAllowed( 'echo-read-notifications' ) ) {
977 return;
978 }
979
980 $title = $skinTemplate->getTitle();
981 $out = $skinTemplate->getOutput();
982 $user = $skinTemplate->getUser();
983
984 $subtractions = $this->processMarkAsRead( $user, $out->getRequest(), $title );
985
986 // Add a "My notifications" item to personal URLs
987 $notifUser = NotifUser::newFromUser( $user );
988 $msgCount = $notifUser->getMessageCount() - $subtractions[AttributeManager::MESSAGE];
989 $alertCount = $notifUser->getAlertCount() - $subtractions[AttributeManager::ALERT];
990 // But make sure we never show a negative number (T130853)
991 $msgCount = max( 0, $msgCount );
992 $alertCount = max( 0, $alertCount );
993
994 $msgNotificationTimestamp = $notifUser->getLastUnreadMessageTime();
995 $alertNotificationTimestamp = $notifUser->getLastUnreadAlertTime();
996
997 $seenTime = SeenTime::newFromUser( $user );
998 if ( $title->isSpecial( 'Notifications' ) ) {
999 // If this is the Special:Notifications page, seenTime to now
1000 $seenTime->setTime( wfTimestamp( TS_MW ), AttributeManager::ALL );
1001 }
1002 $seenAlertTime = $seenTime->getTime( 'alert', TS_ISO_8601 );
1003 $seenMsgTime = $seenTime->getTime( 'message', TS_ISO_8601 );
1004
1005 $out->addJsConfigVars( 'wgEchoSeenTime', [
1006 'alert' => $seenAlertTime,
1007 'notice' => $seenMsgTime,
1008 ] );
1009
1010 $msgFormattedCount = NotificationController::formatNotificationCount( $msgCount );
1011 $alertFormattedCount = NotificationController::formatNotificationCount( $alertCount );
1012
1013 $url = SpecialPage::getTitleFor( 'Notifications' )->getLocalURL();
1014
1015 $skinName = strtolower( $skinTemplate->getSkinName() );
1016 $isMinervaSkin = $skinName === 'minerva';
1017 // HACK: inverted icons only work in the "MediaWiki" OOUI theme
1018 // Avoid flashes in skins that don't use it (T111821)
1019 $out::setupOOUI( $skinName, $out->getLanguage()->getDir() );
1020 $bellIconClass = $isMinervaSkin ? 'oo-ui-icon-bellOutline' : 'oo-ui-icon-bell';
1021
1022 $msgLinkClasses = [ "mw-echo-notifications-badge", "mw-echo-notification-badge-nojs", "oo-ui-icon-tray" ];
1023 $alertLinkClasses = [ "mw-echo-notifications-badge", "mw-echo-notification-badge-nojs", $bellIconClass ];
1024
1025 $hasUnseen = false;
1026 if (
1027 // no unread notifications
1028 $msgCount !== 0 &&
1029 // should already always be false if count === 0
1030 $msgNotificationTimestamp !== false &&
1031 // there are no unseen notifications
1032 ( $seenMsgTime === null ||
1033 $seenMsgTime < $msgNotificationTimestamp->getTimestamp( TS_ISO_8601 ) )
1034 ) {
1035 $msgLinkClasses[] = 'mw-echo-unseen-notifications';
1036 $hasUnseen = true;
1037 } elseif ( $msgCount === 0 ) {
1038 $msgLinkClasses[] = 'mw-echo-notifications-badge-all-read';
1039 }
1040
1041 if ( $msgCount > NotifUser::MAX_BADGE_COUNT ) {
1042 $msgLinkClasses[] = 'mw-echo-notifications-badge-long-label';
1043 }
1044
1045 if (
1046 // no unread notifications
1047 $alertCount !== 0 &&
1048 // should already always be false if count === 0
1049 $alertNotificationTimestamp !== false &&
1050 // all notifications have already been seen
1051 ( $seenAlertTime === null ||
1052 $seenAlertTime < $alertNotificationTimestamp->getTimestamp( TS_ISO_8601 ) )
1053 ) {
1054 $alertLinkClasses[] = 'mw-echo-unseen-notifications';
1055 $hasUnseen = true;
1056 } elseif ( $alertCount === 0 ) {
1057 $alertLinkClasses[] = 'mw-echo-notifications-badge-all-read';
1058 }
1059
1060 if ( $alertCount > NotifUser::MAX_BADGE_COUNT ) {
1061 $alertLinkClasses[] = 'mw-echo-notifications-badge-long-label';
1062 }
1063
1064 $mytalk = $links['user-menu']['mytalk'] ?? false;
1065 if (
1066 $mytalk &&
1067 $this->shouldDisplayTalkAlert( $user, $title ) &&
1068 ( new HookRunner( $this->hookContainer ) )->onBeforeDisplayOrangeAlert( $user, $title )
1069 ) {
1070 // Create new talk alert inheriting from the talk link data.
1071 $links['notifications']['talk-alert'] = array_merge(
1072 $links['user-menu']['mytalk'],
1073 [
1074 // Hardcode id, which is needed to dismiss the talk alert notification
1075 'id' => 'pt-talk-alert',
1076 // If Vector hook ran anicon will have been copied to the link class.
1077 // We must reset it.
1078 'link-class' => [],
1079 'text' => $skinTemplate->msg( 'echo-new-messages' )->text(),
1080 'class' => [ 'mw-echo-alert' ],
1081 // unset icon
1082 'icon' => null,
1083 ]
1084 );
1085
1086 // If there's exactly one new user talk message, then link directly to it from the alert.
1087 $notificationMapper = new NotificationMapper();
1088 $notifications = $notificationMapper->fetchUnreadByUser( $user, 2, null, [ 'edit-user-talk' ] );
1089 if ( count( $notifications ) === 1 ) {
1090 $presModel = EchoEventPresentationModel::factory(
1091 current( $notifications )->getEvent(),
1092 $out->getLanguage(),
1093 $user
1094 );
1095 $links['notifications']['talk-alert']['href'] = $presModel->getPrimaryLink()['url'];
1096 }
1097 }
1098
1099 $links['notifications']['notifications-alert'] = [
1100 'href' => $url,
1101 'text' => $skinTemplate->msg( 'echo-notification-alert', $alertCount )->text(),
1102 'active' => ( $url == $title->getLocalURL() ),
1103 'link-class' => $alertLinkClasses,
1104 'icon' => 'bell',
1105 'data' => [
1106 'event-name' => 'ui.notifications',
1107 'counter-num' => $alertCount,
1108 'counter-text' => $alertFormattedCount,
1109 ],
1110 // This item used to be part of personal tools, and much CSS relies on it using this id.
1111 'id' => 'pt-notifications-alert',
1112 ];
1113
1114 $links['notifications']['notifications-notice'] = [
1115 'href' => $url,
1116 'text' => $skinTemplate->msg( 'echo-notification-notice', $msgCount )->text(),
1117 'active' => ( $url == $title->getLocalURL() ),
1118 'link-class' => $msgLinkClasses,
1119 'icon' => 'tray',
1120 'data' => [
1121 'counter-num' => $msgCount,
1122 'counter-text' => $msgFormattedCount,
1123 ],
1124 // This item used to be part of personal tools, and much CSS relies on it using this id.
1125 'id' => 'pt-notifications-notice',
1126 ];
1127
1128 if ( $hasUnseen ) {
1129 // Record that the user is going to see an indicator that they have unseen notifications
1130 // This is part of tracking how likely users are to click a badge with unseen notifications.
1131 // The other part is the 'echo.unseen.click' counter, see ext.echo.init.js.
1132 $this->statsFactory->getCounter( 'unseen_total' )
1133 ->copyToStatsdAt( 'echo.unseen' )
1134 ->increment();
1135 }
1136 }
1137
1138 /**
1139 * Handler for AbortTalkPageEmailNotification hook.
1140 * @see https://www.mediawiki.org/wiki/Manual:Hooks/AbortTalkPageEmailNotification
1141 * @param User $targetUser
1142 * @param Title $title
1143 * @return bool
1144 */
1145 public function onAbortTalkPageEmailNotification( $targetUser, $title ) {
1146 // Send legacy talk page email notification if
1147 // 1. echo is disabled for them or
1148 // 2. echo talk page notification is disabled
1149 if ( !isset( $this->config->get( ConfigNames::Notifications )['edit-user-talk'] ) ) {
1150 // Legacy talk page email notification
1151 return true;
1152 }
1153
1154 // Echo talk page email notification
1155 return false;
1156 }
1157
1158 /**
1159 * Handler for AbortWatchlistEmailNotification hook.
1160 * @see https://www.mediawiki.org/wiki/Manual:Hooks/AbortWatchlistEmailNotification
1161 * @param User $targetUser
1162 * @param Title $title
1163 * @param EmailNotification $emailNotification The email notification object that sends non-echo notifications
1164 * @return bool
1165 */
1166 public function onSendWatchlistEmailNotification( $targetUser, $title, $emailNotification ) {
1167 if ( $this->config->get( ConfigNames::WatchlistNotifications ) &&
1168 isset( $this->config->get( ConfigNames::Notifications )["watchlist-change"] )
1169 ) {
1170 // Let echo handle watchlist notifications entirely
1171 return false;
1172 }
1173 $eventName = false;
1174 // The edit-user-talk and edit-user-page events effectively duplicate watchlist notifications.
1175 // If we are sending Echo notification emails, suppress the watchlist notifications.
1176 if ( $title->inNamespace( NS_USER_TALK ) && $targetUser->getTalkPage()->equals( $title ) ) {
1177 $eventName = 'edit-user-talk';
1178 } elseif ( $title->inNamespace( NS_USER ) && $targetUser->getUserPage()->equals( $title ) ) {
1179 $eventName = 'edit-user-page';
1180 }
1181
1182 if ( $eventName !== false ) {
1183 $events = $this->attributeManager->getUserEnabledEvents( $targetUser, 'email' );
1184 if ( in_array( $eventName, $events ) ) {
1185 // Do not send watchlist email notification, the user will receive an Echo notification
1186 return false;
1187 }
1188 }
1189
1190 // Proceed to send watchlist email notification
1191 return true;
1192 }
1193
1194 /**
1195 * @param array &$modifiedTimes
1196 * @param OutputPage $out
1197 */
1198 public function onOutputPageCheckLastModified( &$modifiedTimes, $out ) {
1199 $req = $out->getRequest();
1200 if ( $req->getRawVal( 'action' ) === 'raw' || $req->getRawVal( 'action' ) === 'render' ) {
1201 // Optimisation: Avoid expensive SeenTime compute on non-skin responses (T279213)
1202 return;
1203 }
1204
1205 $user = $out->getUser();
1206 if ( $user->isRegistered() ) {
1207 $notifUser = NotifUser::newFromUser( $user );
1208 $lastUpdate = $notifUser->getGlobalUpdateTime();
1209 if ( $lastUpdate !== false ) {
1210 $modifiedTimes['notifications-global'] = $lastUpdate;
1211 }
1212
1213 $modifiedTimes['notifications-seen-alert'] = SeenTime::newFromUser( $user )->getTime( 'alert' );
1214 $modifiedTimes['notifications-seen-message'] = SeenTime::newFromUser( $user )->getTime( 'message' );
1215 }
1216 }
1217
1218 /**
1219 * Handler for GetNewMessagesAlert hook.
1220 * We're using the GetNewMessagesAlert hook instead of the
1221 * ArticleEditUpdateNewTalk hook since we still want the user_newtalk data
1222 * to be updated and available to client-side tools and the API.
1223 * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetNewMessagesAlert
1224 * @param string &$newMessagesAlert An alert that the user has new messages
1225 * or an empty string if the user does not (empty by default)
1226 * @param array $newtalks This will be empty if the user has no new messages
1227 * or an Array containing links and revisions if there are new messages
1228 * @param User $user The user who is loading the page
1229 * @param OutputPage $out
1230 * @return bool Should return false to prevent the new messages alert (OBOD)
1231 * or true to allow the new messages alert
1232 */
1233 public function onGetNewMessagesAlert( &$newMessagesAlert, $newtalks, $user, $out ) {
1234 // If the user has the notifications flyout turned on and is receiving
1235 // notifications for talk page messages, disable the new messages alert.
1236 if ( $user->isRegistered()
1237 && isset( $this->config->get( ConfigNames::Notifications )['edit-user-talk'] )
1238 && ( new HookRunner( $this->hookContainer ) )->onEchoCanAbortNewMessagesAlert()
1239 ) {
1240 // hide new messages alert
1241 return false;
1242 } else {
1243 // show new messages alert
1244 return true;
1245 }
1246 }
1247
1248 /**
1249 * Handler for RollbackComplete hook.
1250 * @see https://www.mediawiki.org/wiki/Manual:Hooks/RollbackComplete
1251 *
1252 * @param WikiPage $wikiPage The article that was edited
1253 * @param UserIdentity $agent The user who did the rollback
1254 * @param RevisionRecord $newRevision The revision the page was reverted back to
1255 * @param RevisionRecord $oldRevision The revision of the top edit that was reverted
1256 */
1257 public function onRollbackComplete(
1258 $wikiPage,
1259 $agent,
1260 $newRevision,
1261 $oldRevision
1262 ) {
1263 $revertedUser = $oldRevision->getUser();
1264 $latestRevision = $wikiPage->getRevisionRecord();
1265
1266 if (
1267 $revertedUser &&
1268 // No notifications for anonymous users
1269 $revertedUser->isRegistered() &&
1270 // No notifications for null rollbacks
1271 !$oldRevision->hasSameContent( $newRevision )
1272 ) {
1273 Event::create( [
1274 'type' => 'reverted',
1275 'title' => $wikiPage->getTitle(),
1276 'extra' => [
1277 'revid' => $latestRevision->getId(),
1278 'reverted-user-id' => $revertedUser->getId(),
1279 'reverted-revision-id' => $oldRevision->getId(),
1280 'method' => 'rollback',
1281 ],
1282 'agent' => $agent,
1283 ] );
1284 }
1285 }
1286
1287 /**
1288 * Handler for UserSaveSettings hook.
1289 * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserSaveSettings
1290 * @param User $user whose settings were saved
1291 */
1292 public function onUserSaveSettings( $user ) {
1293 // Extensions like AbuseFilter might create an account, but
1294 // the tables we need might not exist. Bug 57335
1295 if ( !defined( 'MW_UPDATER' ) ) {
1296 // Reset the notification count since it may have changed due to user
1297 // option changes. This covers both explicit changes in the preferences
1298 // and changes made through the options API (since both call this hook).
1299 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
1300 if ( !$user->isRegistered() ) {
1301 // It's possible the user account was deleted before the deferred
1302 // update runs (T318081)
1303 return;
1304 }
1305 NotifUser::newFromUser( $user )->resetNotificationCount();
1306 } );
1307 }
1308 }
1309
1310 /**
1311 * Some of Echo's subscription user preferences are mapped to existing user preferences defined in
1312 * core MediaWiki. This returns the map of Echo preference names to core preference names.
1313 *
1314 * @return array
1315 */
1316 public static function getVirtualUserOptions() {
1317 $config = MediaWikiServices::getInstance()->getMainConfig();
1318 $options = [];
1319 $options['echo-subscriptions-email-edit-user-talk'] = 'enotifusertalkpages';
1320 if ( $config->get( ConfigNames::WatchlistNotifications ) ) {
1321 $options['echo-subscriptions-email-watchlist'] = 'enotifwatchlistpages';
1322 $options['echo-subscriptions-email-minor-watchlist'] = 'enotifminoredits';
1323 }
1324 return $options;
1325 }
1326
1327 /**
1328 * Handler for LoadUserOptions hook.
1329 * @see https://www.mediawiki.org/wiki/Manual:Hooks/LoadUserOptions
1330 * @param UserIdentity $user User whose options were loaded
1331 * @param array &$options Options can be modified
1332 */
1333 public function onLoadUserOptions( UserIdentity $user, &$options ): void {
1334 foreach ( self::getVirtualUserOptions() as $echoPref => $mwPref ) {
1335 // Use the existing core option's value for the Echo option
1336 if ( isset( $options[ $mwPref ] ) ) {
1337 $options[ $echoPref ] = $options[ $mwPref ];
1338 }
1339 }
1340 }
1341
1342 /**
1343 * Handler for SaveUserOptions hook.
1344 * @see https://www.mediawiki.org/wiki/Manual:Hooks/SaveUserOptions
1345 * @param UserIdentity $user User whose options are being saved
1346 * @param array &$modifiedOptions Options can be modified
1347 * @param array $originalOptions
1348 */
1349 public function onSaveUserOptions( UserIdentity $user, array &$modifiedOptions, array $originalOptions ) {
1350 foreach ( self::getVirtualUserOptions() as $echoPref => $mwPref ) {
1351 // Save virtual option values in corresponding real option values
1352 if ( isset( $modifiedOptions[ $echoPref ] ) ) {
1353 $modifiedOptions[ $mwPref ] = $modifiedOptions[ $echoPref ];
1354 unset( $modifiedOptions[ $echoPref ] );
1355 }
1356 }
1357 }
1358
1359 /**
1360 * Convert all values in an array to integers and filter out zeroes.
1361 *
1362 * @param array $numbers
1363 *
1364 * @return int[]
1365 */
1366 protected static function mapToInt( array $numbers ) {
1367 $data = [];
1368
1369 foreach ( $numbers as $value ) {
1370 $int = intval( $value );
1371 if ( $int === 0 ) {
1372 continue;
1373 }
1374 $data[] = $int;
1375 }
1376
1377 return $data;
1378 }
1379
1380 /**
1381 * Handler for UserClearNewTalkNotification hook.
1382 * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserClearNewTalkNotification
1383 * @param UserIdentity $user User whose talk page notification should be marked as read
1384 * @param int $oldid
1385 */
1386 public function onUserClearNewTalkNotification( $user, $oldid ) {
1387 if ( $user->isRegistered() ) {
1388 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
1389 NotifUser::newFromUser( $user )->clearUserTalkNotifications();
1390 } );
1391 }
1392 }
1393
1394 /**
1395 * Handler for EmailUserComplete hook.
1396 * @see https://www.mediawiki.org/wiki/Manual:Hooks/EmailUserComplete
1397 * @param MailAddress $address Adress of receiving user
1398 * @param MailAddress $from Adress of sending user
1399 * @param string $subject Subject of the mail
1400 * @param string $text Text of the mail
1401 */
1402 public function onEmailUserComplete( $address, $from, $subject, $text ) {
1403 if ( $from->name === $address->name ) {
1404 // nothing to notify
1405 return;
1406 }
1407 $userTo = User::newFromName( $address->name );
1408 $userFrom = User::newFromName( $from->name );
1409
1410 $autoSubject = wfMessage( 'defemailsubject', $from->name )->inContentLanguage()->text();
1411 if ( $subject === $autoSubject ) {
1412 $autoFooter = "\n\n-- \n" . wfMessage( 'emailuserfooter', $from->name, $address->name )
1413 ->inContentLanguage()->text();
1414 $textWithoutFooter = preg_replace( '/' . preg_quote( $autoFooter, '/' ) . '$/', '', $text );
1415 $preview = $this->contentLanguage->truncateForVisual( $textWithoutFooter, 125 );
1416 } else {
1417 $preview = $subject;
1418 }
1419
1420 Event::create( [
1421 'type' => 'emailuser',
1422 'extra' => [
1423 'to-user-id' => $userTo->getId(),
1424 'preview' => $preview,
1425 ],
1426 'agent' => $userFrom,
1427 ] );
1428 }
1429
1430 /**
1431 * Sets custom login message for redirect from notification page
1432 *
1433 * @param array &$messages
1434 */
1435 public function onLoginFormValidErrorMessages( array &$messages ) {
1436 $messages[] = 'echo-notification-loginrequired';
1437 }
1438
1439 public static function getConfigVars( RL\Context $context, Config $config ) {
1440 return [
1441 'EchoMaxNotificationCount' => NotifUser::MAX_BADGE_COUNT,
1442 'EchoPollForUpdates' => $config->get( ConfigNames::PollForUpdates )
1443 ];
1444 }
1445
1446 /**
1447 * @param WikiPage $article
1448 * @param User $user
1449 * @param string $reason
1450 * @param int $articleId
1451 * @param Content|null $content
1452 * @param LogEntry $logEntry
1453 * @param int $archivedRevisionCount
1454 */
1455 public function onArticleDeleteComplete(
1456 $article,
1457 $user,
1458 $reason,
1459 $articleId,
1460 $content,
1461 $logEntry,
1462 $archivedRevisionCount
1463 ) {
1464 DeferredUpdates::addCallableUpdate( static function () use ( $articleId ) {
1465 $eventMapper = new EventMapper();
1466 $eventIds = $eventMapper->fetchIdsByPage( $articleId );
1467 ModerationController::moderate( $eventIds, true );
1468 } );
1469 }
1470
1471 /**
1472 * @param Title $title
1473 * @param bool $create
1474 * @param string $comment
1475 * @param int $oldPageId
1476 * @param array $restoredPages
1477 */
1478 public function onArticleUndelete( $title, $create, $comment, $oldPageId, $restoredPages ) {
1479 if ( $create ) {
1480 DeferredUpdates::addCallableUpdate( static function () use ( $oldPageId ) {
1481 $eventMapper = new EventMapper();
1482 $eventIds = $eventMapper->fetchIdsByPage( $oldPageId );
1483 ModerationController::moderate( $eventIds, false );
1484 } );
1485 }
1486 }
1487
1488 /**
1489 * Handler for SpecialMuteModifyFormFields hook
1490 *
1491 * @param UserIdentity|null $target
1492 * @param User $user
1493 * @param array &$fields
1494 */
1495 public function onSpecialMuteModifyFormFields( $target, $user, &$fields ) {
1496 $echoPerUserBlacklist = $this->config->get( ConfigNames::PerUserBlacklist );
1497 if ( $echoPerUserBlacklist ) {
1498 $id = $target ? $this->centralIdLookup->centralIdFromLocalUser( $target ) : 0;
1499 $notificationList = $this->userOptionsManager->getOption( $user, 'echo-notifications-blacklist' );
1500 $list = $notificationList ? MultiUsernameFilter::splitIds(
1501 $notificationList
1502 ) : [];
1503 $fields[ 'echo-notifications-blacklist'] = [
1504 'type' => 'check',
1505 'label-message' => [
1506 'echo-specialmute-label-mute-notifications',
1507 $target ? $target->getName() : ''
1508 ],
1509 'default' => in_array( $id, $list, true ),
1510 ];
1511 }
1512 }
1513
1514 /**
1515 * @param RecentChange $change
1516 * @return bool|void
1517 */
1518 public function onRecentChange_save( $change ) {
1519 if ( !$this->config->get( 'EchoWatchlistNotifications' ) ) {
1520 return;
1521 }
1522 if ( $change->getAttribute( 'rc_minor' ) ) {
1523 $type = 'minor-watchlist-change';
1524 } else {
1525 $type = 'watchlist-change';
1526 }
1527 Event::create( [
1528 'type' => $type,
1529 'title' => $change->getTitle(),
1530 'extra' => [
1531 'page_title' => $change->getPage()->getDBkey(),
1532 'page_namespace' => $change->getPage()->getNamespace(),
1533 'revid' => $change->getAttribute( "rc_this_oldid" ),
1534 'logid' => $change->getAttribute( "rc_logid" ),
1535 'status' => $change->mExtra["pageStatus"],
1536 'timestamp' => $change->getAttribute( "rc_timestamp" ),
1537 'emailonce' => $this->config->get( ConfigNames::WatchlistEmailOncePerPage ),
1538 ],
1539 'agent' => $change->getPerformerIdentity(),
1540 ] );
1541 }
1542
1543 /**
1544 * Hook handler for ApiMain::moduleManager.
1545 * Used here to put the echopushsubscriptions API module behind our push feature flag.
1546 * TODO: Register this the usual way in extension.json when we don't need the feature flag
1547 * anymore.
1548 * @param ApiModuleManager $moduleManager
1549 */
1550 public function onApiMain__ModuleManager( $moduleManager ) {
1551 $pushEnabled = $this->config->get( 'EchoEnablePush' );
1552 if ( $pushEnabled ) {
1553 $moduleManager->addModule(
1554 'echopushsubscriptions',
1555 'action',
1556 ApiEchoPushSubscriptions::class
1557 );
1558 }
1559 }
1560
1561 }