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