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