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