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