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