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