Make position time APC key in LoadBalancer more Het-Deploy friendly
[mediawiki.git] / includes / WatchedItemStore.php
blob858d87bc591208e640cbb02ccb48a818b5685756
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;
9 /**
10 * Storage layer class for WatchedItems.
11 * Database interaction.
13 * @author Addshore
15 * @since 1.27
17 class WatchedItemStore implements StatsdAwareInterface {
19 const SORT_DESC = 'DESC';
20 const SORT_ASC = 'ASC';
22 /**
23 * @var LoadBalancer
25 private $loadBalancer;
27 /**
28 * @var HashBagOStuff
30 private $cache;
32 /**
33 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
34 * The index is needed so that on mass changes all relevant items can be un-cached.
35 * For example: Clearing a users watchlist of all items or updating notification timestamps
36 * for all users watching a single target.
38 private $cacheIndex = [];
40 /**
41 * @var callable|null
43 private $deferredUpdatesAddCallableUpdateCallback;
45 /**
46 * @var callable|null
48 private $revisionGetTimestampFromIdCallback;
50 /**
51 * @var StatsdDataFactoryInterface
53 private $stats;
55 /**
56 * @param LoadBalancer $loadBalancer
57 * @param HashBagOStuff $cache
59 public function __construct(
60 LoadBalancer $loadBalancer,
61 HashBagOStuff $cache
62 ) {
63 $this->loadBalancer = $loadBalancer;
64 $this->cache = $cache;
65 $this->stats = new NullStatsdDataFactory();
66 $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
67 $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
70 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
71 $this->stats = $stats;
74 /**
75 * Overrides the DeferredUpdates::addCallableUpdate callback
76 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
78 * @param callable $callback
80 * @see DeferredUpdates::addCallableUpdate for callback signiture
82 * @return ScopedCallback to reset the overridden value
83 * @throws MWException
85 public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
86 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
87 throw new MWException(
88 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
91 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback;
92 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
93 return new ScopedCallback( function() use ( $previousValue ) {
94 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
95 } );
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.
102 * @param callable $callback
103 * @see Revision::getTimestampFromId for callback signiture
105 * @return ScopedCallback to reset the overridden value
106 * @throws MWException
108 public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
109 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
110 throw new MWException(
111 'Cannot override Revision::getTimestampFromId callback in operation.'
114 $previousValue = $this->revisionGetTimestampFromIdCallback;
115 $this->revisionGetTimestampFromIdCallback = $callback;
116 return new ScopedCallback( function() use ( $previousValue ) {
117 $this->revisionGetTimestampFromIdCallback = $previousValue;
118 } );
121 private function getCacheKey( User $user, LinkTarget $target ) {
122 return $this->cache->makeKey(
123 (string)$target->getNamespace(),
124 $target->getDBkey(),
125 (string)$user->getId()
129 private function cache( WatchedItem $item ) {
130 $user = $item->getUser();
131 $target = $item->getLinkTarget();
132 $key = $this->getCacheKey( $user, $target );
133 $this->cache->set( $key, $item );
134 $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
135 $this->stats->increment( 'WatchedItemStore.cache' );
138 private function uncache( User $user, LinkTarget $target ) {
139 $this->cache->delete( $this->getCacheKey( $user, $target ) );
140 unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
141 $this->stats->increment( 'WatchedItemStore.uncache' );
144 private function uncacheLinkTarget( LinkTarget $target ) {
145 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
146 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
147 return;
149 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
150 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
151 $this->cache->delete( $key );
155 private function uncacheUser( User $user ) {
156 $this->stats->increment( 'WatchedItemStore.uncacheUser' );
157 foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
158 foreach ( $dbKeyArray as $dbKey => $userArray ) {
159 if ( isset( $userArray[$user->getId()] ) ) {
160 $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
161 $this->cache->delete( $userArray[$user->getId()] );
168 * @param User $user
169 * @param LinkTarget $target
171 * @return WatchedItem|false
173 private function getCached( User $user, LinkTarget $target ) {
174 return $this->cache->get( $this->getCacheKey( $user, $target ) );
178 * Return an array of conditions to select or update the appropriate database
179 * row.
181 * @param User $user
182 * @param LinkTarget $target
184 * @return array
186 private function dbCond( User $user, LinkTarget $target ) {
187 return [
188 'wl_user' => $user->getId(),
189 'wl_namespace' => $target->getNamespace(),
190 'wl_title' => $target->getDBkey(),
195 * @param int $dbIndex DB_MASTER or DB_REPLICA
197 * @return IDatabase
198 * @throws MWException
200 private function getConnectionRef( $dbIndex ) {
201 return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
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.
208 * @param User $user
210 * @return int
212 public function countWatchedItems( User $user ) {
213 $dbr = $this->getConnectionRef( DB_REPLICA );
214 $return = (int)$dbr->selectField(
215 'watchlist',
216 'COUNT(*)',
218 'wl_user' => $user->getId()
220 __METHOD__
223 return $return;
227 * @param LinkTarget $target
229 * @return int
231 public function countWatchers( LinkTarget $target ) {
232 $dbr = $this->getConnectionRef( DB_REPLICA );
233 $return = (int)$dbr->selectField(
234 'watchlist',
235 'COUNT(*)',
237 'wl_namespace' => $target->getNamespace(),
238 'wl_title' => $target->getDBkey(),
240 __METHOD__
243 return $return;
247 * Number of page watchers who also visited a "recent" edit
249 * @param LinkTarget $target
250 * @param mixed $threshold timestamp accepted by wfTimestamp
252 * @return int
253 * @throws DBUnexpectedError
254 * @throws MWException
256 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
257 $dbr = $this->getConnectionRef( DB_REPLICA );
258 $visitingWatchers = (int)$dbr->selectField(
259 'watchlist',
260 'COUNT(*)',
262 'wl_namespace' => $target->getNamespace(),
263 'wl_title' => $target->getDBkey(),
264 'wl_notificationtimestamp >= ' .
265 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
266 ' OR wl_notificationtimestamp IS NULL'
268 __METHOD__
271 return $visitingWatchers;
275 * @param LinkTarget[] $targets
276 * @param array $options Allowed keys:
277 * 'minimumWatchers' => int
279 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
280 * All targets will be present in the result. 0 either means no watchers or the number
281 * of watchers was below the minimumWatchers option if passed.
283 public function countWatchersMultiple( array $targets, array $options = [] ) {
284 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
286 $dbr = $this->getConnectionRef( DB_REPLICA );
288 if ( array_key_exists( 'minimumWatchers', $options ) ) {
289 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
292 $lb = new LinkBatch( $targets );
293 $res = $dbr->select(
294 'watchlist',
295 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
296 [ $lb->constructSet( 'wl', $dbr ) ],
297 __METHOD__,
298 $dbOptions
301 $watchCounts = [];
302 foreach ( $targets as $linkTarget ) {
303 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
306 foreach ( $res as $row ) {
307 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
310 return $watchCounts;
314 * Number of watchers of each page who have visited recent edits to that page
316 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget $target, mixed $threshold),
317 * $threshold is:
318 * - a timestamp of the recent edit if $target exists (format accepted by wfTimestamp)
319 * - null if $target doesn't exist
320 * @param int|null $minimumWatchers
321 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $watchers,
322 * where $watchers is an int:
323 * - if the page exists, number of users watching who have visited the page recently
324 * - if the page doesn't exist, number of users that have the page on their watchlist
325 * - 0 means there are no visiting watchers or their number is below the minimumWatchers
326 * option (if passed).
328 public function countVisitingWatchersMultiple(
329 array $targetsWithVisitThresholds,
330 $minimumWatchers = null
332 $dbr = $this->getConnectionRef( DB_REPLICA );
334 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
336 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
337 if ( $minimumWatchers !== null ) {
338 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
340 $res = $dbr->select(
341 'watchlist',
342 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
343 $conds,
344 __METHOD__,
345 $dbOptions
348 $watcherCounts = [];
349 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
350 /* @var LinkTarget $target */
351 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
354 foreach ( $res as $row ) {
355 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
358 return $watcherCounts;
362 * Generates condition for the query used in a batch count visiting watchers.
364 * @param IDatabase $db
365 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
366 * @return string
368 private function getVisitingWatchersCondition(
369 IDatabase $db,
370 array $targetsWithVisitThresholds
372 $missingTargets = [];
373 $namespaceConds = [];
374 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
375 if ( $threshold === null ) {
376 $missingTargets[] = $target;
377 continue;
379 /* @var LinkTarget $target */
380 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
381 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
382 $db->makeList( [
383 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
384 'wl_notificationtimestamp IS NULL'
385 ], LIST_OR )
386 ], LIST_AND );
389 $conds = [];
390 foreach ( $namespaceConds as $namespace => $pageConds ) {
391 $conds[] = $db->makeList( [
392 'wl_namespace = ' . $namespace,
393 '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
394 ], LIST_AND );
397 if ( $missingTargets ) {
398 $lb = new LinkBatch( $missingTargets );
399 $conds[] = $lb->constructSet( 'wl', $db );
402 return $db->makeList( $conds, LIST_OR );
406 * Get an item (may be cached)
408 * @param User $user
409 * @param LinkTarget $target
411 * @return WatchedItem|false
413 public function getWatchedItem( User $user, LinkTarget $target ) {
414 if ( $user->isAnon() ) {
415 return false;
418 $cached = $this->getCached( $user, $target );
419 if ( $cached ) {
420 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
421 return $cached;
423 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
424 return $this->loadWatchedItem( $user, $target );
428 * Loads an item from the db
430 * @param User $user
431 * @param LinkTarget $target
433 * @return WatchedItem|false
435 public function loadWatchedItem( User $user, LinkTarget $target ) {
436 // Only loggedin user can have a watchlist
437 if ( $user->isAnon() ) {
438 return false;
441 $dbr = $this->getConnectionRef( DB_REPLICA );
442 $row = $dbr->selectRow(
443 'watchlist',
444 'wl_notificationtimestamp',
445 $this->dbCond( $user, $target ),
446 __METHOD__
449 if ( !$row ) {
450 return false;
453 $item = new WatchedItem(
454 $user,
455 $target,
456 $row->wl_notificationtimestamp
458 $this->cache( $item );
460 return $item;
464 * @param User $user
465 * @param array $options Allowed keys:
466 * 'forWrite' => bool defaults to false
467 * 'sort' => string optional sorting by namespace ID and title
468 * one of the self::SORT_* constants
470 * @return WatchedItem[]
472 public function getWatchedItemsForUser( User $user, array $options = [] ) {
473 $options += [ 'forWrite' => false ];
475 $dbOptions = [];
476 if ( array_key_exists( 'sort', $options ) ) {
477 Assert::parameter(
478 ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
479 '$options[\'sort\']',
480 'must be SORT_ASC or SORT_DESC'
482 $dbOptions['ORDER BY'] = [
483 "wl_namespace {$options['sort']}",
484 "wl_title {$options['sort']}"
487 $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
489 $res = $db->select(
490 'watchlist',
491 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
492 [ 'wl_user' => $user->getId() ],
493 __METHOD__,
494 $dbOptions
497 $watchedItems = [];
498 foreach ( $res as $row ) {
499 // @todo: Should we add these to the process cache?
500 $watchedItems[] = new WatchedItem(
501 $user,
502 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
503 $row->wl_notificationtimestamp
507 return $watchedItems;
511 * Must be called separately for Subject & Talk namespaces
513 * @param User $user
514 * @param LinkTarget $target
516 * @return bool
518 public function isWatched( User $user, LinkTarget $target ) {
519 return (bool)$this->getWatchedItem( $user, $target );
523 * @param User $user
524 * @param LinkTarget[] $targets
526 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $timestamp,
527 * where $timestamp is:
528 * - string|null value of wl_notificationtimestamp,
529 * - false if $target is not watched by $user.
531 public function getNotificationTimestampsBatch( User $user, array $targets ) {
532 $timestamps = [];
533 foreach ( $targets as $target ) {
534 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
537 if ( $user->isAnon() ) {
538 return $timestamps;
541 $targetsToLoad = [];
542 foreach ( $targets as $target ) {
543 $cachedItem = $this->getCached( $user, $target );
544 if ( $cachedItem ) {
545 $timestamps[$target->getNamespace()][$target->getDBkey()] =
546 $cachedItem->getNotificationTimestamp();
547 } else {
548 $targetsToLoad[] = $target;
552 if ( !$targetsToLoad ) {
553 return $timestamps;
556 $dbr = $this->getConnectionRef( DB_REPLICA );
558 $lb = new LinkBatch( $targetsToLoad );
559 $res = $dbr->select(
560 'watchlist',
561 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
563 $lb->constructSet( 'wl', $dbr ),
564 'wl_user' => $user->getId(),
566 __METHOD__
569 foreach ( $res as $row ) {
570 $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
573 return $timestamps;
577 * Must be called separately for Subject & Talk namespaces
579 * @param User $user
580 * @param LinkTarget $target
582 public function addWatch( User $user, LinkTarget $target ) {
583 $this->addWatchBatchForUser( $user, [ $target ] );
587 * @param User $user
588 * @param LinkTarget[] $targets
590 * @return bool success
592 public function addWatchBatchForUser( User $user, array $targets ) {
593 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
594 return false;
596 // Only loggedin user can have a watchlist
597 if ( $user->isAnon() ) {
598 return false;
601 if ( !$targets ) {
602 return true;
605 $rows = [];
606 $items = [];
607 foreach ( $targets as $target ) {
608 $rows[] = [
609 'wl_user' => $user->getId(),
610 'wl_namespace' => $target->getNamespace(),
611 'wl_title' => $target->getDBkey(),
612 'wl_notificationtimestamp' => null,
614 $items[] = new WatchedItem(
615 $user,
616 $target,
617 null
619 $this->uncache( $user, $target );
622 $dbw = $this->getConnectionRef( DB_MASTER );
623 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
624 // Use INSERT IGNORE to avoid overwriting the notification timestamp
625 // if there's already an entry for this page
626 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
628 // Update process cache to ensure skin doesn't claim that the current
629 // page is unwatched in the response of action=watch itself (T28292).
630 // This would otherwise be re-queried from a slave by isWatched().
631 foreach ( $items as $item ) {
632 $this->cache( $item );
635 return true;
639 * Removes the an entry for the User watching the LinkTarget
640 * Must be called separately for Subject & Talk namespaces
642 * @param User $user
643 * @param LinkTarget $target
645 * @return bool success
646 * @throws DBUnexpectedError
647 * @throws MWException
649 public function removeWatch( User $user, LinkTarget $target ) {
650 // Only logged in user can have a watchlist
651 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
652 return false;
655 $this->uncache( $user, $target );
657 $dbw = $this->getConnectionRef( DB_MASTER );
658 $dbw->delete( 'watchlist',
660 'wl_user' => $user->getId(),
661 'wl_namespace' => $target->getNamespace(),
662 'wl_title' => $target->getDBkey(),
663 ], __METHOD__
665 $success = (bool)$dbw->affectedRows();
667 return $success;
671 * @param User $user The user to set the timestamp for
672 * @param string|null $timestamp Set the update timestamp to this value
673 * @param LinkTarget[] $targets List of targets to update. Default to all targets
675 * @return bool success
677 public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
678 // Only loggedin user can have a watchlist
679 if ( $user->isAnon() ) {
680 return false;
683 $dbw = $this->getConnectionRef( DB_MASTER );
685 $conds = [ 'wl_user' => $user->getId() ];
686 if ( $targets ) {
687 $batch = new LinkBatch( $targets );
688 $conds[] = $batch->constructSet( 'wl', $dbw );
691 if ( $timestamp !== null ) {
692 $timestamp = $dbw->timestamp( $timestamp );
695 $success = $dbw->update(
696 'watchlist',
697 [ 'wl_notificationtimestamp' => $timestamp ],
698 $conds,
699 __METHOD__
702 $this->uncacheUser( $user );
704 return $success;
708 * @param User $editor The editor that triggered the update. Their notification
709 * timestamp will not be updated(they have already seen it)
710 * @param LinkTarget $target The target to update timestamps for
711 * @param string $timestamp Set the update timestamp to this value
713 * @return int[] Array of user IDs the timestamp has been updated for
715 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
716 $dbw = $this->getConnectionRef( DB_MASTER );
717 $uids = $dbw->selectFieldValues(
718 'watchlist',
719 'wl_user',
721 'wl_user != ' . intval( $editor->getId() ),
722 'wl_namespace' => $target->getNamespace(),
723 'wl_title' => $target->getDBkey(),
724 'wl_notificationtimestamp IS NULL',
726 __METHOD__
729 $watchers = array_map( 'intval', $uids );
730 if ( $watchers ) {
731 // Update wl_notificationtimestamp for all watching users except the editor
732 $fname = __METHOD__;
733 DeferredUpdates::addCallableUpdate(
734 function () use ( $timestamp, $watchers, $target, $fname ) {
735 global $wgUpdateRowsPerQuery;
737 $dbw = $this->getConnectionRef( DB_MASTER );
738 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
739 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
741 $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
742 foreach ( $watchersChunks as $watchersChunk ) {
743 $dbw->update( 'watchlist',
744 [ /* SET */
745 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
746 ], [ /* WHERE - TODO Use wl_id T130067 */
747 'wl_user' => $watchersChunk,
748 'wl_namespace' => $target->getNamespace(),
749 'wl_title' => $target->getDBkey(),
750 ], $fname
752 if ( count( $watchersChunks ) > 1 ) {
753 $factory->commitAndWaitForReplication(
754 __METHOD__, $ticket, [ 'wiki' => $dbw->getWikiID() ]
758 $this->uncacheLinkTarget( $target );
760 DeferredUpdates::POSTSEND,
761 $dbw
765 return $watchers;
769 * Reset the notification timestamp of this entry
771 * @param User $user
772 * @param Title $title
773 * @param string $force Whether to force the write query to be executed even if the
774 * page is not watched or the notification timestamp is already NULL.
775 * 'force' in order to force
776 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
778 * @return bool success
780 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
781 // Only loggedin user can have a watchlist
782 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
783 return false;
786 $item = null;
787 if ( $force != 'force' ) {
788 $item = $this->loadWatchedItem( $user, $title );
789 if ( !$item || $item->getNotificationTimestamp() === null ) {
790 return false;
794 // If the page is watched by the user (or may be watched), update the timestamp
795 $job = new ActivityUpdateJob(
796 $title,
798 'type' => 'updateWatchlistNotification',
799 'userid' => $user->getId(),
800 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
801 'curTime' => time()
805 // Try to run this post-send
806 // Calls DeferredUpdates::addCallableUpdate in normal operation
807 call_user_func(
808 $this->deferredUpdatesAddCallableUpdateCallback,
809 function() use ( $job ) {
810 $job->run();
814 $this->uncache( $user, $title );
816 return true;
819 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
820 if ( !$oldid ) {
821 // No oldid given, assuming latest revision; clear the timestamp.
822 return null;
825 if ( !$title->getNextRevisionID( $oldid ) ) {
826 // Oldid given and is the latest revision for this title; clear the timestamp.
827 return null;
830 if ( $item === null ) {
831 $item = $this->loadWatchedItem( $user, $title );
834 if ( !$item ) {
835 // This can only happen if $force is enabled.
836 return null;
839 // Oldid given and isn't the latest; update the timestamp.
840 // This will result in no further notification emails being sent!
841 // Calls Revision::getTimestampFromId in normal operation
842 $notificationTimestamp = call_user_func(
843 $this->revisionGetTimestampFromIdCallback,
844 $title,
845 $oldid
848 // We need to go one second to the future because of various strict comparisons
849 // throughout the codebase
850 $ts = new MWTimestamp( $notificationTimestamp );
851 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
852 $notificationTimestamp = $ts->getTimestamp( TS_MW );
854 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
855 if ( $force != 'force' ) {
856 return false;
857 } else {
858 // This is a little silly…
859 return $item->getNotificationTimestamp();
863 return $notificationTimestamp;
867 * @param User $user
868 * @param int $unreadLimit
870 * @return int|bool The number of unread notifications
871 * true if greater than or equal to $unreadLimit
873 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
874 $queryOptions = [];
875 if ( $unreadLimit !== null ) {
876 $unreadLimit = (int)$unreadLimit;
877 $queryOptions['LIMIT'] = $unreadLimit;
880 $dbr = $this->getConnectionRef( DB_REPLICA );
881 $rowCount = $dbr->selectRowCount(
882 'watchlist',
883 '1',
885 'wl_user' => $user->getId(),
886 'wl_notificationtimestamp IS NOT NULL',
888 __METHOD__,
889 $queryOptions
892 if ( !isset( $unreadLimit ) ) {
893 return $rowCount;
896 if ( $rowCount >= $unreadLimit ) {
897 return true;
900 return $rowCount;
904 * Check if the given title already is watched by the user, and if so
905 * add a watch for the new title.
907 * To be used for page renames and such.
909 * @param LinkTarget $oldTarget
910 * @param LinkTarget $newTarget
912 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
913 $oldTarget = Title::newFromLinkTarget( $oldTarget );
914 $newTarget = Title::newFromLinkTarget( $newTarget );
916 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
917 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
921 * Check if the given title already is watched by the user, and if so
922 * add a watch for the new title.
924 * To be used for page renames and such.
925 * This must be called separately for Subject and Talk pages
927 * @param LinkTarget $oldTarget
928 * @param LinkTarget $newTarget
930 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
931 $dbw = $this->getConnectionRef( DB_MASTER );
933 $result = $dbw->select(
934 'watchlist',
935 [ 'wl_user', 'wl_notificationtimestamp' ],
937 'wl_namespace' => $oldTarget->getNamespace(),
938 'wl_title' => $oldTarget->getDBkey(),
940 __METHOD__,
941 [ 'FOR UPDATE' ]
944 $newNamespace = $newTarget->getNamespace();
945 $newDBkey = $newTarget->getDBkey();
947 # Construct array to replace into the watchlist
948 $values = [];
949 foreach ( $result as $row ) {
950 $values[] = [
951 'wl_user' => $row->wl_user,
952 'wl_namespace' => $newNamespace,
953 'wl_title' => $newDBkey,
954 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
958 if ( !empty( $values ) ) {
959 # Perform replace
960 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
961 # some other DBMSes, mostly due to poor simulation by us
962 $dbw->replace(
963 'watchlist',
964 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
965 $values,
966 __METHOD__