Move remaining LoadBalancer classes to Rdbms
[mediawiki.git] / includes / WatchedItemStore.php
blob9af5310ee10bac00cfa83599c203adc0f0555c10
1 <?php
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;
10 /**
11 * Storage layer class for WatchedItems.
12 * Database interaction.
14 * @author Addshore
16 * @since 1.27
18 class WatchedItemStore implements StatsdAwareInterface {
20 const SORT_DESC = 'DESC';
21 const SORT_ASC = 'ASC';
23 /**
24 * @var LoadBalancer
26 private $loadBalancer;
28 /**
29 * @var HashBagOStuff
31 private $cache;
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.
39 private $cacheIndex = [];
41 /**
42 * @var callable|null
44 private $deferredUpdatesAddCallableUpdateCallback;
46 /**
47 * @var callable|null
49 private $revisionGetTimestampFromIdCallback;
51 /**
52 * @var StatsdDataFactoryInterface
54 private $stats;
56 /**
57 * @param LoadBalancer $loadBalancer
58 * @param HashBagOStuff $cache
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' ];
71 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
72 $this->stats = $stats;
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.
79 * @param callable $callback
81 * @see DeferredUpdates::addCallableUpdate for callback signiture
83 * @return ScopedCallback to reset the overridden value
84 * @throws MWException
86 public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
87 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
88 throw new MWException(
89 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
92 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback;
93 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
94 return new ScopedCallback( function() use ( $previousValue ) {
95 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
96 } );
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.
103 * @param callable $callback
104 * @see Revision::getTimestampFromId for callback signiture
106 * @return ScopedCallback to reset the overridden value
107 * @throws MWException
109 public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
110 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
111 throw new MWException(
112 'Cannot override Revision::getTimestampFromId callback in operation.'
115 $previousValue = $this->revisionGetTimestampFromIdCallback;
116 $this->revisionGetTimestampFromIdCallback = $callback;
117 return new ScopedCallback( function() use ( $previousValue ) {
118 $this->revisionGetTimestampFromIdCallback = $previousValue;
119 } );
122 private function getCacheKey( User $user, LinkTarget $target ) {
123 return $this->cache->makeKey(
124 (string)$target->getNamespace(),
125 $target->getDBkey(),
126 (string)$user->getId()
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' );
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' );
145 private function uncacheLinkTarget( LinkTarget $target ) {
146 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
147 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
148 return;
150 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
151 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
152 $this->cache->delete( $key );
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()] );
169 * @param User $user
170 * @param LinkTarget $target
172 * @return WatchedItem|false
174 private function getCached( User $user, LinkTarget $target ) {
175 return $this->cache->get( $this->getCacheKey( $user, $target ) );
179 * Return an array of conditions to select or update the appropriate database
180 * row.
182 * @param User $user
183 * @param LinkTarget $target
185 * @return array
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(),
196 * @param int $dbIndex DB_MASTER or DB_REPLICA
198 * @return IDatabase
199 * @throws MWException
201 private function getConnectionRef( $dbIndex ) {
202 return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
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.
209 * @param User $user
211 * @return int
213 public function countWatchedItems( User $user ) {
214 $dbr = $this->getConnectionRef( DB_REPLICA );
215 $return = (int)$dbr->selectField(
216 'watchlist',
217 'COUNT(*)',
219 'wl_user' => $user->getId()
221 __METHOD__
224 return $return;
228 * @param LinkTarget $target
230 * @return int
232 public function countWatchers( LinkTarget $target ) {
233 $dbr = $this->getConnectionRef( DB_REPLICA );
234 $return = (int)$dbr->selectField(
235 'watchlist',
236 'COUNT(*)',
238 'wl_namespace' => $target->getNamespace(),
239 'wl_title' => $target->getDBkey(),
241 __METHOD__
244 return $return;
248 * Number of page watchers who also visited a "recent" edit
250 * @param LinkTarget $target
251 * @param mixed $threshold timestamp accepted by wfTimestamp
253 * @return int
254 * @throws DBUnexpectedError
255 * @throws MWException
257 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
258 $dbr = $this->getConnectionRef( DB_REPLICA );
259 $visitingWatchers = (int)$dbr->selectField(
260 'watchlist',
261 'COUNT(*)',
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'
269 __METHOD__
272 return $visitingWatchers;
276 * @param LinkTarget[] $targets
277 * @param array $options Allowed keys:
278 * 'minimumWatchers' => int
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.
284 public function countWatchersMultiple( array $targets, array $options = [] ) {
285 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
287 $dbr = $this->getConnectionRef( DB_REPLICA );
289 if ( array_key_exists( 'minimumWatchers', $options ) ) {
290 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
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
302 $watchCounts = [];
303 foreach ( $targets as $linkTarget ) {
304 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
307 foreach ( $res as $row ) {
308 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
311 return $watchCounts;
315 * Number of watchers of each page who have visited recent edits to that page
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).
329 public function countVisitingWatchersMultiple(
330 array $targetsWithVisitThresholds,
331 $minimumWatchers = null
333 $dbr = $this->getConnectionRef( DB_REPLICA );
335 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
337 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
338 if ( $minimumWatchers !== null ) {
339 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
341 $res = $dbr->select(
342 'watchlist',
343 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
344 $conds,
345 __METHOD__,
346 $dbOptions
349 $watcherCounts = [];
350 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
351 /* @var LinkTarget $target */
352 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
355 foreach ( $res as $row ) {
356 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
359 return $watcherCounts;
363 * Generates condition for the query used in a batch count visiting watchers.
365 * @param IDatabase $db
366 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
367 * @return string
369 private function getVisitingWatchersCondition(
370 IDatabase $db,
371 array $targetsWithVisitThresholds
373 $missingTargets = [];
374 $namespaceConds = [];
375 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
376 if ( $threshold === null ) {
377 $missingTargets[] = $target;
378 continue;
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 );
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 );
398 if ( $missingTargets ) {
399 $lb = new LinkBatch( $missingTargets );
400 $conds[] = $lb->constructSet( 'wl', $db );
403 return $db->makeList( $conds, LIST_OR );
407 * Get an item (may be cached)
409 * @param User $user
410 * @param LinkTarget $target
412 * @return WatchedItem|false
414 public function getWatchedItem( User $user, LinkTarget $target ) {
415 if ( $user->isAnon() ) {
416 return false;
419 $cached = $this->getCached( $user, $target );
420 if ( $cached ) {
421 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
422 return $cached;
424 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
425 return $this->loadWatchedItem( $user, $target );
429 * Loads an item from the db
431 * @param User $user
432 * @param LinkTarget $target
434 * @return WatchedItem|false
436 public function loadWatchedItem( User $user, LinkTarget $target ) {
437 // Only loggedin user can have a watchlist
438 if ( $user->isAnon() ) {
439 return false;
442 $dbr = $this->getConnectionRef( DB_REPLICA );
443 $row = $dbr->selectRow(
444 'watchlist',
445 'wl_notificationtimestamp',
446 $this->dbCond( $user, $target ),
447 __METHOD__
450 if ( !$row ) {
451 return false;
454 $item = new WatchedItem(
455 $user,
456 $target,
457 $row->wl_notificationtimestamp
459 $this->cache( $item );
461 return $item;
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
471 * @return WatchedItem[]
473 public function getWatchedItemsForUser( User $user, array $options = [] ) {
474 $options += [ 'forWrite' => false ];
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'
483 $dbOptions['ORDER BY'] = [
484 "wl_namespace {$options['sort']}",
485 "wl_title {$options['sort']}"
488 $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
490 $res = $db->select(
491 'watchlist',
492 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
493 [ 'wl_user' => $user->getId() ],
494 __METHOD__,
495 $dbOptions
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
508 return $watchedItems;
512 * Must be called separately for Subject & Talk namespaces
514 * @param User $user
515 * @param LinkTarget $target
517 * @return bool
519 public function isWatched( User $user, LinkTarget $target ) {
520 return (bool)$this->getWatchedItem( $user, $target );
524 * @param User $user
525 * @param LinkTarget[] $targets
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.
532 public function getNotificationTimestampsBatch( User $user, array $targets ) {
533 $timestamps = [];
534 foreach ( $targets as $target ) {
535 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
538 if ( $user->isAnon() ) {
539 return $timestamps;
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;
553 if ( !$targetsToLoad ) {
554 return $timestamps;
557 $dbr = $this->getConnectionRef( DB_REPLICA );
559 $lb = new LinkBatch( $targetsToLoad );
560 $res = $dbr->select(
561 'watchlist',
562 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
564 $lb->constructSet( 'wl', $dbr ),
565 'wl_user' => $user->getId(),
567 __METHOD__
570 foreach ( $res as $row ) {
571 $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
574 return $timestamps;
578 * Must be called separately for Subject & Talk namespaces
580 * @param User $user
581 * @param LinkTarget $target
583 public function addWatch( User $user, LinkTarget $target ) {
584 $this->addWatchBatchForUser( $user, [ $target ] );
588 * @param User $user
589 * @param LinkTarget[] $targets
591 * @return bool success
593 public function addWatchBatchForUser( User $user, array $targets ) {
594 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
595 return false;
597 // Only loggedin user can have a watchlist
598 if ( $user->isAnon() ) {
599 return false;
602 if ( !$targets ) {
603 return true;
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,
615 $items[] = new WatchedItem(
616 $user,
617 $target,
618 null
620 $this->uncache( $user, $target );
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' );
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 );
636 return true;
640 * Removes the an entry for the User watching the LinkTarget
641 * Must be called separately for Subject & Talk namespaces
643 * @param User $user
644 * @param LinkTarget $target
646 * @return bool success
647 * @throws DBUnexpectedError
648 * @throws MWException
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;
656 $this->uncache( $user, $target );
658 $dbw = $this->getConnectionRef( DB_MASTER );
659 $dbw->delete( 'watchlist',
661 'wl_user' => $user->getId(),
662 'wl_namespace' => $target->getNamespace(),
663 'wl_title' => $target->getDBkey(),
664 ], __METHOD__
666 $success = (bool)$dbw->affectedRows();
668 return $success;
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
676 * @return bool success
678 public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
679 // Only loggedin user can have a watchlist
680 if ( $user->isAnon() ) {
681 return false;
684 $dbw = $this->getConnectionRef( DB_MASTER );
686 $conds = [ 'wl_user' => $user->getId() ];
687 if ( $targets ) {
688 $batch = new LinkBatch( $targets );
689 $conds[] = $batch->constructSet( 'wl', $dbw );
692 if ( $timestamp !== null ) {
693 $timestamp = $dbw->timestamp( $timestamp );
696 $success = $dbw->update(
697 'watchlist',
698 [ 'wl_notificationtimestamp' => $timestamp ],
699 $conds,
700 __METHOD__
703 $this->uncacheUser( $user );
705 return $success;
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
714 * @return int[] Array of user IDs the timestamp has been updated for
716 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
717 $dbw = $this->getConnectionRef( DB_MASTER );
718 $uids = $dbw->selectFieldValues(
719 'watchlist',
720 'wl_user',
722 'wl_user != ' . intval( $editor->getId() ),
723 'wl_namespace' => $target->getNamespace(),
724 'wl_title' => $target->getDBkey(),
725 'wl_notificationtimestamp IS NULL',
727 __METHOD__
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;
738 $dbw = $this->getConnectionRef( DB_MASTER );
739 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
740 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
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
753 if ( count( $watchersChunks ) > 1 ) {
754 $factory->commitAndWaitForReplication(
755 __METHOD__, $ticket, [ 'wiki' => $dbw->getWikiID() ]
759 $this->uncacheLinkTarget( $target );
761 DeferredUpdates::POSTSEND,
762 $dbw
766 return $watchers;
770 * Reset the notification timestamp of this entry
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.
779 * @return bool success
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;
787 $item = null;
788 if ( $force != 'force' ) {
789 $item = $this->loadWatchedItem( $user, $title );
790 if ( !$item || $item->getNotificationTimestamp() === null ) {
791 return false;
795 // If the page is watched by the user (or may be watched), update the timestamp
796 $job = new ActivityUpdateJob(
797 $title,
799 'type' => 'updateWatchlistNotification',
800 'userid' => $user->getId(),
801 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
802 'curTime' => time()
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();
815 $this->uncache( $user, $title );
817 return true;
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;
826 if ( !$title->getNextRevisionID( $oldid ) ) {
827 // Oldid given and is the latest revision for this title; clear the timestamp.
828 return null;
831 if ( $item === null ) {
832 $item = $this->loadWatchedItem( $user, $title );
835 if ( !$item ) {
836 // This can only happen if $force is enabled.
837 return null;
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
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 );
855 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
856 if ( $force != 'force' ) {
857 return false;
858 } else {
859 // This is a little silly…
860 return $item->getNotificationTimestamp();
864 return $notificationTimestamp;
868 * @param User $user
869 * @param int $unreadLimit
871 * @return int|bool The number of unread notifications
872 * true if greater than or equal to $unreadLimit
874 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
875 $queryOptions = [];
876 if ( $unreadLimit !== null ) {
877 $unreadLimit = (int)$unreadLimit;
878 $queryOptions['LIMIT'] = $unreadLimit;
881 $dbr = $this->getConnectionRef( DB_REPLICA );
882 $rowCount = $dbr->selectRowCount(
883 'watchlist',
884 '1',
886 'wl_user' => $user->getId(),
887 'wl_notificationtimestamp IS NOT NULL',
889 __METHOD__,
890 $queryOptions
893 if ( !isset( $unreadLimit ) ) {
894 return $rowCount;
897 if ( $rowCount >= $unreadLimit ) {
898 return true;
901 return $rowCount;
905 * Check if the given title already is watched by the user, and if so
906 * add a watch for the new title.
908 * To be used for page renames and such.
910 * @param LinkTarget $oldTarget
911 * @param LinkTarget $newTarget
913 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
914 $oldTarget = Title::newFromLinkTarget( $oldTarget );
915 $newTarget = Title::newFromLinkTarget( $newTarget );
917 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
918 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
922 * Check if the given title already is watched by the user, and if so
923 * add a watch for the new title.
925 * To be used for page renames and such.
926 * This must be called separately for Subject and Talk pages
928 * @param LinkTarget $oldTarget
929 * @param LinkTarget $newTarget
931 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
932 $dbw = $this->getConnectionRef( DB_MASTER );
934 $result = $dbw->select(
935 'watchlist',
936 [ 'wl_user', 'wl_notificationtimestamp' ],
938 'wl_namespace' => $oldTarget->getNamespace(),
939 'wl_title' => $oldTarget->getDBkey(),
941 __METHOD__,
942 [ 'FOR UPDATE' ]
945 $newNamespace = $newTarget->getNamespace();
946 $newDBkey = $newTarget->getDBkey();
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,
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__