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