Debian Codegraph @

extensions/Echo/includes/Formatters/EchoEventPresentationModel.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications\Formatters;
4
5 use InvalidArgumentException;
6 use JsonSerializable;
7 use MediaWiki\Extension\Notifications\Controller\NotificationController;
8 use MediaWiki\Extension\Notifications\Model\Event;
9 use MediaWiki\Language\Language;
10 use MediaWiki\MediaWikiServices;
11 use MediaWiki\Message\Message;
12 use MediaWiki\Revision\RevisionRecord;
13 use MediaWiki\SpecialPage\SpecialPage;
14 use MediaWiki\Title\Title;
15 use MediaWiki\User\User;
16 use MediaWiki\User\UserIdentity;
17 use MediaWiki\WikiMap\WikiMap;
18 use MessageLocalizer;
19 use Wikimedia\Message\MessageSpecifier;
20 use Wikimedia\Timestamp\TimestampException;
21
22 /**
23 * Class that returns structured data based
24 * on the provided event.
25 */
26 abstract class EchoEventPresentationModel implements JsonSerializable, MessageLocalizer {
27
28 /**
29 * Recommended length of usernames included in messages, in
30 * characters (not bytes).
31 */
32 private const USERNAME_RECOMMENDED_LENGTH = 20;
33
34 /**
35 * Recommended length of usernames used as link label, in
36 * characters (not bytes).
37 */
38 private const USERNAME_AS_LABEL_RECOMMENDED_LENGTH = 15;
39
40 /**
41 * Recommended length of page names included in messages, in
42 * characters (not bytes).
43 */
44 protected const PAGE_NAME_RECOMMENDED_LENGTH = 50;
45
46 /**
47 * Recommended length of page names used as link label, in
48 * characters (not bytes).
49 */
50 private const PAGE_NAME_AS_LABEL_RECOMMENDED_LENGTH = 15;
51
52 /**
53 * Recommended length of section titles included in messages, in
54 * characters (not bytes).
55 */
56 public const SECTION_TITLE_RECOMMENDED_LENGTH = 50;
57
58 /**
59 * @var Event
60 */
61 protected $event;
62
63 /**
64 * @var Language
65 */
66 protected $language;
67
68 /**
69 * @var string
70 */
71 protected $type;
72
73 /**
74 * @var User for permissions checking
75 */
76 private $user;
77
78 /**
79 * @var string 'web' or 'email'
80 */
81 private $distributionType;
82
83 /**
84 * @param Event $event
85 * @param Language $language
86 * @param User $user Only used for permissions checking and GENDER
87 * @param string $distributionType
88 */
89 protected function __construct(
90 Event $event,
91 Language $language,
92 User $user,
93 $distributionType
94 ) {
95 $this->event = $event;
96 $this->type = $event->getType();
97 $this->language = $language;
98 $this->user = $user;
99 $this->distributionType = $distributionType;
100 }
101
102 /**
103 * Convenience function to detect whether the event type
104 * has a presentation model available for rendering
105 *
106 * @param string $type event type
107 * @return bool
108 */
109 public static function supportsPresentationModel( $type ) {
110 global $wgEchoNotifications;
111 return isset( $wgEchoNotifications[$type]['presentation-model'] )
112 && class_exists( $wgEchoNotifications[$type]['presentation-model'] );
113 }
114
115 /**
116 * @param Event $event
117 * @param Language $language
118 * @param User $user
119 * @param string $distributionType 'web' or 'email'
120 * @return EchoEventPresentationModel
121 */
122 public static function factory(
123 Event $event,
124 Language $language,
125 User $user,
126 $distributionType = 'web'
127 ) {
128 global $wgEchoNotifications;
129 // @todo don't depend upon globals
130
131 /** @var class-string<EchoEventPresentationModel> $class */
132 $class = $wgEchoNotifications[$event->getType()]['presentation-model'];
133 return new $class( $event, $language, $user, $distributionType );
134 }
135
136 /**
137 * Get the type of event
138 *
139 * @return string
140 */
141 final public function getType() {
142 return $this->type;
143 }
144
145 /**
146 * Get the user receiving the notification
147 *
148 * @return User
149 */
150 final public function getUser() {
151 return $this->user;
152 }
153
154 /**
155 * Get the category of event
156 *
157 * @return string
158 */
159 final public function getCategory() {
160 return $this->event->getCategory();
161 }
162
163 /**
164 * @return string 'web' or 'email'
165 */
166 final public function getDistributionType() {
167 return $this->distributionType;
168 }
169
170 /**
171 * Equivalent to IContextSource::msg for the current
172 * language
173 *
174 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
175 * or a MessageSpecifier.
176 * @param mixed ...$params Normal message parameters
177 * @return Message
178 */
179 public function msg( $key, ...$params ) {
180 /**
181 * @var Message $msg
182 */
183 $msg = wfMessage( $key, ...$params );
184 $msg->inLanguage( $this->language );
185
186 // Notifications are considered UI (and should be in UI language, not
187 // content), and this flag is set false by inLanguage.
188 $msg->setInterfaceMessageFlag( true );
189
190 return $msg;
191 }
192
193 /**
194 * @return Event[]
195 */
196 final protected function getBundledEvents() {
197 return $this->event->getBundledEvents() ?: [];
198 }
199
200 /**
201 * Get the ids of the bundled notifications or false if it's not bundled
202 *
203 * @return int[]|false
204 */
205 public function getBundledIds() {
206 if ( $this->isBundled() ) {
207 return array_map( static function ( Event $event ) {
208 return $event->getId();
209 }, $this->getBundledEvents() );
210 }
211 return false;
212 }
213
214 /**
215 * This method returns true when there are bundled notifications, even if they are all
216 * in the same group according to getBundleGrouping(). For presentation purposes, you may
217 * want to check if getBundleCount( true, $yourCallback ) > 1 instead.
218 *
219 * @return bool Whether there are other notifications bundled with this one.
220 */
221 final protected function isBundled() {
222 return $this->getBundleCount() > 1;
223 }
224
225 /**
226 * Count the number of event groups in this bundle.
227 *
228 * By default, each event is in its own group, and this method returns the number of events.
229 * To group events differently, pass $groupCallback. For example, to group events with the
230 * same title together, use $callback = function ( $event ) { return $event->getTitle()->getPrefixedText(); }
231 *
232 * If $includeCurrent is false, all events in the same group as the current one will be ignored.
233 *
234 * @param bool $includeCurrent Include the current event (and its group)
235 * @param callable|null $groupCallback Callback that takes an Event and returns a grouping value
236 * @return int Number of bundled events or groups
237 * @throws InvalidArgumentException
238 */
239 final protected function getBundleCount( $includeCurrent = true, $groupCallback = null ) {
240 $events = array_merge( $this->getBundledEvents(), [ $this->event ] );
241 if ( $groupCallback ) {
242 if ( !is_callable( $groupCallback ) ) {
243 // If we pass an invalid callback to array_map(), it'll just throw a warning
244 // and return NULL, so $count ends up being 0 or -1. Instead of doing that,
245 // throw an exception.
246 throw new InvalidArgumentException( 'Invalid callback passed to getBundleCount' );
247 }
248 $events = array_unique( array_map( $groupCallback, $events ) );
249 }
250 $count = count( $events );
251
252 if ( !$includeCurrent ) {
253 $count--;
254 }
255 return $count;
256 }
257
258 /**
259 * Return the count of notifications bundled together.
260 *
261 * For parameters, see {@see EchoEventPresentationModel::getBundleCount}.
262 *
263 * @param bool $includeCurrent
264 * @param callable|null $groupCallback
265 * @return int count
266 */
267 final protected function getNotificationCountForOutput( $includeCurrent = true, $groupCallback = null ) {
268 $count = $this->getBundleCount( $includeCurrent, $groupCallback );
269 return NotificationController::getCappedNotificationCount( $count );
270 }
271
272 /**
273 * @return string The symbolic icon name as defined in $wgEchoNotificationIcons
274 */
275 abstract public function getIconType();
276
277 /**
278 * @return string Timestamp the event occurred at
279 */
280 final public function getTimestamp() {
281 return $this->event->getTimestamp();
282 }
283
284 /**
285 * Helper for Event::userCan
286 *
287 * @param int $type RevisionRecord::DELETED_* constant
288 * @return bool
289 */
290 final protected function userCan( $type ) {
291 return $this->event->userCan( $type, $this->user );
292 }
293
294 /**
295 * @return string[]|false ['wikitext to display', 'username for GENDER'], false if no agent
296 *
297 * We have to display wikitext so we can add CSS classes for revision deleted user.
298 * The goal of this function is for callers not to worry about whether
299 * the user is visible or not.
300 * @par Example:
301 * @code
302 * [ $formattedName, $genderName ] = $this->getAgentForOutput();
303 * $msg->params( $formattedName, $genderName );
304 * @endcode
305 */
306 final protected function getAgentForOutput() {
307 $agent = $this->event->getAgent();
308 if ( !$agent ) {
309 return false;
310 }
311
312 if ( $this->userCan( RevisionRecord::DELETED_USER ) ) {
313 // Not deleted
314 return [
315 $this->getTruncatedUsername( $agent ),
316 $agent->getName()
317 ];
318 } else {
319 // Deleted/hidden
320 $msg = $this->msg( 'rev-deleted-user' )->plain();
321 // HACK: Pass an invalid username to GENDER to force the default
322 return [ '<span class="history-deleted">' . $msg . '</span>', '[]' ];
323 }
324 }
325
326 /**
327 * Return a message with the given key and the agent's
328 * formatted name and name for GENDER as 1st and
329 * 2nd parameters.
330 * @param string $key
331 * @return Message
332 */
333 final protected function getMessageWithAgent( $key ) {
334 $msg = $this->msg( $key );
335 [ $formattedName, $genderName ] = $this->getAgentForOutput();
336 $msg->params( $formattedName, $genderName );
337 return $msg;
338 }
339
340 /**
341 * Get the viewing user's name for usage in GENDER
342 *
343 * @return string
344 */
345 final protected function getViewingUserForGender() {
346 return $this->user->getName();
347 }
348
349 /**
350 * @return array|null Link object to the user's page or Special:Contributions for anon users.
351 * Can be used for primary or secondary links.
352 * Same format as secondary link.
353 * Returns null if the current user cannot see the agent.
354 */
355 final protected function getAgentLink() {
356 return $this->getUserLink( $this->event->getAgent() );
357 }
358
359 /**
360 * To be overridden by subclasses if they are unable to render the
361 * notification, for example when a page is deleted.
362 * If this function returns false, no other methods will be called
363 * on the object.
364 *
365 * @return bool
366 */
367 public function canRender() {
368 return true;
369 }
370
371 /**
372 * @return string Message key that will be used in getHeaderMessage
373 */
374 protected function getHeaderMessageKey() {
375 return "notification-header-{$this->type}";
376 }
377
378 /**
379 * Get a message object and add the performer's name as
380 * a parameter. It is expected that subclasses will override
381 * this.
382 *
383 * @return Message
384 */
385 public function getHeaderMessage() {
386 return $this->getMessageWithAgent( $this->getHeaderMessageKey() );
387 }
388
389 /**
390 * @return string Message key that will be used in getCompactHeaderMessage
391 */
392 public function getCompactHeaderMessageKey() {
393 return "notification-compact-header-{$this->type}";
394 }
395
396 /**
397 * Get a message object and add the performer's name as
398 * a parameter. It is expected that subclasses will override
399 * this.
400 *
401 * This message should be more compact than the header message
402 * ( getHeaderMessage() ). It is displayed when a
403 * notification is part of an expanded bundle.
404 *
405 * @return Message
406 */
407 public function getCompactHeaderMessage() {
408 $msg = $this->getMessageWithAgent( $this->getCompactHeaderMessageKey() );
409 if ( $msg->isDisabled() ) {
410 // Back-compat for models that haven't been updated yet
411 $msg = $this->getHeaderMessage();
412 }
413
414 return $msg;
415 }
416
417 /**
418 * @return string Message key that will be used in getSubjectMessage
419 */
420 protected function getSubjectMessageKey() {
421 return "notification-subject-{$this->type}";
422 }
423
424 /**
425 * Get a message object and add the performer's name as
426 * a parameter. It is expected that subclasses will override
427 * this. The output of the message should be plaintext.
428 *
429 * This message is used as the subject line in
430 * single-notification emails.
431 *
432 * For backward compatibility, if this is not defined,
433 * the header message ( getHeaderMessage() ) is used instead.
434 *
435 * @return Message
436 */
437 public function getSubjectMessage() {
438 $msg = $this->getMessageWithAgent( $this->getSubjectMessageKey() );
439 $msg->params( $this->getViewingUserForGender() );
440 if ( $msg->isDisabled() ) {
441 // Back-compat for models that haven't been updated yet
442 $msg = $this->getHeaderMessage();
443 }
444
445 return $msg;
446 }
447
448 /**
449 * Get a message for the notification's body, false if it has no body
450 *
451 * @return bool|Message
452 */
453 public function getBodyMessage() {
454 return false;
455 }
456
457 /**
458 * Array of primary link details, with possibly-relative URL & label.
459 *
460 * @return array|false Array of link data, or false for no link:
461 * ['url' => (string) url, 'label' => (string) link text (non-escaped)]
462 */
463 abstract public function getPrimaryLink();
464
465 /**
466 * Like getPrimaryLink(), but with the URL altered to add ?markasread=XYZ. When this link is followed,
467 * the notification is marked as read.
468 *
469 * If the notification is a bundle, the notification IDs are added to the parameter value
470 * separated by a "|". If cross-wiki notifications are enabled, a markasreadwiki parameter is
471 * added.
472 *
473 * @return array|false
474 */
475 final public function getPrimaryLinkWithMarkAsRead() {
476 global $wgEchoCrossWikiNotifications;
477 $primaryLink = $this->getPrimaryLink();
478 if ( $primaryLink ) {
479 $eventIds = [ $this->event->getId() ];
480 if ( $this->getBundledIds() ) {
481 $eventIds = array_merge( $eventIds, $this->getBundledIds() );
482 }
483
484 $queryParams = [ 'markasread' => implode( '|', $eventIds ) ];
485 if ( $wgEchoCrossWikiNotifications ) {
486 $queryParams['markasreadwiki'] = WikiMap::getCurrentWikiId();
487 }
488
489 $primaryLink['url'] = wfAppendQuery( $primaryLink['url'], $queryParams );
490 }
491 return $primaryLink;
492 }
493
494 /**
495 * Array of secondary link details, including possibly-relative URLs, label,
496 * description & icon name.
497 *
498 * @return (null|array)[] Array of links in the format of:
499 * [['url' => (string) url,
500 * 'label' => (string) link text (non-escaped),
501 * 'description' => (string) descriptive text (optional, non-escaped),
502 * 'icon' => (bool|string) symbolic ooui icon name (or false if there is none),
503 * 'type' => (string) optional action type. Used to note a dynamic action,
504 * by setting it to 'dynamic-action'
505 * 'data' => (array) optional array containing information about the dynamic
506 * action. It must include 'tokenType' (string), 'messages' (array)
507 * with messages supplied for the item and the confirmation dialog
508 * and 'params' (array) for the API operation needed to complete the
509 * action. For example:
510 * 'data' => [
511 * 'tokenType' => 'watch',
512 * 'params' => [
513 * 'action' => 'watch',
514 * 'titles' => 'Namespace:SomeTitle'
515 * ],
516 * 'messages' => [
517 * 'confirmation' => [
518 * 'title' => 'message (parsed as HTML)',
519 * 'description' => 'optional message (parsed as HTML)'
520 * ]
521 * ]
522 * ]
523 * 'prioritized' => (bool) true to request the link be placed outside the action menu.
524 * false or omitted for the default behavior. By default, a link will
525 * be placed inside the menu, unless there are maxPrioritizedActions
526 * or fewer secondary links. If there are maxPrioritizedActions or
527 * fewer secondary links, they will all appear outside the action menu.
528 * At most maxPrioritizedActions links will be placed outside the action menu.
529 * maxPrioritizedActions is 2 on desktop and 1 on mobile.
530 * ...]
531 *
532 * Note that you should call array_values(array_filter()) on the
533 * result of this function (FIXME).
534 */
535 public function getSecondaryLinks() {
536 return [];
537 }
538
539 /**
540 * Get the ID of the associated event
541 * @return int Event id
542 */
543 public function getEventId() {
544 return $this->event->getId();
545 }
546
547 /**
548 * @return array
549 * @throws TimestampException
550 */
551 public function jsonSerialize(): array {
552 $body = $this->getBodyMessage();
553
554 return [
555 'header' => $this->getHeaderMessage()->parse(),
556 'compactHeader' => $this->getCompactHeaderMessage()->parse(),
557 'body' => $body ? $body->escaped() : '',
558 'icon' => $this->getIconType(),
559 'links' => [
560 'primary' => $this->getPrimaryLinkWithMarkAsRead() ?: [],
561 'secondary' => array_values( array_filter( $this->getSecondaryLinks() ) ),
562 ],
563 ];
564 }
565
566 /**
567 * @param UserIdentity $user
568 * @return string
569 */
570 protected function getTruncatedUsername( UserIdentity $user ) {
571 return $this->language->embedBidi( $this->language->truncateForVisual(
572 $user->getName(), self::USERNAME_RECOMMENDED_LENGTH, '...', false ) );
573 }
574
575 /**
576 * @param Title $title
577 * @param bool $includeNamespace
578 * @return string
579 */
580 protected function getTruncatedTitleText( Title $title, $includeNamespace = false ) {
581 $text = $includeNamespace ? $title->getPrefixedText() : $title->getText();
582 return $this->language->embedBidi( $this->language->truncateForVisual(
583 $text, self::PAGE_NAME_RECOMMENDED_LENGTH, '...', false ) );
584 }
585
586 /**
587 * @param User|null $user
588 * @return array|null
589 */
590 final protected function getUserLink( $user ) {
591 if ( !$user ) {
592 return null;
593 }
594
595 if ( !$this->userCan( RevisionRecord::DELETED_USER ) ) {
596 return null;
597 }
598
599 $url = !$user->isRegistered()
600 ? SpecialPage::getTitleFor( 'Contributions', $user->getName() )->getFullURL()
601 : $user->getUserPage()->getFullURL();
602
603 $label = $user->getName();
604 $truncatedLabel = $this->language->truncateForVisual(
605 $label, self::USERNAME_AS_LABEL_RECOMMENDED_LENGTH, '...', false );
606 $isTruncated = $label !== $truncatedLabel;
607
608 return [
609 'url' => $url,
610 'label' => $this->language->embedBidi( $truncatedLabel ),
611 'tooltip' => $isTruncated ? $label : '',
612 'description' => '',
613 'icon' => $user->isTemp() ? 'userTemporary' : 'userAvatar',
614 'prioritized' => true,
615 ];
616 }
617
618 /**
619 * @param Title $title
620 * @param string $description
621 * @param bool $prioritized
622 * @param array $query
623 * @return array
624 */
625 final protected function getPageLink( Title $title, $description, $prioritized, $query = [] ) {
626 if ( $title->getNamespace() === NS_USER_TALK ) {
627 $icon = 'userSpeechBubble';
628 } elseif ( $title->isTalkPage() ) {
629 $icon = 'speechBubbles';
630 } else {
631 $icon = 'article';
632 }
633
634 return [
635 'url' => $title->getFullURL( $query ),
636 'label' => $this->language->embedBidi(
637 $this->language->truncateForVisual(
638 $title->getText(), self::PAGE_NAME_AS_LABEL_RECOMMENDED_LENGTH, '...', false )
639 ),
640 'tooltip' => $title->getPrefixedText(),
641 'description' => $description,
642 'icon' => $icon,
643 'prioritized' => $prioritized,
644 ];
645 }
646
647 /**
648 * Get a dynamic action link
649 *
650 * @param Title $title Title relating to this action
651 * @param string|false $icon Optional. Symbolic name of the OOUI icon to use
652 * @param string $label link text (non-escaped)
653 * @param string|null $description descriptive text (optional, non-escaped)
654 * @param array $data Action data
655 * @param array $query
656 * @return array Array compatible with the structure of
657 * secondary links
658 */
659 final protected function getDynamicActionLink(
660 Title $title,
661 $icon,
662 $label,
663 $description = null,
664 $data = [],
665 $query = []
666 ) {
667 if ( !$icon && $title->getNamespace() === NS_USER_TALK ) {
668 $icon = 'userSpeechBubble';
669 } elseif ( !$icon && $title->isTalkPage() ) {
670 $icon = 'speechBubbles';
671 } elseif ( !$icon ) {
672 $icon = 'article';
673 }
674
675 return [
676 'type' => 'dynamic-action',
677 'label' => $label,
678 'description' => $description,
679 'data' => $data,
680 'url' => $title->getFullURL( $query ),
681 'icon' => $icon,
682 ];
683 }
684
685 /**
686 * Get an 'watch' or 'unwatch' dynamic action link
687 *
688 * @param Title $title Title to watch or unwatch
689 * @return array Array compatible with dynamic action link
690 */
691 final protected function getWatchActionLink( Title $title ) {
692 $isTitleWatched = MediaWikiServices::getInstance()->getWatchlistManager()
693 ->isWatched( $this->getUser(), $title );
694 $availableAction = $isTitleWatched ? 'unwatch' : 'watch';
695
696 $data = [
697 'tokenType' => 'watch',
698 'params' => [
699 'action' => 'watch',
700 'titles' => $title->getPrefixedText(),
701 ],
702 'messages' => [
703 'confirmation' => [
704 // notification-dynamic-actions-watch-confirmation
705 // notification-dynamic-actions-unwatch-confirmation
706 'title' => $this
707 ->msg( 'notification-dynamic-actions-' . $availableAction . '-confirmation' )
708 ->params(
709 $this->getTruncatedTitleText( $title ),
710 $title->getFullURL(),
711 $this->getUser()->getName()
712 ),
713 // notification-dynamic-actions-watch-confirmation-description
714 // notification-dynamic-actions-unwatch-confirmation-description
715 'description' => $this
716 ->msg( 'notification-dynamic-actions-' . $availableAction . '-confirmation-description' )
717 ->params(
718 $this->getTruncatedTitleText( $title ),
719 $title->getFullURL(),
720 $this->getUser()->getName()
721 ),
722 ],
723 ],
724 ];
725
726 // "Unwatching" action requires another parameter
727 if ( $isTitleWatched ) {
728 $data[ 'params' ][ 'unwatch' ] = 1;
729 }
730
731 return $this->getDynamicActionLink(
732 $title,
733 // Design requirements are to flip the star icons
734 // in their meaning; that is, for the 'unwatch' action
735 // we should display an empty star, and for the 'watch'
736 // action a full star. In OOUI icons, their names
737 // are reversed.
738 $isTitleWatched ? 'star' : 'unStar',
739 // notification-dynamic-actions-watch
740 // notification-dynamic-actions-unwatch
741 $this->msg( 'notification-dynamic-actions-' . $availableAction )
742 ->params(
743 $this->getTruncatedTitleText( $title ),
744 $title->getFullURL( [ 'action' => $availableAction ] ),
745 $this->getUser()->getName()
746 )->text(),
747 null,
748 $data,
749 [ 'action' => $availableAction ]
750 );
751 }
752 }
753
754 class_alias( EchoEventPresentationModel::class, 'EchoEventPresentationModel' );