Debian Codegraph @

extensions/Echo/includes/DataOutputFormatter.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications;
4
5 use MediaWiki\Context\RequestContext;
6 use MediaWiki\Extension\Notifications\Formatters\EchoEventFormatter;
7 use MediaWiki\Extension\Notifications\Formatters\EchoFlyoutFormatter;
8 use MediaWiki\Extension\Notifications\Formatters\EchoModelFormatter;
9 use MediaWiki\Extension\Notifications\Formatters\SpecialNotificationsFormatter;
10 use MediaWiki\Extension\Notifications\Model\Event;
11 use MediaWiki\Extension\Notifications\Model\Notification;
12 use MediaWiki\Language\Language;
13 use MediaWiki\Revision\RevisionRecord;
14 use MediaWiki\User\User;
15 use MediaWiki\User\UserIdentity;
16 use MediaWiki\Utils\MWTimestamp;
17 use MediaWiki\WikiMap\WikiMap;
18
19 /**
20 * Utility class that formats a notification in the format specified
21 * @todo Make this a service with DI
22 */
23 class DataOutputFormatter {
24
25 /**
26 * @var array<string,class-string<EchoEventFormatter>> type => class
27 */
28 protected static $formatters = [
29 'flyout' => EchoFlyoutFormatter::class,
30 'model' => EchoModelFormatter::class,
31 'special' => SpecialNotificationsFormatter::class,
32 'html' => SpecialNotificationsFormatter::class,
33 ];
34
35 /**
36 * Format a notification for a user in the format specified
37 *
38 * This method returns an array of data, some of it html
39 * escaped, some of it not. This confuses phan-taint-check,
40 * so mark it as safe for html and safe to be escaped again.
41 * @return-taint onlysafefor_htmlnoent
42 *
43 * @param Notification $notification
44 * @param string|false $format Output format, false to not format any notifications
45 * @param User $user the target user viewing the notification
46 * @param Language $lang Language to format the notification in
47 * @return array|false False if it could not be formatted
48 */
49 public static function formatOutput(
50 Notification $notification,
51 $format,
52 User $user,
53 Language $lang
54 ) {
55 $event = $notification->getEvent();
56 $timestamp = $notification->getTimestamp();
57 $utcTimestampIso8601 = wfTimestamp( TS_ISO_8601, $timestamp );
58 $utcTimestampUnix = (int)wfTimestamp( TS_UNIX, $timestamp );
59 $utcTimestampMW = wfTimestamp( TS_MW, $timestamp );
60 $bundledIds = null;
61
62 $bundledNotifs = $notification->getBundledNotifications();
63 if ( $bundledNotifs ) {
64 $bundledEvents = array_map( static function ( Notification $notif ) {
65 return $notif->getEvent();
66 }, $bundledNotifs );
67 $event->setBundledEvents( $bundledEvents );
68
69 $bundledIds = array_map( static function ( $event ) {
70 return (int)$event->getId();
71 }, $bundledEvents );
72 }
73
74 $timestampMw = self::getUserLocalTime( $user, $timestamp );
75
76 // Start creating date section header
77 $now = (int)wfTimestamp();
78 $dateFormat = substr( $timestampMw, 0, 8 );
79 $timeDiff = $now - $utcTimestampUnix;
80 // Most notifications would be more than two days ago, check this
81 // first instead of checking 'today' then 'yesterday'
82 if ( $timeDiff > 172800 ) {
83 $date = self::getDateHeader( $user, $timestampMw );
84 // 'Today'
85 } elseif ( str_starts_with( self::getUserLocalTime( $user, $now ), $dateFormat ) ) {
86 $date = wfMessage( 'echo-date-today' )->escaped();
87 // 'Yesterday'
88 } elseif ( str_starts_with( self::getUserLocalTime( $user, $now - 86400 ), $dateFormat ) ) {
89 $date = wfMessage( 'echo-date-yesterday' )->escaped();
90 } else {
91 $date = self::getDateHeader( $user, $timestampMw );
92 }
93 // End creating date section header
94
95 $output = [
96 'wiki' => WikiMap::getCurrentWikiId(),
97 'id' => $event->getId(),
98 'type' => $event->getType(),
99 'category' => $event->getCategory(),
100 'section' => $event->getSection(),
101 'timestamp' => [
102 // ISO 8601 is supposed to be the *only* format used for
103 // date output, but back-compat...
104 'utciso8601' => $utcTimestampIso8601,
105
106 // UTC timestamp in UNIX format used for loading more notification
107 'utcunix' => $utcTimestampUnix,
108 'unix' => self::getUserLocalTime( $user, $timestamp, TS_UNIX ),
109 'utcmw' => $utcTimestampMW,
110 'mw' => $timestampMw,
111 'date' => $date
112 ],
113 ];
114
115 if ( $bundledIds ) {
116 $output['bundledIds'] = $bundledIds;
117 }
118
119 if ( $event->getVariant() ) {
120 $output['variant'] = $event->getVariant();
121 }
122
123 $title = $event->getTitle();
124 if ( $title ) {
125 $output['title'] = [
126 'full' => $title->getPrefixedText(),
127 'namespace' => $title->getNsText(),
128 'namespace-key' => $title->getNamespace(),
129 'text' => $title->getText(),
130 ];
131 }
132
133 $agent = $event->getAgent();
134 if ( $agent ) {
135 if ( $event->userCan( RevisionRecord::DELETED_USER, $user ) ) {
136 $output['agent'] = [
137 'id' => $agent->getId(),
138 'name' => $agent->getName(),
139 ];
140 } else {
141 $output['agent'] = [ 'userhidden' => '' ];
142 }
143 }
144
145 if ( $event->getRevision() ) {
146 $output['revid'] = $event->getRevision()->getId();
147 }
148
149 if ( $notification->getReadTimestamp() ) {
150 $output['read'] = $notification->getReadTimestamp();
151 }
152
153 // This is only meant for unread notifications, if a notification has a target
154 // page, then it shouldn't be auto marked as read unless the user visits
155 // the target page or a user marks it as read manually ( coming soon )
156 $output['targetpages'] = [];
157 if ( $notification->getTargetPages() ) {
158 foreach ( $notification->getTargetPages() as $targetPage ) {
159 $output['targetpages'][] = $targetPage->getPageId();
160 }
161 }
162
163 if ( $format ) {
164 $formatted = self::formatNotification( $event, $user, $format, $lang );
165 if ( $formatted === false ) {
166 // Can't display it, so mark it as read
167 DeferredMarkAsDeletedUpdate::add( $event );
168 return false;
169 }
170 $output['*'] = $formatted;
171
172 if ( $notification->getBundledNotifications() &&
173 Services::getInstance()->getAttributeManager()->isBundleExpandable( $event->getType() )
174 ) {
175 $output['bundledNotifications'] = array_values( array_filter( array_map(
176 static function ( Notification $notification ) use ( $format, $user, $lang ) {
177 // remove nested notifications to
178 // - ensure they are formatted as single notifications (not bundled)
179 // - prevent further re-entrance on the current notification
180 $notification->setBundledNotifications( [] );
181 $notification->getEvent()->setBundledEvents( [] );
182 return self::formatOutput( $notification, $format, $user, $lang );
183 },
184 array_merge( [ $notification ], $notification->getBundledNotifications() )
185 ) ) );
186 }
187 }
188
189 return $output;
190 }
191
192 /**
193 * @param Event $event
194 * @param User $user
195 * @param string $format
196 * @param Language $lang
197 * @return string[]|string|false False if it could not be formatted
198 */
199 protected static function formatNotification( Event $event, User $user, $format, $lang ) {
200 if ( isset( self::$formatters[$format] ) ) {
201 $class = self::$formatters[$format];
202 /** @var EchoEventFormatter $formatter */
203 $formatter = new $class( $user, $lang );
204 return $formatter->format( $event );
205 }
206
207 return false;
208 }
209
210 /**
211 * Get the date header in user's format, 'May 10' or '10 May', depending
212 * on user's date format preference
213 * @param User $user
214 * @param string $timestampMw
215 * @return string
216 */
217 protected static function getDateHeader( User $user, $timestampMw ) {
218 $lang = RequestContext::getMain()->getLanguage();
219 $dateFormat = $lang->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
220
221 return $lang->sprintfDate( $dateFormat, $timestampMw );
222 }
223
224 /**
225 * Helper function for converting UTC timezone to a user's timezone
226 *
227 * @param UserIdentity $user
228 * @param string|int $ts
229 * @param int $format output format
230 *
231 * @return string
232 */
233 public static function getUserLocalTime( UserIdentity $user, $ts, $format = TS_MW ) {
234 $timestamp = new MWTimestamp( $ts );
235 $timestamp->offsetForUser( $user );
236
237 return $timestamp->getTimestamp( $format );
238 }
239
240 }