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