Debian Codegraph @

extensions/Echo/includes/Mapper/NotificationMapper.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications\Mapper;
4
5 use BatchRowIterator;
6 use Exception;
7 use InvalidArgumentException;
8 use MediaWiki\Deferred\AtomicSectionUpdate;
9 use MediaWiki\Deferred\DeferredUpdates;
10 use MediaWiki\Extension\Notifications\Model\Notification;
11 use MediaWiki\MediaWikiServices;
12 use MediaWiki\Title\Title;
13 use MediaWiki\User\UserIdentity;
14 use MWExceptionHandler;
15 use Wikimedia\Rdbms\IDatabase;
16 use Wikimedia\Rdbms\SelectQueryBuilder;
17
18 /**
19 * Database mapper for Notification model
20 */
21 class NotificationMapper extends AbstractMapper {
22
23 /**
24 * Insert a notification record
25 * @param Notification $notification
26 */
27 public function insert( Notification $notification ) {
28 $dbw = $this->dbFactory->getEchoDb( DB_PRIMARY );
29
30 $listeners = $this->getMethodListeners( __FUNCTION__ );
31
32 $row = $notification->toDbArray();
33 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
34 $dbw,
35 __METHOD__,
36 static function ( IDatabase $dbw, $fname ) use ( $row, $listeners ) {
37 $row['notification_timestamp'] =
38 $dbw->timestamp( $row['notification_timestamp'] );
39 $row['notification_read_timestamp'] =
40 $dbw->timestampOrNull( $row['notification_read_timestamp'] );
41 $dbw->newInsertQueryBuilder()
42 ->insertInto( 'echo_notification' )
43 ->row( $row )
44 ->caller( $fname )
45 ->execute();
46 foreach ( $listeners as $listener ) {
47 $dbw->onTransactionCommitOrIdle( $listener, $fname );
48 }
49 }
50 ) );
51 }
52
53 /**
54 * Extract the offset used for notification list
55 * @param string|null $continue String Used for offset
56 * @return int[]
57 */
58 protected function extractQueryOffset( $continue ) {
59 $offset = [
60 'timestamp' => 0,
61 'offset' => 0,
62 ];
63 if ( $continue ) {
64 $values = explode( '|', $continue, 3 );
65 if ( count( $values ) !== 2 ) {
66 throw new InvalidArgumentException( 'Invalid continue param: ' . $continue );
67 }
68 $offset['timestamp'] = (int)$values[0];
69 $offset['offset'] = (int)$values[1];
70 }
71
72 return $offset;
73 }
74
75 /**
76 * Get unread notifications by user in the amount specified by limit order by
77 * notification timestamp in descending order. We have an index to retrieve
78 * unread notifications, but it's not optimized for ordering by timestamp. The
79 * descending order is only allowed if we keep the notification in low volume,
80 * which is done via a deleteJob
81 * @param UserIdentity $userIdentity
82 * @param int $limit
83 * @param string|null $continue Used for offset
84 * @param string[] $eventTypes
85 * @param Title[]|null $titles If set, only return notifications for these pages.
86 * To find notifications not associated with any page, add null as an element to this array.
87 * @param int $dbSource Use primary database or replica database
88 * @return Notification[]
89 */
90 public function fetchUnreadByUser(
91 UserIdentity $userIdentity,
92 $limit,
93 $continue,
94 array $eventTypes = [],
95 ?array $titles = null,
96 $dbSource = DB_REPLICA
97 ) {
98 $conds = [ 'notification_read_timestamp' => null ];
99 if ( $titles ) {
100 $conds['event_page_id'] = $this->getIdsForTitles( $titles );
101 if ( !$conds['event_page_id'] ) {
102 return [];
103 }
104 }
105 return $this->fetchByUserInternal(
106 $userIdentity,
107 $limit,
108 $continue,
109 $eventTypes,
110 $conds,
111 $dbSource
112 );
113 }
114
115 /**
116 * Get read notifications by user in the amount specified by limit order by
117 * notification timestamp in descending order. We have an index to retrieve
118 * unread notifications but it's not optimized for ordering by timestamp. The
119 * descending order is only allowed if we keep the notification in low volume,
120 * which is done via a deleteJob
121 * @param UserIdentity $userIdentity
122 * @param int $limit
123 * @param string|null $continue Used for offset
124 * @param string[] $eventTypes
125 * @param Title[]|null $titles If set, only return notifications for these pages.
126 * To find notifications not associated with any page, add null as an element to this array.
127 * @param int $dbSource Use primary database or replica database
128 * @return Notification[]
129 */
130 public function fetchReadByUser(
131 UserIdentity $userIdentity,
132 $limit,
133 $continue,
134 array $eventTypes = [],
135 ?array $titles = null,
136 $dbSource = DB_REPLICA
137 ) {
138 $dbr = $this->dbFactory->getEchoDb( $dbSource );
139 $conds = [ $dbr->expr( 'notification_read_timestamp', '!=', null ) ];
140 if ( $titles ) {
141 $conds['event_page_id'] = $this->getIdsForTitles( $titles );
142 if ( !$conds['event_page_id'] ) {
143 return [];
144 }
145 }
146 return $this->fetchByUserInternal(
147 $userIdentity,
148 $limit,
149 $continue,
150 $eventTypes,
151 $conds,
152 $dbSource
153 );
154 }
155
156 /**
157 * Get Notification by user in batch along with limit, offset etc
158 *
159 * @param UserIdentity $userIdentity the user to get notifications for
160 * @param int $limit The maximum number of notifications to return
161 * @param string|null $continue Used for offset
162 * @param array $eventTypes Event types to load
163 * @param array $excludeEventIds Event id's to exclude.
164 * @param Title[]|null $titles If set, only return notifications for these pages.
165 * To find notifications not associated with any page, add null as an element to this array.
166 * @return Notification[]
167 */
168 public function fetchByUser(
169 UserIdentity $userIdentity,
170 $limit,
171 $continue,
172 array $eventTypes = [],
173 array $excludeEventIds = [],
174 ?array $titles = null
175 ) {
176 $dbr = $this->dbFactory->getEchoDb( DB_REPLICA );
177
178 $conds = [];
179 if ( $excludeEventIds ) {
180 $conds[] = $dbr->expr( 'event_id', '!=', $excludeEventIds );
181 }
182 if ( $titles ) {
183 $conds['event_page_id'] = $this->getIdsForTitles( $titles );
184 if ( !$conds['event_page_id'] ) {
185 return [];
186 }
187 }
188
189 return $this->fetchByUserInternal(
190 $userIdentity,
191 $limit,
192 $continue,
193 $eventTypes,
194 $conds
195 );
196 }
197
198 protected function getIdsForTitles( array $titles ) {
199 $ids = [];
200 foreach ( $titles as $title ) {
201 if ( $title === null ) {
202 $ids[] = null;
203 } elseif ( $title->exists() ) {
204 $ids[] = $title->getArticleId();
205 }
206 }
207 return $ids;
208 }
209
210 /**
211 * @param UserIdentity $userIdentity the user to get notifications for
212 * @param int $limit The maximum number of notifications to return
213 * @param string|null $continue Used for offset
214 * @param array $eventTypes Event types to load
215 * @param array $conds Additional query conditions.
216 * @param int $dbSource Use primary database or replica database
217 * @return Notification[]
218 */
219 protected function fetchByUserInternal(
220 UserIdentity $userIdentity,
221 $limit,
222 $continue,
223 array $eventTypes = [],
224 array $conds = [],
225 $dbSource = DB_REPLICA
226 ) {
227 $dbr = $this->dbFactory->getEchoDb( $dbSource );
228
229 if ( !$eventTypes ) {
230 return [];
231 }
232
233 // There is a problem with querying by event type, if a user has only one or none
234 // flow notification and huge amount other notifications, the lookup of only flow
235 // notification will result in a slow query. Luckily users won't have that many
236 // notifications. We should have some cron job to remove old notifications so
237 // the notification volume is in a reasonable amount for such case. The other option
238 // is to denormalize notification table with event_type and lookup index.
239 $conds = [
240 'notification_user' => $userIdentity->getId(),
241 'event_type' => $eventTypes,
242 'event_deleted' => 0,
243 ] + $conds;
244
245 $offset = $this->extractQueryOffset( $continue );
246
247 // Start points are specified
248 if ( $offset['timestamp'] && $offset['offset'] ) {
249 // The offset and timestamp are those of the first notification we want to return
250 $conds[] = $dbr->buildComparison( '<=', [
251 'notification_timestamp' => $dbr->timestamp( $offset['timestamp'] ),
252 'notification_event' => $offset['offset'],
253 ] );
254 }
255
256 $res = $dbr->newSelectQueryBuilder()
257 ->select( Notification::selectFields() )
258 ->from( 'echo_notification' )
259 ->leftJoin( 'echo_event', null, 'notification_event=event_id' )
260 ->where( $conds )
261 ->orderBy( [ 'notification_timestamp', 'notification_event' ], SelectQueryBuilder::SORT_DESC )
262 ->limit( $limit )
263 ->caller( __METHOD__ )
264 ->fetchResultSet();
265
266 /** @var Notification[] $allNotifications */
267 $allNotifications = [];
268 foreach ( $res as $row ) {
269 try {
270 $notification = Notification::newFromRow( $row );
271 if ( $notification ) {
272 $allNotifications[] = $notification;
273 }
274 } catch ( Exception $e ) {
275 $id = $row->event_id ?? 'unknown event';
276 wfDebugLog( 'Echo', __METHOD__ . ": Failed initializing event: $id" );
277 MWExceptionHandler::logException( $e );
278 }
279 }
280
281 $data = [];
282 foreach ( $allNotifications as $notification ) {
283 $data[ $notification->getEvent()->getId() ] = $notification;
284 }
285
286 return $data;
287 }
288
289 /**
290 * Fetch Notifications by user and event IDs.
291 *
292 * @param UserIdentity $userIdentity
293 * @param int[] $eventIds
294 * @return Notification[]
295 */
296 public function fetchByUserEvents( UserIdentity $userIdentity, array $eventIds ) {
297 $dbr = $this->dbFactory->getEchoDb( DB_REPLICA );
298
299 $result = $dbr->newSelectQueryBuilder()
300 ->select( Notification::selectFields() )
301 ->from( 'echo_notification' )
302 ->join( 'echo_event', null, 'notification_event=event_id' )
303 ->where( [
304 'notification_user' => $userIdentity->getId(),
305 'notification_event' => $eventIds
306 ] )
307 ->caller( __METHOD__ )
308 ->fetchResultSet();
309
310 $notifications = [];
311 foreach ( $result as $row ) {
312 $notifications[] = Notification::newFromRow( $row );
313 }
314 return $notifications;
315 }
316
317 /**
318 * Fetch a notification by user in the specified offset. The caller should
319 * know that passing a big number for offset is NOT going to work
320 * @param UserIdentity $userIdentity
321 * @param int $offset
322 * @return Notification|false
323 */
324 public function fetchByUserOffset( UserIdentity $userIdentity, $offset ) {
325 $dbr = $this->dbFactory->getEchoDb( DB_REPLICA );
326 $row = $dbr->newSelectQueryBuilder()
327 ->select( Notification::selectFields() )
328 ->from( 'echo_notification' )
329 ->leftJoin( 'echo_event', null, 'notification_event=event_id' )
330 ->where( [
331 'notification_user' => $userIdentity->getId(),
332 'event_deleted' => 0,
333 ] )
334 ->orderBy( [ 'notification_timestamp', 'notification_event' ], SelectQueryBuilder::SORT_DESC )
335 ->offset( $offset )
336 ->caller( __METHOD__ )
337 ->fetchRow();
338
339 if ( $row ) {
340 return Notification::newFromRow( $row );
341 } else {
342 return false;
343 }
344 }
345
346 /**
347 * Batch delete notifications by user and eventId offset
348 * @param UserIdentity $userIdentity
349 * @param int $eventId
350 * @return bool
351 */
352 public function deleteByUserEventOffset( UserIdentity $userIdentity, $eventId ) {
353 global $wgUpdateRowsPerQuery;
354 $eventMapper = new EventMapper( $this->dbFactory );
355 $userId = $userIdentity->getId();
356 $dbw = $this->dbFactory->getEchoDb( DB_PRIMARY );
357 $dbr = $this->dbFactory->getEchoDb( DB_REPLICA );
358 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
359 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
360 $domainId = $dbw->getDomainID();
361
362 $iterator = new BatchRowIterator(
363 $dbr,
364 'echo_notification',
365 'notification_event',
366 $wgUpdateRowsPerQuery
367 );
368 $iterator->addConditions( [
369 'notification_user' => $userId,
370 $dbw->expr( 'notification_event', '<', (int)$eventId ),
371 ] );
372 $iterator->setCaller( __METHOD__ );
373
374 foreach ( $iterator as $batch ) {
375 $eventIds = [];
376 foreach ( $batch as $row ) {
377 $eventIds[] = $row->notification_event;
378 }
379 $dbw->newDeleteQueryBuilder()
380 ->deleteFrom( 'echo_notification' )
381 ->where( [
382 'notification_user' => $userId,
383 'notification_event' => $eventIds,
384 ] )
385 ->caller( __METHOD__ )
386 ->execute();
387
388 // Find out which events are now orphaned, i.e. no longer referenced in echo_notifications
389 // (besides the rows we just deleted) or in echo_email_batch, and delete them
390 $eventMapper->deleteOrphanedEvents( $eventIds, $userId, 'echo_notification' );
391
392 $lbFactory->commitAndWaitForReplication(
393 __METHOD__, $ticket, [ 'domain' => $domainId ] );
394 }
395 return true;
396 }
397
398 /**
399 * Fetch ids of users that have notifications for certain events
400 *
401 * @param int[] $eventIds
402 * @return int[]
403 */
404 public function fetchUsersWithNotificationsForEvents( array $eventIds ) {
405 $dbr = $this->dbFactory->getEchoDb( DB_REPLICA );
406
407 return $dbr->newSelectQueryBuilder()
408 ->select( 'notification_user' )
409 ->distinct()
410 ->from( 'echo_notification' )
411 ->where( [
412 'notification_event' => $eventIds
413 ] )
414 ->caller( __METHOD__ )
415 ->fetchFieldValues();
416 }
417
418 }
419
420 class_alias( NotificationMapper::class, 'EchoNotificationMapper' );