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