API: Fixes for AuthManager
[mediawiki.git] / includes / WatchedItemStore.php
blob6486955fc4887c471f9006448c62e14f1bf6144b
1 <?php
3 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
4 use MediaWiki\MediaWikiServices;
5 use MediaWiki\Linker\LinkTarget;
6 use Wikimedia\Assert\Assert;
8 /**
9 * Storage layer class for WatchedItems.
10 * Database interaction.
12 * @author Addshore
14 * @since 1.27
16 class WatchedItemStore implements StatsdAwareInterface {
18 const SORT_DESC = 'DESC';
19 const SORT_ASC = 'ASC';
21 /**
22 * @var LoadBalancer
24 private $loadBalancer;
26 /**
27 * @var HashBagOStuff
29 private $cache;
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.
37 private $cacheIndex = [];
39 /**
40 * @var callable|null
42 private $deferredUpdatesAddCallableUpdateCallback;
44 /**
45 * @var callable|null
47 private $revisionGetTimestampFromIdCallback;
49 /**
50 * @var StatsdDataFactoryInterface
52 private $stats;
54 /**
55 * @param LoadBalancer $loadBalancer
56 * @param HashBagOStuff $cache
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' ];
69 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
70 $this->stats = $stats;
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.
77 * @param callable $callback
79 * @see DeferredUpdates::addCallableUpdate for callback signiture
81 * @return ScopedCallback to reset the overridden value
82 * @throws MWException
84 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
85 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
86 throw new MWException(
87 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
90 Assert::parameterType( 'callable', $callback, '$callback' );
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( $callback ) {
110 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
111 throw new MWException(
112 'Cannot override Revision::getTimestampFromId callback in operation.'
115 Assert::parameterType( 'callable', $callback, '$callback' );
117 $previousValue = $this->revisionGetTimestampFromIdCallback;
118 $this->revisionGetTimestampFromIdCallback = $callback;
119 return new ScopedCallback( function() use ( $previousValue ) {
120 $this->revisionGetTimestampFromIdCallback = $previousValue;
121 } );
124 private function getCacheKey( User $user, LinkTarget $target ) {
125 return $this->cache->makeKey(
126 (string)$target->getNamespace(),
127 $target->getDBkey(),
128 (string)$user->getId()
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' );
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' );
147 private function uncacheLinkTarget( LinkTarget $target ) {
148 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
149 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
150 return;
152 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
153 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
154 $this->cache->delete( $key );
158 private function uncacheUser( User $user ) {
159 $this->stats->increment( 'WatchedItemStore.uncacheUser' );
160 foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
161 foreach ( $dbKeyArray as $dbKey => $userArray ) {
162 if ( isset( $userArray[$user->getId()] ) ) {
163 $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
164 $this->cache->delete( $userArray[$user->getId()] );
171 * @param User $user
172 * @param LinkTarget $target
174 * @return WatchedItem|null
176 private function getCached( User $user, LinkTarget $target ) {
177 return $this->cache->get( $this->getCacheKey( $user, $target ) );
181 * Return an array of conditions to select or update the appropriate database
182 * row.
184 * @param User $user
185 * @param LinkTarget $target
187 * @return array
189 private function dbCond( User $user, LinkTarget $target ) {
190 return [
191 'wl_user' => $user->getId(),
192 'wl_namespace' => $target->getNamespace(),
193 'wl_title' => $target->getDBkey(),
198 * @param int $slaveOrMaster DB_MASTER or DB_SLAVE
200 * @return DatabaseBase
201 * @throws MWException
203 private function getConnection( $slaveOrMaster ) {
204 return $this->loadBalancer->getConnection( $slaveOrMaster, [ 'watchlist' ] );
208 * @param DatabaseBase $connection
210 * @throws MWException
212 private function reuseConnection( $connection ) {
213 $this->loadBalancer->reuseConnection( $connection );
217 * Count the number of individual items that are watched by the user.
218 * If a subject and corresponding talk page are watched this will return 2.
220 * @param User $user
222 * @return int
224 public function countWatchedItems( User $user ) {
225 $dbr = $this->getConnection( DB_SLAVE );
226 $return = (int)$dbr->selectField(
227 'watchlist',
228 'COUNT(*)',
230 'wl_user' => $user->getId()
232 __METHOD__
234 $this->reuseConnection( $dbr );
236 return $return;
240 * @param LinkTarget $target
242 * @return int
244 public function countWatchers( LinkTarget $target ) {
245 $dbr = $this->getConnection( DB_SLAVE );
246 $return = (int)$dbr->selectField(
247 'watchlist',
248 'COUNT(*)',
250 'wl_namespace' => $target->getNamespace(),
251 'wl_title' => $target->getDBkey(),
253 __METHOD__
255 $this->reuseConnection( $dbr );
257 return $return;
261 * Number of page watchers who also visited a "recent" edit
263 * @param LinkTarget $target
264 * @param mixed $threshold timestamp accepted by wfTimestamp
266 * @return int
267 * @throws DBUnexpectedError
268 * @throws MWException
270 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
271 $dbr = $this->getConnection( DB_SLAVE );
272 $visitingWatchers = (int)$dbr->selectField(
273 'watchlist',
274 'COUNT(*)',
276 'wl_namespace' => $target->getNamespace(),
277 'wl_title' => $target->getDBkey(),
278 'wl_notificationtimestamp >= ' .
279 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
280 ' OR wl_notificationtimestamp IS NULL'
282 __METHOD__
284 $this->reuseConnection( $dbr );
286 return $visitingWatchers;
290 * @param LinkTarget[] $targets
291 * @param array $options Allowed keys:
292 * 'minimumWatchers' => int
294 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
295 * All targets will be present in the result. 0 either means no watchers or the number
296 * of watchers was below the minimumWatchers option if passed.
298 public function countWatchersMultiple( array $targets, array $options = [] ) {
299 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
301 $dbr = $this->getConnection( DB_SLAVE );
303 if ( array_key_exists( 'minimumWatchers', $options ) ) {
304 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
307 $lb = new LinkBatch( $targets );
308 $res = $dbr->select(
309 'watchlist',
310 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
311 [ $lb->constructSet( 'wl', $dbr ) ],
312 __METHOD__,
313 $dbOptions
316 $this->reuseConnection( $dbr );
318 $watchCounts = [];
319 foreach ( $targets as $linkTarget ) {
320 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
323 foreach ( $res as $row ) {
324 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
327 return $watchCounts;
331 * Number of watchers of each page who have visited recent edits to that page
333 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget $target, mixed $threshold),
334 * $threshold is:
335 * - a timestamp of the recent edit if $target exists (format accepted by wfTimestamp)
336 * - null if $target doesn't exist
337 * @param int|null $minimumWatchers
338 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $watchers,
339 * where $watchers is an int:
340 * - if the page exists, number of users watching who have visited the page recently
341 * - if the page doesn't exist, number of users that have the page on their watchlist
342 * - 0 means there are no visiting watchers or their number is below the minimumWatchers
343 * option (if passed).
345 public function countVisitingWatchersMultiple(
346 array $targetsWithVisitThresholds,
347 $minimumWatchers = null
349 $dbr = $this->getConnection( DB_SLAVE );
351 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
353 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
354 if ( $minimumWatchers !== null ) {
355 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
357 $res = $dbr->select(
358 'watchlist',
359 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
360 $conds,
361 __METHOD__,
362 $dbOptions
365 $this->reuseConnection( $dbr );
367 $watcherCounts = [];
368 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
369 /* @var LinkTarget $target */
370 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
373 foreach ( $res as $row ) {
374 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
377 return $watcherCounts;
381 * Generates condition for the query used in a batch count visiting watchers.
383 * @param IDatabase $db
384 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
385 * @return string
387 private function getVisitingWatchersCondition(
388 IDatabase $db,
389 array $targetsWithVisitThresholds
391 $missingTargets = [];
392 $namespaceConds = [];
393 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
394 if ( $threshold === null ) {
395 $missingTargets[] = $target;
396 continue;
398 /* @var LinkTarget $target */
399 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
400 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
401 $db->makeList( [
402 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
403 'wl_notificationtimestamp IS NULL'
404 ], LIST_OR )
405 ], LIST_AND );
408 $conds = [];
409 foreach ( $namespaceConds as $namespace => $pageConds ) {
410 $conds[] = $db->makeList( [
411 'wl_namespace = ' . $namespace,
412 '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
413 ], LIST_AND );
416 if ( $missingTargets ) {
417 $lb = new LinkBatch( $missingTargets );
418 $conds[] = $lb->constructSet( 'wl', $db );
421 return $db->makeList( $conds, LIST_OR );
425 * Get an item (may be cached)
427 * @param User $user
428 * @param LinkTarget $target
430 * @return WatchedItem|false
432 public function getWatchedItem( User $user, LinkTarget $target ) {
433 if ( $user->isAnon() ) {
434 return false;
437 $cached = $this->getCached( $user, $target );
438 if ( $cached ) {
439 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
440 return $cached;
442 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
443 return $this->loadWatchedItem( $user, $target );
447 * Loads an item from the db
449 * @param User $user
450 * @param LinkTarget $target
452 * @return WatchedItem|false
454 public function loadWatchedItem( User $user, LinkTarget $target ) {
455 // Only loggedin user can have a watchlist
456 if ( $user->isAnon() ) {
457 return false;
460 $dbr = $this->getConnection( DB_SLAVE );
461 $row = $dbr->selectRow(
462 'watchlist',
463 'wl_notificationtimestamp',
464 $this->dbCond( $user, $target ),
465 __METHOD__
467 $this->reuseConnection( $dbr );
469 if ( !$row ) {
470 return false;
473 $item = new WatchedItem(
474 $user,
475 $target,
476 $row->wl_notificationtimestamp
478 $this->cache( $item );
480 return $item;
484 * @param User $user
485 * @param array $options Allowed keys:
486 * 'forWrite' => bool defaults to false
487 * 'sort' => string optional sorting by namespace ID and title
488 * one of the self::SORT_* constants
490 * @return WatchedItem[]
492 public function getWatchedItemsForUser( User $user, array $options = [] ) {
493 $options += [ 'forWrite' => false ];
495 $dbOptions = [];
496 if ( array_key_exists( 'sort', $options ) ) {
497 Assert::parameter(
498 ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
499 '$options[\'sort\']',
500 'must be SORT_ASC or SORT_DESC'
502 $dbOptions['ORDER BY'] = [
503 "wl_namespace {$options['sort']}",
504 "wl_title {$options['sort']}"
507 $db = $this->getConnection( $options['forWrite'] ? DB_MASTER : DB_SLAVE );
509 $res = $db->select(
510 'watchlist',
511 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
512 [ 'wl_user' => $user->getId() ],
513 __METHOD__,
514 $dbOptions
516 $this->reuseConnection( $db );
518 $watchedItems = [];
519 foreach ( $res as $row ) {
520 // todo these could all be cached at some point?
521 $watchedItems[] = new WatchedItem(
522 $user,
523 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
524 $row->wl_notificationtimestamp
528 return $watchedItems;
532 * Must be called separately for Subject & Talk namespaces
534 * @param User $user
535 * @param LinkTarget $target
537 * @return bool
539 public function isWatched( User $user, LinkTarget $target ) {
540 return (bool)$this->getWatchedItem( $user, $target );
544 * @param User $user
545 * @param LinkTarget[] $targets
547 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $timestamp,
548 * where $timestamp is:
549 * - string|null value of wl_notificationtimestamp,
550 * - false if $target is not watched by $user.
552 public function getNotificationTimestampsBatch( User $user, array $targets ) {
553 $timestamps = [];
554 foreach ( $targets as $target ) {
555 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
558 if ( $user->isAnon() ) {
559 return $timestamps;
562 $targetsToLoad = [];
563 foreach ( $targets as $target ) {
564 $cachedItem = $this->getCached( $user, $target );
565 if ( $cachedItem ) {
566 $timestamps[$target->getNamespace()][$target->getDBkey()] =
567 $cachedItem->getNotificationTimestamp();
568 } else {
569 $targetsToLoad[] = $target;
573 if ( !$targetsToLoad ) {
574 return $timestamps;
577 $dbr = $this->getConnection( DB_SLAVE );
579 $lb = new LinkBatch( $targetsToLoad );
580 $res = $dbr->select(
581 'watchlist',
582 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
584 $lb->constructSet( 'wl', $dbr ),
585 'wl_user' => $user->getId(),
587 __METHOD__
589 $this->reuseConnection( $dbr );
591 foreach ( $res as $row ) {
592 $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
595 return $timestamps;
599 * Must be called separately for Subject & Talk namespaces
601 * @param User $user
602 * @param LinkTarget $target
604 public function addWatch( User $user, LinkTarget $target ) {
605 $this->addWatchBatchForUser( $user, [ $target ] );
609 * @param User $user
610 * @param LinkTarget[] $targets
612 * @return bool success
614 public function addWatchBatchForUser( User $user, array $targets ) {
615 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
616 return false;
618 // Only loggedin user can have a watchlist
619 if ( $user->isAnon() ) {
620 return false;
623 if ( !$targets ) {
624 return true;
627 $rows = [];
628 foreach ( $targets as $target ) {
629 $rows[] = [
630 'wl_user' => $user->getId(),
631 'wl_namespace' => $target->getNamespace(),
632 'wl_title' => $target->getDBkey(),
633 'wl_notificationtimestamp' => null,
635 $this->uncache( $user, $target );
638 $dbw = $this->getConnection( DB_MASTER );
639 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
640 // Use INSERT IGNORE to avoid overwriting the notification timestamp
641 // if there's already an entry for this page
642 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
644 $this->reuseConnection( $dbw );
646 return true;
650 * Removes the an entry for the User watching the LinkTarget
651 * Must be called separately for Subject & Talk namespaces
653 * @param User $user
654 * @param LinkTarget $target
656 * @return bool success
657 * @throws DBUnexpectedError
658 * @throws MWException
660 public function removeWatch( User $user, LinkTarget $target ) {
661 // Only logged in user can have a watchlist
662 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
663 return false;
666 $this->uncache( $user, $target );
668 $dbw = $this->getConnection( DB_MASTER );
669 $dbw->delete( 'watchlist',
671 'wl_user' => $user->getId(),
672 'wl_namespace' => $target->getNamespace(),
673 'wl_title' => $target->getDBkey(),
674 ], __METHOD__
676 $success = (bool)$dbw->affectedRows();
677 $this->reuseConnection( $dbw );
679 return $success;
683 * @param User $user The user to set the timestamp for
684 * @param string $timestamp Set the update timestamp to this value
685 * @param LinkTarget[] $targets List of targets to update. Default to all targets
687 * @return bool success
689 public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
690 // Only loggedin user can have a watchlist
691 if ( $user->isAnon() ) {
692 return false;
695 $dbw = $this->getConnection( DB_MASTER );
697 $conds = [ 'wl_user' => $user->getId() ];
698 if ( $targets ) {
699 $batch = new LinkBatch( $targets );
700 $conds[] = $batch->constructSet( 'wl', $dbw );
703 $success = $dbw->update(
704 'watchlist',
705 [ 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp ) ],
706 $conds,
707 __METHOD__
710 $this->reuseConnection( $dbw );
712 $this->uncacheUser( $user );
714 return $success;
718 * @param User $editor The editor that triggered the update. Their notification
719 * timestamp will not be updated(they have already seen it)
720 * @param LinkTarget $target The target to update timestamps for
721 * @param string $timestamp Set the update timestamp to this value
723 * @return int[] Array of user IDs the timestamp has been updated for
725 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
726 $dbw = $this->getConnection( DB_MASTER );
727 $res = $dbw->select( [ 'watchlist' ],
728 [ 'wl_user' ],
730 'wl_user != ' . intval( $editor->getId() ),
731 'wl_namespace' => $target->getNamespace(),
732 'wl_title' => $target->getDBkey(),
733 'wl_notificationtimestamp IS NULL',
734 ], __METHOD__
737 $watchers = [];
738 foreach ( $res as $row ) {
739 $watchers[] = intval( $row->wl_user );
742 if ( $watchers ) {
743 // Update wl_notificationtimestamp for all watching users except the editor
744 $fname = __METHOD__;
745 $dbw->onTransactionIdle(
746 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
747 global $wgUpdateRowsPerQuery;
749 $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
750 foreach ( $watchersChunks as $watchersChunk ) {
751 $dbw->update( 'watchlist',
752 [ /* SET */
753 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
754 ], [ /* WHERE - TODO Use wl_id T130067 */
755 'wl_user' => $watchersChunk,
756 'wl_namespace' => $target->getNamespace(),
757 'wl_title' => $target->getDBkey(),
758 ], $fname
760 if ( count( $watchersChunks ) > 1 ) {
761 $dbw->commit( __METHOD__, 'flush' );
762 wfGetLBFactory()->waitForReplication( [ 'wiki' => $dbw->getWikiID() ] );
765 $this->uncacheLinkTarget( $target );
770 $this->reuseConnection( $dbw );
772 return $watchers;
776 * Reset the notification timestamp of this entry
778 * @param User $user
779 * @param Title $title
780 * @param string $force Whether to force the write query to be executed even if the
781 * page is not watched or the notification timestamp is already NULL.
782 * 'force' in order to force
783 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
785 * @return bool success
787 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
788 // Only loggedin user can have a watchlist
789 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
790 return false;
793 $item = null;
794 if ( $force != 'force' ) {
795 $item = $this->loadWatchedItem( $user, $title );
796 if ( !$item || $item->getNotificationTimestamp() === null ) {
797 return false;
801 // If the page is watched by the user (or may be watched), update the timestamp
802 $job = new ActivityUpdateJob(
803 $title,
805 'type' => 'updateWatchlistNotification',
806 'userid' => $user->getId(),
807 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
808 'curTime' => time()
812 // Try to run this post-send
813 // Calls DeferredUpdates::addCallableUpdate in normal operation
814 call_user_func(
815 $this->deferredUpdatesAddCallableUpdateCallback,
816 function() use ( $job ) {
817 $job->run();
821 $this->uncache( $user, $title );
823 return true;
826 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
827 if ( !$oldid ) {
828 // No oldid given, assuming latest revision; clear the timestamp.
829 return null;
832 if ( !$title->getNextRevisionID( $oldid ) ) {
833 // Oldid given and is the latest revision for this title; clear the timestamp.
834 return null;
837 if ( $item === null ) {
838 $item = $this->loadWatchedItem( $user, $title );
841 if ( !$item ) {
842 // This can only happen if $force is enabled.
843 return null;
846 // Oldid given and isn't the latest; update the timestamp.
847 // This will result in no further notification emails being sent!
848 // Calls Revision::getTimestampFromId in normal operation
849 $notificationTimestamp = call_user_func(
850 $this->revisionGetTimestampFromIdCallback,
851 $title,
852 $oldid
855 // We need to go one second to the future because of various strict comparisons
856 // throughout the codebase
857 $ts = new MWTimestamp( $notificationTimestamp );
858 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
859 $notificationTimestamp = $ts->getTimestamp( TS_MW );
861 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
862 if ( $force != 'force' ) {
863 return false;
864 } else {
865 // This is a little silly…
866 return $item->getNotificationTimestamp();
870 return $notificationTimestamp;
874 * @param User $user
875 * @param int $unreadLimit
877 * @return int|bool The number of unread notifications
878 * true if greater than or equal to $unreadLimit
880 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
881 $queryOptions = [];
882 if ( $unreadLimit !== null ) {
883 $unreadLimit = (int)$unreadLimit;
884 $queryOptions['LIMIT'] = $unreadLimit;
887 $dbr = $this->getConnection( DB_SLAVE );
888 $rowCount = $dbr->selectRowCount(
889 'watchlist',
890 '1',
892 'wl_user' => $user->getId(),
893 'wl_notificationtimestamp IS NOT NULL',
895 __METHOD__,
896 $queryOptions
898 $this->reuseConnection( $dbr );
900 if ( !isset( $unreadLimit ) ) {
901 return $rowCount;
904 if ( $rowCount >= $unreadLimit ) {
905 return true;
908 return $rowCount;
912 * Check if the given title already is watched by the user, and if so
913 * add a watch for the new title.
915 * To be used for page renames and such.
917 * @param LinkTarget $oldTarget
918 * @param LinkTarget $newTarget
920 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
921 $oldTarget = Title::newFromLinkTarget( $oldTarget );
922 $newTarget = Title::newFromLinkTarget( $newTarget );
924 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
925 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
929 * Check if the given title already is watched by the user, and if so
930 * add a watch for the new title.
932 * To be used for page renames and such.
933 * This must be called separately for Subject and Talk pages
935 * @param LinkTarget $oldTarget
936 * @param LinkTarget $newTarget
938 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
939 $dbw = $this->getConnection( DB_MASTER );
941 $result = $dbw->select(
942 'watchlist',
943 [ 'wl_user', 'wl_notificationtimestamp' ],
945 'wl_namespace' => $oldTarget->getNamespace(),
946 'wl_title' => $oldTarget->getDBkey(),
948 __METHOD__,
949 [ 'FOR UPDATE' ]
952 $newNamespace = $newTarget->getNamespace();
953 $newDBkey = $newTarget->getDBkey();
955 # Construct array to replace into the watchlist
956 $values = [];
957 foreach ( $result as $row ) {
958 $values[] = [
959 'wl_user' => $row->wl_user,
960 'wl_namespace' => $newNamespace,
961 'wl_title' => $newDBkey,
962 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
966 if ( !empty( $values ) ) {
967 # Perform replace
968 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
969 # some other DBMSes, mostly due to poor simulation by us
970 $dbw->replace(
971 'watchlist',
972 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
973 $values,
974 __METHOD__
978 $this->reuseConnection( $dbw );