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