Add WatchedItemStore::getWatchedItemsForUser
[lhc/web/wiklou.git] / includes / WatchedItemStore.php
1 <?php
2
3 use Wikimedia\Assert\Assert;
4
5 /**
6 * Storage layer class for WatchedItems.
7 * Database interaction.
8 *
9 * @author Addshore
10 *
11 * @since 1.27
12 */
13 class WatchedItemStore {
14
15 /**
16 * @var LoadBalancer
17 */
18 private $loadBalancer;
19
20 /**
21 * @var HashBagOStuff
22 */
23 private $cache;
24
25 /**
26 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
27 * The index is needed so that on mass changes all relevant items can be un-cached.
28 * For example: Clearing a users watchlist of all items or updating notification timestamps
29 * for all users watching a single target.
30 */
31 private $cacheIndex = [];
32
33 /**
34 * @var callable|null
35 */
36 private $deferredUpdatesAddCallableUpdateCallback;
37
38 /**
39 * @var callable|null
40 */
41 private $revisionGetTimestampFromIdCallback;
42
43 /**
44 * @var self|null
45 */
46 private static $instance;
47
48 /**
49 * @param LoadBalancer $loadBalancer
50 * @param HashBagOStuff $cache
51 */
52 public function __construct(
53 LoadBalancer $loadBalancer,
54 HashBagOStuff $cache
55 ) {
56 $this->loadBalancer = $loadBalancer;
57 $this->cache = $cache;
58 $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
59 $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
60 }
61
62 /**
63 * Overrides the DeferredUpdates::addCallableUpdate callback
64 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
65 *
66 * @param callable $callback
67 *
68 * @see DeferredUpdates::addCallableUpdate for callback signiture
69 *
70 * @return ScopedCallback to reset the overridden value
71 * @throws MWException
72 */
73 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
74 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
75 throw new MWException(
76 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
77 );
78 }
79 Assert::parameterType( 'callable', $callback, '$callback' );
80
81 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback;
82 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
83 return new ScopedCallback( function() use ( $previousValue ) {
84 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
85 } );
86 }
87
88 /**
89 * Overrides the Revision::getTimestampFromId callback
90 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
91 *
92 * @param callable $callback
93 * @see Revision::getTimestampFromId for callback signiture
94 *
95 * @return ScopedCallback to reset the overridden value
96 * @throws MWException
97 */
98 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
99 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
100 throw new MWException(
101 'Cannot override Revision::getTimestampFromId callback in operation.'
102 );
103 }
104 Assert::parameterType( 'callable', $callback, '$callback' );
105
106 $previousValue = $this->revisionGetTimestampFromIdCallback;
107 $this->revisionGetTimestampFromIdCallback = $callback;
108 return new ScopedCallback( function() use ( $previousValue ) {
109 $this->revisionGetTimestampFromIdCallback = $previousValue;
110 } );
111 }
112
113 /**
114 * Overrides the default instance of this class
115 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
116 *
117 * If this method is used it MUST also be called with null after a test to ensure a new
118 * default instance is created next time getDefaultInstance is called.
119 *
120 * @param WatchedItemStore|null $store
121 *
122 * @return ScopedCallback to reset the overridden value
123 * @throws MWException
124 */
125 public static function overrideDefaultInstance( WatchedItemStore $store = null ) {
126 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
127 throw new MWException(
128 'Cannot override ' . __CLASS__ . 'default instance in operation.'
129 );
130 }
131
132 $previousValue = self::$instance;
133 self::$instance = $store;
134 return new ScopedCallback( function() use ( $previousValue ) {
135 self::$instance = $previousValue;
136 } );
137 }
138
139 /**
140 * @return self
141 */
142 public static function getDefaultInstance() {
143 if ( !self::$instance ) {
144 self::$instance = new self(
145 wfGetLB(),
146 new HashBagOStuff( [ 'maxKeys' => 100 ] )
147 );
148 }
149 return self::$instance;
150 }
151
152 private function getCacheKey( User $user, LinkTarget $target ) {
153 return $this->cache->makeKey(
154 (string)$target->getNamespace(),
155 $target->getDBkey(),
156 (string)$user->getId()
157 );
158 }
159
160 private function cache( WatchedItem $item ) {
161 $user = $item->getUser();
162 $target = $item->getLinkTarget();
163 $key = $this->getCacheKey( $user, $target );
164 $this->cache->set( $key, $item );
165 $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
166 }
167
168 private function uncache( User $user, LinkTarget $target ) {
169 $this->cache->delete( $this->getCacheKey( $user, $target ) );
170 unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
171 }
172
173 private function uncacheLinkTarget( LinkTarget $target ) {
174 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
175 return;
176 }
177 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
178 $this->cache->delete( $key );
179 }
180 }
181
182 /**
183 * @param User $user
184 * @param LinkTarget $target
185 *
186 * @return WatchedItem|null
187 */
188 private function getCached( User $user, LinkTarget $target ) {
189 return $this->cache->get( $this->getCacheKey( $user, $target ) );
190 }
191
192 /**
193 * Return an array of conditions to select or update the appropriate database
194 * row.
195 *
196 * @param User $user
197 * @param LinkTarget $target
198 *
199 * @return array
200 */
201 private function dbCond( User $user, LinkTarget $target ) {
202 return [
203 'wl_user' => $user->getId(),
204 'wl_namespace' => $target->getNamespace(),
205 'wl_title' => $target->getDBkey(),
206 ];
207 }
208
209 /**
210 * @param int $slaveOrMaster DB_MASTER or DB_SLAVE
211 *
212 * @return DatabaseBase
213 * @throws MWException
214 */
215 private function getConnection( $slaveOrMaster ) {
216 return $this->loadBalancer->getConnection( $slaveOrMaster, [ 'watchlist' ] );
217 }
218
219 /**
220 * @param DatabaseBase $connection
221 *
222 * @throws MWException
223 */
224 private function reuseConnection( $connection ) {
225 $this->loadBalancer->reuseConnection( $connection );
226 }
227
228 /**
229 * Count the number of individual items that are watched by the user.
230 * If a subject and corresponding talk page are watched this will return 2.
231 *
232 * @param User $user
233 *
234 * @return int
235 */
236 public function countWatchedItems( User $user ) {
237 $dbr = $this->getConnection( DB_SLAVE );
238 $return = (int)$dbr->selectField(
239 'watchlist',
240 'COUNT(*)',
241 [
242 'wl_user' => $user->getId()
243 ],
244 __METHOD__
245 );
246 $this->reuseConnection( $dbr );
247
248 return $return;
249 }
250
251 /**
252 * @param LinkTarget $target
253 *
254 * @return int
255 */
256 public function countWatchers( LinkTarget $target ) {
257 $dbr = $this->getConnection( DB_SLAVE );
258 $return = (int)$dbr->selectField(
259 'watchlist',
260 'COUNT(*)',
261 [
262 'wl_namespace' => $target->getNamespace(),
263 'wl_title' => $target->getDBkey(),
264 ],
265 __METHOD__
266 );
267 $this->reuseConnection( $dbr );
268
269 return $return;
270 }
271
272 /**
273 * Number of page watchers who also visited a "recent" edit
274 *
275 * @param LinkTarget $target
276 * @param mixed $threshold timestamp accepted by wfTimestamp
277 *
278 * @return int
279 * @throws DBUnexpectedError
280 * @throws MWException
281 */
282 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
283 $dbr = $this->getConnection( DB_SLAVE );
284 $visitingWatchers = (int)$dbr->selectField(
285 'watchlist',
286 'COUNT(*)',
287 [
288 'wl_namespace' => $target->getNamespace(),
289 'wl_title' => $target->getDBkey(),
290 'wl_notificationtimestamp >= ' .
291 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
292 ' OR wl_notificationtimestamp IS NULL'
293 ],
294 __METHOD__
295 );
296 $this->reuseConnection( $dbr );
297
298 return $visitingWatchers;
299 }
300
301 /**
302 * @param LinkTarget[] $targets
303 * @param array $options Allowed keys:
304 * 'minimumWatchers' => int
305 *
306 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
307 * All targets will be present in the result. 0 either means no watchers or the number
308 * of watchers was below the minimumWatchers option if passed.
309 */
310 public function countWatchersMultiple( array $targets, array $options = [] ) {
311 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
312
313 $dbr = $this->getConnection( DB_SLAVE );
314
315 if ( array_key_exists( 'minimumWatchers', $options ) ) {
316 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
317 }
318
319 $lb = new LinkBatch( $targets );
320 $res = $dbr->select(
321 'watchlist',
322 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
323 [ $lb->constructSet( 'wl', $dbr ) ],
324 __METHOD__,
325 $dbOptions
326 );
327
328 $this->reuseConnection( $dbr );
329
330 $watchCounts = [];
331 foreach ( $targets as $linkTarget ) {
332 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
333 }
334
335 foreach ( $res as $row ) {
336 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
337 }
338
339 return $watchCounts;
340 }
341
342 /**
343 * Get an item (may be cached)
344 *
345 * @param User $user
346 * @param LinkTarget $target
347 *
348 * @return WatchedItem|false
349 */
350 public function getWatchedItem( User $user, LinkTarget $target ) {
351 if ( $user->isAnon() ) {
352 return false;
353 }
354
355 $cached = $this->getCached( $user, $target );
356 if ( $cached ) {
357 return $cached;
358 }
359 return $this->loadWatchedItem( $user, $target );
360 }
361
362 /**
363 * Loads an item from the db
364 *
365 * @param User $user
366 * @param LinkTarget $target
367 *
368 * @return WatchedItem|false
369 */
370 public function loadWatchedItem( User $user, LinkTarget $target ) {
371 // Only loggedin user can have a watchlist
372 if ( $user->isAnon() ) {
373 return false;
374 }
375
376 $dbr = $this->getConnection( DB_SLAVE );
377 $row = $dbr->selectRow(
378 'watchlist',
379 'wl_notificationtimestamp',
380 $this->dbCond( $user, $target ),
381 __METHOD__
382 );
383 $this->reuseConnection( $dbr );
384
385 if ( !$row ) {
386 return false;
387 }
388
389 $item = new WatchedItem(
390 $user,
391 $target,
392 $row->wl_notificationtimestamp
393 );
394 $this->cache( $item );
395
396 return $item;
397 }
398
399 /**
400 * @param User $user
401 * @param array $options Allowed keys:
402 * 'forWrite' => bool defaults to false
403 *
404 * @return WatchedItem[]
405 */
406 public function getWatchedItemsForUser( User $user, array $options = [] ) {
407 $options += [ 'forWrite' => false ];
408
409 $db = $this->getConnection( $options['forWrite'] ? DB_MASTER : DB_SLAVE );
410 $res = $db->select(
411 'watchlist',
412 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
413 [ 'wl_user' => $user->getId() ],
414 __METHOD__
415 );
416 $this->reuseConnection( $db );
417
418 $watchedItems = [];
419 foreach ( $res as $row ) {
420 // todo these could all be cached at some point?
421 $watchedItems[] = new WatchedItem(
422 $user,
423 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
424 $row->wl_notificationtimestamp
425 );
426 }
427
428 return $watchedItems;
429 }
430
431 /**
432 * Must be called separately for Subject & Talk namespaces
433 *
434 * @param User $user
435 * @param LinkTarget $target
436 *
437 * @return bool
438 */
439 public function isWatched( User $user, LinkTarget $target ) {
440 return (bool)$this->getWatchedItem( $user, $target );
441 }
442
443 /**
444 * Must be called separately for Subject & Talk namespaces
445 *
446 * @param User $user
447 * @param LinkTarget $target
448 */
449 public function addWatch( User $user, LinkTarget $target ) {
450 $this->addWatchBatch( [ [ $user, $target ] ] );
451 }
452
453 /**
454 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
455 *
456 * @return bool success
457 */
458 public function addWatchBatch( array $userTargetCombinations ) {
459 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
460 return false;
461 }
462
463 $rows = [];
464 foreach ( $userTargetCombinations as list( $user, $target ) ) {
465 /**
466 * @var User $user
467 * @var LinkTarget $target
468 */
469
470 // Only loggedin user can have a watchlist
471 if ( $user->isAnon() ) {
472 continue;
473 }
474 $rows[] = [
475 'wl_user' => $user->getId(),
476 'wl_namespace' => $target->getNamespace(),
477 'wl_title' => $target->getDBkey(),
478 'wl_notificationtimestamp' => null,
479 ];
480 $this->uncache( $user, $target );
481 }
482
483 if ( !$rows ) {
484 return false;
485 }
486
487 $dbw = $this->getConnection( DB_MASTER );
488 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
489 // Use INSERT IGNORE to avoid overwriting the notification timestamp
490 // if there's already an entry for this page
491 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
492 }
493 $this->reuseConnection( $dbw );
494
495 return true;
496 }
497
498 /**
499 * Removes the an entry for the User watching the LinkTarget
500 * Must be called separately for Subject & Talk namespaces
501 *
502 * @param User $user
503 * @param LinkTarget $target
504 *
505 * @return bool success
506 * @throws DBUnexpectedError
507 * @throws MWException
508 */
509 public function removeWatch( User $user, LinkTarget $target ) {
510 // Only logged in user can have a watchlist
511 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
512 return false;
513 }
514
515 $this->uncache( $user, $target );
516
517 $dbw = $this->getConnection( DB_MASTER );
518 $dbw->delete( 'watchlist',
519 [
520 'wl_user' => $user->getId(),
521 'wl_namespace' => $target->getNamespace(),
522 'wl_title' => $target->getDBkey(),
523 ], __METHOD__
524 );
525 $success = (bool)$dbw->affectedRows();
526 $this->reuseConnection( $dbw );
527
528 return $success;
529 }
530
531 /**
532 * @param User $editor The editor that triggered the update. Their notification
533 * timestamp will not be updated(they have already seen it)
534 * @param LinkTarget $target The target to update timestamps for
535 * @param string $timestamp Set the update timestamp to this value
536 *
537 * @return int[] Array of user IDs the timestamp has been updated for
538 */
539 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
540 $dbw = $this->getConnection( DB_MASTER );
541 $res = $dbw->select( [ 'watchlist' ],
542 [ 'wl_user' ],
543 [
544 'wl_user != ' . intval( $editor->getId() ),
545 'wl_namespace' => $target->getNamespace(),
546 'wl_title' => $target->getDBkey(),
547 'wl_notificationtimestamp IS NULL',
548 ], __METHOD__
549 );
550
551 $watchers = [];
552 foreach ( $res as $row ) {
553 $watchers[] = intval( $row->wl_user );
554 }
555
556 if ( $watchers ) {
557 // Update wl_notificationtimestamp for all watching users except the editor
558 $fname = __METHOD__;
559 $dbw->onTransactionIdle(
560 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
561 $dbw->update( 'watchlist',
562 [ /* SET */
563 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
564 ], [ /* WHERE */
565 'wl_user' => $watchers,
566 'wl_namespace' => $target->getNamespace(),
567 'wl_title' => $target->getDBkey(),
568 ], $fname
569 );
570 $this->uncacheLinkTarget( $target );
571 }
572 );
573 }
574
575 $this->reuseConnection( $dbw );
576
577 return $watchers;
578 }
579
580 /**
581 * Reset the notification timestamp of this entry
582 *
583 * @param User $user
584 * @param Title $title
585 * @param string $force Whether to force the write query to be executed even if the
586 * page is not watched or the notification timestamp is already NULL.
587 * 'force' in order to force
588 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
589 *
590 * @return bool success
591 */
592 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
593 // Only loggedin user can have a watchlist
594 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
595 return false;
596 }
597
598 $item = null;
599 if ( $force != 'force' ) {
600 $item = $this->loadWatchedItem( $user, $title );
601 if ( !$item || $item->getNotificationTimestamp() === null ) {
602 return false;
603 }
604 }
605
606 // If the page is watched by the user (or may be watched), update the timestamp
607 $job = new ActivityUpdateJob(
608 $title,
609 [
610 'type' => 'updateWatchlistNotification',
611 'userid' => $user->getId(),
612 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
613 'curTime' => time()
614 ]
615 );
616
617 // Try to run this post-send
618 // Calls DeferredUpdates::addCallableUpdate in normal operation
619 call_user_func(
620 $this->deferredUpdatesAddCallableUpdateCallback,
621 function() use ( $job ) {
622 $job->run();
623 }
624 );
625
626 $this->uncache( $user, $title );
627
628 return true;
629 }
630
631 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
632 if ( !$oldid ) {
633 // No oldid given, assuming latest revision; clear the timestamp.
634 return null;
635 }
636
637 if ( !$title->getNextRevisionID( $oldid ) ) {
638 // Oldid given and is the latest revision for this title; clear the timestamp.
639 return null;
640 }
641
642 if ( $item === null ) {
643 $item = $this->loadWatchedItem( $user, $title );
644 }
645
646 if ( !$item ) {
647 // This can only happen if $force is enabled.
648 return null;
649 }
650
651 // Oldid given and isn't the latest; update the timestamp.
652 // This will result in no further notification emails being sent!
653 // Calls Revision::getTimestampFromId in normal operation
654 $notificationTimestamp = call_user_func(
655 $this->revisionGetTimestampFromIdCallback,
656 $title,
657 $oldid
658 );
659
660 // We need to go one second to the future because of various strict comparisons
661 // throughout the codebase
662 $ts = new MWTimestamp( $notificationTimestamp );
663 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
664 $notificationTimestamp = $ts->getTimestamp( TS_MW );
665
666 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
667 if ( $force != 'force' ) {
668 return false;
669 } else {
670 // This is a little silly…
671 return $item->getNotificationTimestamp();
672 }
673 }
674
675 return $notificationTimestamp;
676 }
677
678 /**
679 * @param User $user
680 * @param int $unreadLimit
681 *
682 * @return int|bool The number of unread notifications
683 * true if greater than or equal to $unreadLimit
684 */
685 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
686 $queryOptions = [];
687 if ( $unreadLimit !== null ) {
688 $unreadLimit = (int)$unreadLimit;
689 $queryOptions['LIMIT'] = $unreadLimit;
690 }
691
692 $dbr = $this->getConnection( DB_SLAVE );
693 $rowCount = $dbr->selectRowCount(
694 'watchlist',
695 '1',
696 [
697 'wl_user' => $user->getId(),
698 'wl_notificationtimestamp IS NOT NULL',
699 ],
700 __METHOD__,
701 $queryOptions
702 );
703 $this->reuseConnection( $dbr );
704
705 if ( !isset( $unreadLimit ) ) {
706 return $rowCount;
707 }
708
709 if ( $rowCount >= $unreadLimit ) {
710 return true;
711 }
712
713 return $rowCount;
714 }
715
716 /**
717 * Check if the given title already is watched by the user, and if so
718 * add a watch for the new title.
719 *
720 * To be used for page renames and such.
721 *
722 * @param LinkTarget $oldTarget
723 * @param LinkTarget $newTarget
724 */
725 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
726 if ( !$oldTarget instanceof Title ) {
727 $oldTarget = Title::newFromLinkTarget( $oldTarget );
728 }
729 if ( !$newTarget instanceof Title ) {
730 $newTarget = Title::newFromLinkTarget( $newTarget );
731 }
732
733 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
734 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
735 }
736
737 /**
738 * Check if the given title already is watched by the user, and if so
739 * add a watch for the new title.
740 *
741 * To be used for page renames and such.
742 * This must be called separately for Subject and Talk pages
743 *
744 * @param LinkTarget $oldTarget
745 * @param LinkTarget $newTarget
746 */
747 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
748 $dbw = $this->getConnection( DB_MASTER );
749
750 $result = $dbw->select(
751 'watchlist',
752 [ 'wl_user', 'wl_notificationtimestamp' ],
753 [
754 'wl_namespace' => $oldTarget->getNamespace(),
755 'wl_title' => $oldTarget->getDBkey(),
756 ],
757 __METHOD__,
758 [ 'FOR UPDATE' ]
759 );
760
761 $newNamespace = $newTarget->getNamespace();
762 $newDBkey = $newTarget->getDBkey();
763
764 # Construct array to replace into the watchlist
765 $values = [];
766 foreach ( $result as $row ) {
767 $values[] = [
768 'wl_user' => $row->wl_user,
769 'wl_namespace' => $newNamespace,
770 'wl_title' => $newDBkey,
771 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
772 ];
773 }
774
775 if ( !empty( $values ) ) {
776 # Perform replace
777 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
778 # some other DBMSes, mostly due to poor simulation by us
779 $dbw->replace(
780 'watchlist',
781 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
782 $values,
783 __METHOD__
784 );
785 }
786
787 $this->reuseConnection( $dbw );
788 }
789
790 }