Debian Codegraph @

extensions/Echo/includes/NotifUser.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications;
4
5 use InvalidArgumentException;
6 use MediaWiki\Extension\Notifications\Gateway\UserNotificationGateway;
7 use MediaWiki\Extension\Notifications\Mapper\NotificationMapper;
8 use MediaWiki\Extension\Notifications\Mapper\TargetPageMapper;
9 use MediaWiki\Extension\Notifications\Model\Notification;
10 use MediaWiki\MediaWikiServices;
11 use MediaWiki\Request\WebRequest;
12 use MediaWiki\User\CentralId\CentralIdLookup;
13 use MediaWiki\User\Options\UserOptionsLookup;
14 use MediaWiki\User\UserFactory;
15 use MediaWiki\User\UserIdentity;
16 use MediaWiki\Utils\MWTimestamp;
17 use MediaWiki\WikiMap\WikiMap;
18 use Wikimedia\ObjectCache\WANObjectCache;
19 use Wikimedia\Rdbms\Database;
20 use Wikimedia\Rdbms\ReadOnlyMode;
21
22 /**
23 * Entity that represents a notification target user
24 */
25 class NotifUser {
26
27 /**
28 * Notification target user
29 * @var UserIdentity
30 */
31 private $mUser;
32
33 /**
34 * Object cache
35 * @var WANObjectCache
36 */
37 private $cache;
38
39 /**
40 * Database access gateway
41 * @var UserNotificationGateway
42 */
43 private $userNotifGateway;
44
45 /**
46 * Notification mapper
47 * @var NotificationMapper
48 */
49 private $notifMapper;
50
51 /**
52 * Target page mapper
53 * @var TargetPageMapper
54 */
55 private $targetPageMapper;
56
57 /**
58 * @var ForeignNotifications|null
59 */
60 private $foreignNotifications;
61
62 /**
63 * @var array[]|null
64 */
65 private $localCountsAndTimestamps;
66
67 /**
68 * @var array[]|null
69 */
70 private $globalCountsAndTimestamps;
71
72 /**
73 * @var UserOptionsLookup
74 */
75 private $userOptionsLookup;
76
77 /**
78 * @var UserFactory
79 */
80 private $userFactory;
81
82 /**
83 * @var ReadOnlyMode
84 */
85 private $readOnlyMode;
86
87 // The max notification count shown in badge
88
89 // The max number shown in bundled message, eg, <user> and 99+ others <action>.
90 // This is really a totally separate thing, and could be its own constant.
91
92 // WARNING: If you change this, you should also change all references in the
93 // i18n messages (100 and 99) in all repositories using Echo.
94 public const MAX_BADGE_COUNT = 99;
95
96 private const CACHE_TTL = 86400;
97 private const CACHE_KEY = 'echo-notification-counts';
98 private const CHECK_KEY = 'echo-notification-updated';
99
100 /**
101 * Usually client code doesn't need to initialize the object directly
102 * because it could be obtained from factory method newFromUser()
103 */
104 public function __construct(
105 UserIdentity $user,
106 WANObjectCache $cache,
107 UserNotificationGateway $userNotifGateway,
108 NotificationMapper $notifMapper,
109 TargetPageMapper $targetPageMapper,
110 UserOptionsLookup $userOptionsLookup,
111 UserFactory $userFactory,
112 ReadOnlyMode $readOnlyMode
113 ) {
114 $this->mUser = $user;
115 $this->userNotifGateway = $userNotifGateway;
116 $this->cache = $cache;
117 $this->notifMapper = $notifMapper;
118 $this->targetPageMapper = $targetPageMapper;
119 $this->userOptionsLookup = $userOptionsLookup;
120 $this->userFactory = $userFactory;
121 $this->readOnlyMode = $readOnlyMode;
122 }
123
124 /**
125 * Factory method. The caller should make sure that the user is registered.
126 * @param UserIdentity $user
127 * @return NotifUser
128 */
129 public static function newFromUser( UserIdentity $user ) {
130 if ( !$user->isRegistered() ) {
131 throw new InvalidArgumentException( 'User must be logged in to view notification!' );
132 }
133 $services = MediaWikiServices::getInstance();
134 return new NotifUser(
135 $user,
136 $services->getMainWANObjectCache(),
137 new UserNotificationGateway(
138 $user,
139 DbFactory::newFromDefault(),
140 $services->getMainConfig()
141 ),
142 new NotificationMapper(),
143 new TargetPageMapper(),
144 $services->getUserOptionsLookup(),
145 $services->getUserFactory(),
146 $services->getReadOnlyMode()
147 );
148 }
149
150 /**
151 * Mark all edit-user-talk notifications as read. This is called when a user visits their user talk page.
152 */
153 public function clearUserTalkNotifications() {
154 $this->markRead(
155 $this->userNotifGateway->getUnreadNotifications(
156 'edit-user-talk'
157 )
158 );
159 }
160
161 /**
162 * Get message count for this user.
163 *
164 * @return int
165 */
166 public function getMessageCount() {
167 return $this->getNotificationCount( AttributeManager::MESSAGE );
168 }
169
170 /**
171 * Get alert count for this user.
172 *
173 * @return int
174 */
175 public function getAlertCount() {
176 return $this->getNotificationCount( AttributeManager::ALERT );
177 }
178
179 /**
180 * Get the number of unread local notifications in a given section. This does not include
181 * foreign notifications, even if the user has cross-wiki notifications enabled.
182 *
183 * @param string $section Notification section
184 * @return int
185 */
186 public function getLocalNotificationCount( $section = AttributeManager::ALL ) {
187 return $this->getNotificationCount( $section, false );
188 }
189
190 /**
191 * Retrieves number of unread notifications that a user has, would return
192 * NotifUser::MAX_BADGE_COUNT + 1 at most.
193 *
194 * If $wgEchoCrossWikiNotifications is disabled, the $global parameter is ignored.
195 *
196 * @param string $section Notification section
197 * @param bool|string $global Whether to include foreign notifications.
198 * If set to 'preference', uses the user's preference.
199 * @return int
200 */
201 public function getNotificationCount( $section = AttributeManager::ALL, $global = 'preference' ) {
202 if ( !$this->mUser->isRegistered() ) {
203 return 0;
204 }
205
206 global $wgEchoCrossWikiNotifications;
207 if ( !$wgEchoCrossWikiNotifications ) {
208 // Ignore the $global parameter
209 $global = false;
210 }
211
212 if ( $global === 'preference' ) {
213 $global = $this->getForeignNotifications()->isEnabledByUser();
214 }
215
216 $data = $this->getCountsAndTimestamps( $global );
217 if ( $global && $data['global'] === null ) {
218 // No global user exists, no data. Use only local count
219 $global = false;
220 }
221 $count = $data[$global ? 'global' : 'local'][$section]['count'];
222 return (int)$count;
223 }
224
225 /**
226 * Get the timestamp of the latest unread alert
227 *
228 * @return bool|MWTimestamp Timestamp of latest unread alert, or false if there are no unread alerts.
229 */
230 public function getLastUnreadAlertTime() {
231 return $this->getLastUnreadNotificationTime( AttributeManager::ALERT );
232 }
233
234 /**
235 * Get the timestamp of the latest unread message
236 *
237 * @return bool|MWTimestamp
238 */
239 public function getLastUnreadMessageTime() {
240 return $this->getLastUnreadNotificationTime( AttributeManager::MESSAGE );
241 }
242
243 /**
244 * Returns the timestamp of the last unread notification.
245 *
246 * If $wgEchoCrossWikiNotifications is disabled, the $global parameter is ignored.
247 *
248 * @param string $section Notification section
249 * @param bool|string $global Whether to include foreign notifications.
250 * If set to 'preference', uses the user's preference.
251 * @return bool|MWTimestamp Timestamp of latest unread message, or false if there are no unread messages.
252 */
253 public function getLastUnreadNotificationTime( $section = AttributeManager::ALL, $global = 'preference' ) {
254 if ( !$this->mUser->isRegistered() ) {
255 return false;
256 }
257
258 global $wgEchoCrossWikiNotifications;
259 if ( !$wgEchoCrossWikiNotifications ) {
260 // Ignore the $global parameter
261 $global = false;
262 }
263
264 if ( $global === 'preference' ) {
265 $global = $this->getForeignNotifications()->isEnabledByUser();
266 }
267
268 $data = $this->getCountsAndTimestamps( $global );
269 if ( $global && $data['global'] === null ) {
270 // No global user exists, no data. Use only local count
271 $global = false;
272 }
273 $timestamp = $data[$global ? 'global' : 'local'][$section]['timestamp'];
274 return $timestamp === -1 ? false : new MWTimestamp( $timestamp );
275 }
276
277 /**
278 * Mark one or more notifications read for a user.
279 * @param array $eventIds Array of event IDs to mark read
280 * @return bool Returns true when data has been updated in DB, false on
281 * failure, or when there was nothing to update
282 */
283 public function markRead( $eventIds ) {
284 $eventIds = array_filter( (array)$eventIds, 'is_numeric' );
285 if ( !$eventIds || $this->readOnlyMode->isReadOnly() ) {
286 return false;
287 }
288
289 $updated = $this->userNotifGateway->markRead( $eventIds );
290 if ( $updated ) {
291 // Update notification count in cache
292 $this->resetNotificationCount();
293
294 // After this 'mark read', is there any unread edit-user-talk
295 // remaining? If not, we should clear the newtalk flag.
296 $talkPageNotificationManager = MediaWikiServices::getInstance()
297 ->getTalkPageNotificationManager();
298 if ( $talkPageNotificationManager->userHasNewMessages( $this->mUser ) ) {
299 $attributeManager = Services::getInstance()->getAttributeManager();
300 $categoryMap = $attributeManager->getEventsByCategory();
301 $usertalkTypes = $categoryMap['edit-user-talk'];
302 $unreadEditUserTalk = $this->notifMapper->fetchUnreadByUser(
303 $this->mUser,
304 1,
305 null,
306 $usertalkTypes,
307 null,
308 DB_PRIMARY
309 );
310 if ( $unreadEditUserTalk === [] ) {
311 $talkPageNotificationManager->removeUserHasNewMessages( $this->mUser );
312 }
313 }
314 }
315
316 return $updated;
317 }
318
319 /**
320 * Mark one or more notifications unread for a user.
321 * @param array $eventIds Array of event IDs to mark unread
322 * @return bool Returns true when data has been updated in DB, false on
323 * failure, or when there was nothing to update
324 */
325 public function markUnRead( $eventIds ) {
326 $eventIds = array_filter( (array)$eventIds, 'is_numeric' );
327 if ( !$eventIds || $this->readOnlyMode->isReadOnly() ) {
328 return false;
329 }
330
331 $updated = $this->userNotifGateway->markUnRead( $eventIds );
332 if ( $updated ) {
333 // Update notification count in cache
334 $this->resetNotificationCount();
335
336 // After this 'mark unread', is there any unread edit-user-talk?
337 // If so, we should add the edit-user-talk flag
338 $talkPageNotificationManager = MediaWikiServices::getInstance()
339 ->getTalkPageNotificationManager();
340 if ( !$talkPageNotificationManager->userHasNewMessages( $this->mUser ) ) {
341 $attributeManager = Services::getInstance()->getAttributeManager();
342 $categoryMap = $attributeManager->getEventsByCategory();
343 $usertalkTypes = $categoryMap['edit-user-talk'];
344 $unreadEditUserTalk = $this->notifMapper->fetchUnreadByUser(
345 $this->mUser,
346 1,
347 null,
348 $usertalkTypes,
349 null,
350 DB_PRIMARY
351 );
352 if ( $unreadEditUserTalk !== [] ) {
353 $talkPageNotificationManager->setUserHasNewMessages( $this->mUser );
354 }
355 }
356 }
357
358 return $updated;
359 }
360
361 /**
362 * Attempt to mark all or sections of notifications as read, this only
363 * updates up to $wgEchoMaxUpdateCount records per request, see more
364 * detail about this in Echo.php, the other reason is that mediawiki
365 * database interface doesn't support updateJoin() that would update
366 * across multiple tables, we would visit this later
367 *
368 * @param string[] $sections
369 * @return bool
370 */
371 public function markAllRead( array $sections = [ AttributeManager::ALL ] ) {
372 if ( $this->readOnlyMode->isReadOnly() ) {
373 return false;
374 }
375
376 global $wgEchoMaxUpdateCount;
377
378 // Mark all sections as read if this is the case
379 if ( in_array( AttributeManager::ALL, $sections ) ) {
380 $sections = AttributeManager::$sections;
381 }
382
383 $attributeManager = Services::getInstance()->getAttributeManager();
384 $eventTypes = $attributeManager->getUserEnabledEventsBySections( $this->mUser, 'web', $sections );
385
386 $notifs = $this->notifMapper->fetchUnreadByUser( $this->mUser, $wgEchoMaxUpdateCount, null, $eventTypes );
387
388 $eventIds = array_filter(
389 array_map( static function ( Notification $notif ) {
390 // This should not happen at all, but use 0 in
391 // such case so to keep the code running
392 if ( $notif->getEvent() ) {
393 return $notif->getEvent()->getId();
394 }
395 return 0;
396 }, $notifs )
397 );
398
399 $updated = $this->markRead( $eventIds );
400 if ( $updated ) {
401 // Delete records from echo_target_page
402 /**
403 * Keep the 'echo_target_page' records so they can be used for moderation.
404 */
405 // $this->targetPageMapper->deleteByUserEvents( $this->mUser, $eventIds );
406 }
407
408 return $updated;
409 }
410
411 /**
412 * Mark one of more notifications as read on a foreign wiki.
413 *
414 * @param int[] $eventIds Event IDs to mark as read
415 * @param string $wiki Wiki name
416 * @param WebRequest|null $originalRequest Original request data to be sent with these requests
417 */
418 public function markReadForeign( array $eventIds, $wiki, ?WebRequest $originalRequest = null ) {
419 $foreignReq = new ForeignWikiRequest(
420 $this->userFactory->newFromUserIdentity( $this->mUser ),
421 [
422 'action' => 'echomarkread',
423 'list' => implode( '|', $eventIds ),
424 ],
425 [ $wiki ],
426 'wikis',
427 'csrf'
428 );
429 $foreignReq->execute( $originalRequest );
430 }
431
432 /**
433 * Get information about a set of unread notifications on a foreign wiki.
434 *
435 * @param int[] $eventIds Event IDs to look up. Only unread notifications can be found.
436 * @param string $wiki Wiki name
437 * @param WebRequest|null $originalRequest Original request data to be sent with these requests
438 * @return array[] Array of notification data as returned by api.php, keyed by event ID
439 */
440 public function getForeignNotificationInfo( array $eventIds, $wiki, ?WebRequest $originalRequest = null ) {
441 $foreignReq = new ForeignWikiRequest(
442 $this->userFactory->newFromUserIdentity( $this->mUser ),
443 [
444 'action' => 'query',
445 'meta' => 'notifications',
446 'notprop' => 'list',
447 'notfilter' => '!read',
448 'notlimit' => 'max'
449 ],
450 [ $wiki ],
451 'notwikis'
452 );
453 $foreignResults = $foreignReq->execute( $originalRequest );
454 $list = $foreignResults[$wiki]['query']['notifications']['list'] ?? [];
455
456 $result = [];
457 foreach ( $list as $notif ) {
458 if ( in_array( $notif['id'], $eventIds ) ) {
459 $result[$notif['id']] = $notif;
460 }
461 }
462 return $result;
463 }
464
465 /**
466 * Invalidate cache and update echo_unread_wikis if x-wiki notifications is enabled.
467 *
468 * This updates the user's touched timestamp, as well as the value returned by getGlobalUpdateTime().
469 *
470 * NOTE: Consider calling this function from a deferred update, since it will read from and write to
471 * the primary DB if cross-wiki notifications are enabled.
472 */
473 public function resetNotificationCount() {
474 global $wgEchoCrossWikiNotifications;
475
476 // Delete cached local counts and timestamps
477 $localMemcKey = $this->getMemcKey( self::CACHE_KEY );
478 $this->cache->delete( $localMemcKey );
479
480 // Update the user touched timestamp for the local user
481 $this->userFactory->newFromUserIdentity( $this->mUser )->invalidateCache();
482
483 if ( $wgEchoCrossWikiNotifications ) {
484 // Delete cached global counts and timestamps
485 $globalMemcKey = $this->getGlobalMemcKey( self::CACHE_KEY );
486 if ( $globalMemcKey !== false ) {
487 $this->cache->delete( $globalMemcKey );
488 }
489
490 $uw = UnreadWikis::newFromUser( $this->mUser );
491 if ( $uw ) {
492 // Immediately compute new local counts and timestamps
493 $newLocalData = $this->computeLocalCountsAndTimestamps( DB_PRIMARY );
494 // Write the new values to the echo_unread_wikis table
495 $alertTs = $newLocalData[AttributeManager::ALERT]['timestamp'];
496 $messageTs = $newLocalData[AttributeManager::MESSAGE]['timestamp'];
497 $uw->updateCount(
498 WikiMap::getCurrentWikiId(),
499 $newLocalData[AttributeManager::ALERT]['count'],
500 $alertTs === -1 ? false : new MWTimestamp( $alertTs ),
501 $newLocalData[AttributeManager::MESSAGE]['count'],
502 $messageTs === -1 ? false : new MWTimestamp( $messageTs )
503 );
504 // We could set() $newLocalData into the cache here, but we don't because that seems risky;
505 // instead we let it be recomputed on demand
506 }
507
508 // Update the global touched timestamp
509 $checkKey = $this->getGlobalMemcKey( self::CHECK_KEY );
510 if ( $checkKey ) {
511 $this->cache->touchCheckKey( $checkKey );
512 }
513 }
514 }
515
516 /**
517 * Get the timestamp of the last time the global notification counts/timestamps were updated, if available.
518 *
519 * If the timestamp of the last update is not known, this will return the current timestamp.
520 * If the user is not attached, this will return false.
521 *
522 * @return string|false MW timestamp of the last update, or false if the user is not attached
523 */
524 public function getGlobalUpdateTime() {
525 $key = $this->getGlobalMemcKey( self::CHECK_KEY );
526 if ( $key === false ) {
527 return false;
528 }
529 return wfTimestamp( TS_MW, $this->cache->getCheckKeyTime( $key ) );
530 }
531
532 /**
533 * Get the number of notifications in each section, and the timestamp of the latest notification in
534 * each section. This returns the raw data structure that is stored in the cache; unless you want
535 * all of this information, you're probably looking for getNotificationCount(),
536 * getLastUnreadNotificationTime() or one of its wrappers.
537 *
538 * The returned data structure looks like:
539 * [
540 * 'local' => [
541 * 'alert' => [ 'count' => N, 'timestamp' => TS ],
542 * 'message' => [ 'count' = N, 'timestamp' => TS ],
543 * 'all' => [ 'count' => N, 'timestamp' => TS ],
544 * ],
545 * 'global' => [
546 * 'alert' => [ 'count' => N, 'timestamp' => TS ],
547 * 'message' => [ 'count' = N, 'timestamp' => TS ],
548 * 'all' => [ 'count' => N, 'timestamp' => TS ],
549 * ],
550 * ]
551 * Where N is a number and TS is a timestamp in TS_MW format or -1. If $includeGlobal is false,
552 * the 'global' key will not be present. It could be null, if no global user exists.
553 *
554 * @param bool $includeGlobal Whether to include cross-wiki notifications as well
555 * @return array
556 */
557 public function getCountsAndTimestamps( $includeGlobal = false ) {
558 if ( $this->localCountsAndTimestamps === null ) {
559 $this->localCountsAndTimestamps = $this->cache->getWithSetCallback(
560 $this->getMemcKey( self::CACHE_KEY ),
561 self::CACHE_TTL,
562 function ( $oldValue, &$ttl, array &$setOpts ) {
563 $dbr = $this->userNotifGateway->getDB( DB_REPLICA );
564 $setOpts += Database::getCacheSetOptions( $dbr );
565 return $this->computeLocalCountsAndTimestamps();
566 }
567 );
568 }
569 $result = [ 'local' => $this->localCountsAndTimestamps ];
570
571 if ( $includeGlobal ) {
572 if ( $this->globalCountsAndTimestamps === null ) {
573 $memcKey = $this->getGlobalMemcKey( self::CACHE_KEY );
574 // If getGlobalMemcKey returns false, we don't have a global user ID
575 // In that case, don't compute data that we can't cache or store
576 if ( $memcKey !== false ) {
577 $this->globalCountsAndTimestamps = $this->cache->getWithSetCallback(
578 $memcKey,
579 self::CACHE_TTL,
580 function ( $oldValue, &$ttl, array &$setOpts ) {
581 $dbr = $this->userNotifGateway->getDB( DB_REPLICA );
582 $setOpts += Database::getCacheSetOptions( $dbr );
583 return $this->computeGlobalCountsAndTimestamps();
584 }
585 );
586 }
587 }
588 $result['global'] = $this->globalCountsAndTimestamps;
589 }
590 return $result;
591 }
592
593 /**
594 * Compute the counts and timestamps for the local notifications in each section.
595 * @param int $dbSource DB_REPLICA or DB_PRIMARY
596 * @return array[] [ 'alert' => [ 'count' => N, 'timestamp' => TS ], ... ]
597 */
598 protected function computeLocalCountsAndTimestamps( $dbSource = DB_REPLICA ) {
599 $attributeManager = Services::getInstance()->getAttributeManager();
600 $result = [];
601 $totals = [ 'count' => 0, 'timestamp' => -1 ];
602
603 foreach ( AttributeManager::$sections as $section ) {
604 $eventTypesToLoad = $attributeManager->getUserEnabledEventsBySections(
605 $this->mUser,
606 'web',
607 [ $section ]
608 );
609
610 $count = $this->userNotifGateway->getCappedNotificationCount(
611 $dbSource,
612 $eventTypesToLoad,
613 self::MAX_BADGE_COUNT + 1
614 );
615 $result[$section]['count'] = $count;
616 $totals['count'] += $count;
617
618 $notifications = $this->notifMapper->fetchUnreadByUser(
619 $this->mUser,
620 1,
621 null,
622 $eventTypesToLoad,
623 null,
624 $dbSource
625 );
626 if ( $notifications ) {
627 $notification = reset( $notifications );
628 $timestamp = $notification->getTimestamp();
629 } else {
630 $timestamp = -1;
631 }
632 $result[$section]['timestamp'] = $timestamp;
633 $totals['timestamp'] = max( $totals['timestamp'], $timestamp );
634 }
635 $totals['count'] = self::capNotificationCount( $totals['count'] );
636 $result[AttributeManager::ALL] = $totals;
637 return $result;
638 }
639
640 /**
641 * Compute the global counts and timestamps for each section.
642 *
643 * This calls getCountsAndTimestamps() to get data about local notifications, which may end up
644 * calling computeLocalCountsAndTimestamps() if there's a cache miss.
645 * @return array[] [ 'alert' => [ 'count' => N, 'timestamp' => TS ], ... ]
646 */
647 protected function computeGlobalCountsAndTimestamps() {
648 $localData = $this->getCountsAndTimestamps()['local'];
649 $result = [];
650 $totals = [ 'count' => 0, 'timestamp' => -1 ];
651 foreach ( AttributeManager::$sections as $section ) {
652 $localCount = $localData[$section]['count'];
653 $globalCount = self::capNotificationCount( $localCount + $this->getForeignCount( $section ) );
654 $result[$section]['count'] = $globalCount;
655 $totals['count'] += $globalCount;
656
657 $localTimestamp = $localData[$section]['timestamp'];
658 $foreignTimestamp = $this->getForeignTimestamp( $section );
659 $globalTimestamp = max(
660 $localTimestamp,
661 $foreignTimestamp ? $foreignTimestamp->getTimestamp( TS_MW ) : -1
662 );
663 $result[$section]['timestamp'] = $globalTimestamp;
664 $totals['timestamp'] = max( $totals['timestamp'], $globalTimestamp );
665 }
666 $totals['count'] = self::capNotificationCount( $totals['count'] );
667 $result[AttributeManager::ALL] = $totals;
668 return $result;
669 }
670
671 /**
672 * Get the user's email notification format
673 * @return string
674 */
675 public function getEmailFormat() {
676 global $wgAllowHTMLEmail;
677
678 if ( $wgAllowHTMLEmail ) {
679 return $this->userOptionsLookup->getOption( $this->mUser, 'echo-email-format' );
680 }
681
682 return EmailFormat::PLAIN_TEXT;
683 }
684
685 /**
686 * Build a cache key for local use (local to this wiki)
687 *
688 * @param string $key Key, typically prefixed with echo-notification-
689 * @return string Cache key
690 */
691 protected function getMemcKey( $key ) {
692 global $wgEchoCacheVersion;
693 return $this->cache->makeKey( $key, $this->mUser->getId(), $wgEchoCacheVersion );
694 }
695
696 /**
697 * Build a cache key for global use
698 *
699 * @param string $key Key, typically prefixed with echo-notification-
700 * @return string|false Memcached key, or false if one could not be generated
701 */
702 protected function getGlobalMemcKey( $key ) {
703 global $wgEchoCacheVersion;
704 $globalId = MediaWikiServices::getInstance()
705 ->getCentralIdLookup()
706 ->centralIdFromLocalUser( $this->mUser, CentralIdLookup::AUDIENCE_RAW );
707 if ( !$globalId ) {
708 return false;
709 }
710 return $this->cache->makeGlobalKey( $key, $globalId, $wgEchoCacheVersion );
711 }
712
713 /**
714 * Lazy-construct an ForeignNotifications instance. This instance is force-enabled, so it
715 * returns information about cross-wiki notifications even if the user has them disabled.
716 * @return ForeignNotifications
717 */
718 protected function getForeignNotifications() {
719 if ( !$this->foreignNotifications ) {
720 $this->foreignNotifications = new ForeignNotifications( $this->mUser, true );
721 }
722 return $this->foreignNotifications;
723 }
724
725 /**
726 * Get the number of foreign notifications in a given section.
727 * @param string $section One of AttributeManager::$sections
728 * @return int Number of foreign notifications
729 */
730 protected function getForeignCount( $section = AttributeManager::ALL ) {
731 return self::capNotificationCount(
732 $this->getForeignNotifications()->getCount( $section )
733 );
734 }
735
736 /**
737 * Get the timestamp of the most recent foreign notification in a given section.
738 * @param string $section One of AttributeManager::$sections
739 * @return MWTimestamp|false Timestamp of the most recent foreign notification, or false if
740 * there aren't any
741 */
742 protected function getForeignTimestamp( $section = AttributeManager::ALL ) {
743 return $this->getForeignNotifications()->getTimestamp( $section );
744 }
745
746 /**
747 * Helper function to produce the capped number of notifications
748 * based on the value of NotifUser::MAX_BADGE_COUNT
749 *
750 * @param int $number Raw notification count to cap
751 * @return int Capped notification count
752 */
753 public static function capNotificationCount( $number ) {
754 return min( $number, self::MAX_BADGE_COUNT + 1 );
755 }
756 }