Add sslCAFile option to DatabaseMysqli
[mediawiki.git] / includes / WatchedItemStore.php
blob69a9df2d579b5e1771265edf52f09f350d7c8a53
1 <?php
3 use Wikimedia\Rdbms\IDatabase;
4 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
5 use MediaWiki\Linker\LinkTarget;
6 use MediaWiki\MediaWikiServices;
7 use Wikimedia\Assert\Assert;
8 use Wikimedia\ScopedCallback;
9 use Wikimedia\Rdbms\LoadBalancer;
10 use Wikimedia\Rdbms\DBUnexpectedError;
12 /**
13 * Storage layer class for WatchedItems.
14 * Database interaction.
16 * Uses database because this uses User::isAnon
18 * @group Database
20 * @author Addshore
21 * @since 1.27
23 class WatchedItemStore implements StatsdAwareInterface {
25 const SORT_DESC = 'DESC';
26 const SORT_ASC = 'ASC';
28 /**
29 * @var LoadBalancer
31 private $loadBalancer;
33 /**
34 * @var ReadOnlyMode
36 private $readOnlyMode;
38 /**
39 * @var HashBagOStuff
41 private $cache;
43 /**
44 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
45 * The index is needed so that on mass changes all relevant items can be un-cached.
46 * For example: Clearing a users watchlist of all items or updating notification timestamps
47 * for all users watching a single target.
49 private $cacheIndex = [];
51 /**
52 * @var callable|null
54 private $deferredUpdatesAddCallableUpdateCallback;
56 /**
57 * @var callable|null
59 private $revisionGetTimestampFromIdCallback;
61 /**
62 * @var StatsdDataFactoryInterface
64 private $stats;
66 /**
67 * @param LoadBalancer $loadBalancer
68 * @param HashBagOStuff $cache
69 * @param ReadOnlyMode $readOnlyMode
71 public function __construct(
72 LoadBalancer $loadBalancer,
73 HashBagOStuff $cache,
74 ReadOnlyMode $readOnlyMode
75 ) {
76 $this->loadBalancer = $loadBalancer;
77 $this->cache = $cache;
78 $this->readOnlyMode = $readOnlyMode;
79 $this->stats = new NullStatsdDataFactory();
80 $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
81 $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
84 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
85 $this->stats = $stats;
88 /**
89 * Overrides the DeferredUpdates::addCallableUpdate callback
90 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
92 * @param callable $callback
94 * @see DeferredUpdates::addCallableUpdate for callback signiture
96 * @return ScopedCallback to reset the overridden value
97 * @throws MWException
99 public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
100 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
101 throw new MWException(
102 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
105 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback;
106 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
107 return new ScopedCallback( function () use ( $previousValue ) {
108 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
109 } );
113 * Overrides the Revision::getTimestampFromId callback
114 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
116 * @param callable $callback
117 * @see Revision::getTimestampFromId for callback signiture
119 * @return ScopedCallback to reset the overridden value
120 * @throws MWException
122 public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
123 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
124 throw new MWException(
125 'Cannot override Revision::getTimestampFromId callback in operation.'
128 $previousValue = $this->revisionGetTimestampFromIdCallback;
129 $this->revisionGetTimestampFromIdCallback = $callback;
130 return new ScopedCallback( function () use ( $previousValue ) {
131 $this->revisionGetTimestampFromIdCallback = $previousValue;
132 } );
135 private function getCacheKey( User $user, LinkTarget $target ) {
136 return $this->cache->makeKey(
137 (string)$target->getNamespace(),
138 $target->getDBkey(),
139 (string)$user->getId()
143 private function cache( WatchedItem $item ) {
144 $user = $item->getUser();
145 $target = $item->getLinkTarget();
146 $key = $this->getCacheKey( $user, $target );
147 $this->cache->set( $key, $item );
148 $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
149 $this->stats->increment( 'WatchedItemStore.cache' );
152 private function uncache( User $user, LinkTarget $target ) {
153 $this->cache->delete( $this->getCacheKey( $user, $target ) );
154 unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
155 $this->stats->increment( 'WatchedItemStore.uncache' );
158 private function uncacheLinkTarget( LinkTarget $target ) {
159 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
160 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
161 return;
163 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
164 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
165 $this->cache->delete( $key );
169 private function uncacheUser( User $user ) {
170 $this->stats->increment( 'WatchedItemStore.uncacheUser' );
171 foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
172 foreach ( $dbKeyArray as $dbKey => $userArray ) {
173 if ( isset( $userArray[$user->getId()] ) ) {
174 $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
175 $this->cache->delete( $userArray[$user->getId()] );
182 * @param User $user
183 * @param LinkTarget $target
185 * @return WatchedItem|false
187 private function getCached( User $user, LinkTarget $target ) {
188 return $this->cache->get( $this->getCacheKey( $user, $target ) );
192 * Return an array of conditions to select or update the appropriate database
193 * row.
195 * @param User $user
196 * @param LinkTarget $target
198 * @return array
200 private function dbCond( User $user, LinkTarget $target ) {
201 return [
202 'wl_user' => $user->getId(),
203 'wl_namespace' => $target->getNamespace(),
204 'wl_title' => $target->getDBkey(),
209 * @param int $dbIndex DB_MASTER or DB_REPLICA
211 * @return IDatabase
212 * @throws MWException
214 private function getConnectionRef( $dbIndex ) {
215 return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
219 * Count the number of individual items that are watched by the user.
220 * If a subject and corresponding talk page are watched this will return 2.
222 * @param User $user
224 * @return int
226 public function countWatchedItems( User $user ) {
227 $dbr = $this->getConnectionRef( DB_REPLICA );
228 $return = (int)$dbr->selectField(
229 'watchlist',
230 'COUNT(*)',
232 'wl_user' => $user->getId()
234 __METHOD__
237 return $return;
241 * @param LinkTarget $target
243 * @return int
245 public function countWatchers( LinkTarget $target ) {
246 $dbr = $this->getConnectionRef( DB_REPLICA );
247 $return = (int)$dbr->selectField(
248 'watchlist',
249 'COUNT(*)',
251 'wl_namespace' => $target->getNamespace(),
252 'wl_title' => $target->getDBkey(),
254 __METHOD__
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->getConnectionRef( DB_REPLICA );
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__
285 return $visitingWatchers;
289 * @param LinkTarget[] $targets
290 * @param array $options Allowed keys:
291 * 'minimumWatchers' => int
293 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
294 * All targets will be present in the result. 0 either means no watchers or the number
295 * of watchers was below the minimumWatchers option if passed.
297 public function countWatchersMultiple( array $targets, array $options = [] ) {
298 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
300 $dbr = $this->getConnectionRef( DB_REPLICA );
302 if ( array_key_exists( 'minimumWatchers', $options ) ) {
303 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
306 $lb = new LinkBatch( $targets );
307 $res = $dbr->select(
308 'watchlist',
309 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
310 [ $lb->constructSet( 'wl', $dbr ) ],
311 __METHOD__,
312 $dbOptions
315 $watchCounts = [];
316 foreach ( $targets as $linkTarget ) {
317 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
320 foreach ( $res as $row ) {
321 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
324 return $watchCounts;
328 * Number of watchers of each page who have visited recent edits to that page
330 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget $target, mixed $threshold),
331 * $threshold is:
332 * - a timestamp of the recent edit if $target exists (format accepted by wfTimestamp)
333 * - null if $target doesn't exist
334 * @param int|null $minimumWatchers
335 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $watchers,
336 * where $watchers is an int:
337 * - if the page exists, number of users watching who have visited the page recently
338 * - if the page doesn't exist, number of users that have the page on their watchlist
339 * - 0 means there are no visiting watchers or their number is below the minimumWatchers
340 * option (if passed).
342 public function countVisitingWatchersMultiple(
343 array $targetsWithVisitThresholds,
344 $minimumWatchers = null
346 $dbr = $this->getConnectionRef( DB_REPLICA );
348 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
350 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
351 if ( $minimumWatchers !== null ) {
352 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
354 $res = $dbr->select(
355 'watchlist',
356 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
357 $conds,
358 __METHOD__,
359 $dbOptions
362 $watcherCounts = [];
363 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
364 /* @var LinkTarget $target */
365 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
368 foreach ( $res as $row ) {
369 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
372 return $watcherCounts;
376 * Generates condition for the query used in a batch count visiting watchers.
378 * @param IDatabase $db
379 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
380 * @return string
382 private function getVisitingWatchersCondition(
383 IDatabase $db,
384 array $targetsWithVisitThresholds
386 $missingTargets = [];
387 $namespaceConds = [];
388 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
389 if ( $threshold === null ) {
390 $missingTargets[] = $target;
391 continue;
393 /* @var LinkTarget $target */
394 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
395 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
396 $db->makeList( [
397 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
398 'wl_notificationtimestamp IS NULL'
399 ], LIST_OR )
400 ], LIST_AND );
403 $conds = [];
404 foreach ( $namespaceConds as $namespace => $pageConds ) {
405 $conds[] = $db->makeList( [
406 'wl_namespace = ' . $namespace,
407 '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
408 ], LIST_AND );
411 if ( $missingTargets ) {
412 $lb = new LinkBatch( $missingTargets );
413 $conds[] = $lb->constructSet( 'wl', $db );
416 return $db->makeList( $conds, LIST_OR );
420 * Get an item (may be cached)
422 * @param User $user
423 * @param LinkTarget $target
425 * @return WatchedItem|false
427 public function getWatchedItem( User $user, LinkTarget $target ) {
428 if ( $user->isAnon() ) {
429 return false;
432 $cached = $this->getCached( $user, $target );
433 if ( $cached ) {
434 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
435 return $cached;
437 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
438 return $this->loadWatchedItem( $user, $target );
442 * Loads an item from the db
444 * @param User $user
445 * @param LinkTarget $target
447 * @return WatchedItem|false
449 public function loadWatchedItem( User $user, LinkTarget $target ) {
450 // Only loggedin user can have a watchlist
451 if ( $user->isAnon() ) {
452 return false;
455 $dbr = $this->getConnectionRef( DB_REPLICA );
456 $row = $dbr->selectRow(
457 'watchlist',
458 'wl_notificationtimestamp',
459 $this->dbCond( $user, $target ),
460 __METHOD__
463 if ( !$row ) {
464 return false;
467 $item = new WatchedItem(
468 $user,
469 $target,
470 wfTimestampOrNull( TS_MW, $row->wl_notificationtimestamp )
472 $this->cache( $item );
474 return $item;
478 * @param User $user
479 * @param array $options Allowed keys:
480 * 'forWrite' => bool defaults to false
481 * 'sort' => string optional sorting by namespace ID and title
482 * one of the self::SORT_* constants
484 * @return WatchedItem[]
486 public function getWatchedItemsForUser( User $user, array $options = [] ) {
487 $options += [ 'forWrite' => false ];
489 $dbOptions = [];
490 if ( array_key_exists( 'sort', $options ) ) {
491 Assert::parameter(
492 ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
493 '$options[\'sort\']',
494 'must be SORT_ASC or SORT_DESC'
496 $dbOptions['ORDER BY'] = [
497 "wl_namespace {$options['sort']}",
498 "wl_title {$options['sort']}"
501 $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
503 $res = $db->select(
504 'watchlist',
505 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
506 [ 'wl_user' => $user->getId() ],
507 __METHOD__,
508 $dbOptions
511 $watchedItems = [];
512 foreach ( $res as $row ) {
513 // @todo: Should we add these to the process cache?
514 $watchedItems[] = new WatchedItem(
515 $user,
516 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
517 $row->wl_notificationtimestamp
521 return $watchedItems;
525 * Must be called separately for Subject & Talk namespaces
527 * @param User $user
528 * @param LinkTarget $target
530 * @return bool
532 public function isWatched( User $user, LinkTarget $target ) {
533 return (bool)$this->getWatchedItem( $user, $target );
537 * @param User $user
538 * @param LinkTarget[] $targets
540 * @return array multi-dimensional like $return[$namespaceId][$titleString] = $timestamp,
541 * where $timestamp is:
542 * - string|null value of wl_notificationtimestamp,
543 * - false if $target is not watched by $user.
545 public function getNotificationTimestampsBatch( User $user, array $targets ) {
546 $timestamps = [];
547 foreach ( $targets as $target ) {
548 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
551 if ( $user->isAnon() ) {
552 return $timestamps;
555 $targetsToLoad = [];
556 foreach ( $targets as $target ) {
557 $cachedItem = $this->getCached( $user, $target );
558 if ( $cachedItem ) {
559 $timestamps[$target->getNamespace()][$target->getDBkey()] =
560 $cachedItem->getNotificationTimestamp();
561 } else {
562 $targetsToLoad[] = $target;
566 if ( !$targetsToLoad ) {
567 return $timestamps;
570 $dbr = $this->getConnectionRef( DB_REPLICA );
572 $lb = new LinkBatch( $targetsToLoad );
573 $res = $dbr->select(
574 'watchlist',
575 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
577 $lb->constructSet( 'wl', $dbr ),
578 'wl_user' => $user->getId(),
580 __METHOD__
583 foreach ( $res as $row ) {
584 $timestamps[$row->wl_namespace][$row->wl_title] =
585 wfTimestampOrNull( TS_MW, $row->wl_notificationtimestamp );
588 return $timestamps;
592 * Must be called separately for Subject & Talk namespaces
594 * @param User $user
595 * @param LinkTarget $target
597 public function addWatch( User $user, LinkTarget $target ) {
598 $this->addWatchBatchForUser( $user, [ $target ] );
602 * @param User $user
603 * @param LinkTarget[] $targets
605 * @return bool success
607 public function addWatchBatchForUser( User $user, array $targets ) {
608 if ( $this->readOnlyMode->isReadOnly() ) {
609 return false;
611 // Only loggedin user can have a watchlist
612 if ( $user->isAnon() ) {
613 return false;
616 if ( !$targets ) {
617 return true;
620 $rows = [];
621 $items = [];
622 foreach ( $targets as $target ) {
623 $rows[] = [
624 'wl_user' => $user->getId(),
625 'wl_namespace' => $target->getNamespace(),
626 'wl_title' => $target->getDBkey(),
627 'wl_notificationtimestamp' => null,
629 $items[] = new WatchedItem(
630 $user,
631 $target,
632 null
634 $this->uncache( $user, $target );
637 $dbw = $this->getConnectionRef( DB_MASTER );
638 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
639 // Use INSERT IGNORE to avoid overwriting the notification timestamp
640 // if there's already an entry for this page
641 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
643 // Update process cache to ensure skin doesn't claim that the current
644 // page is unwatched in the response of action=watch itself (T28292).
645 // This would otherwise be re-queried from a slave by isWatched().
646 foreach ( $items as $item ) {
647 $this->cache( $item );
650 return true;
654 * Removes the an entry for the User watching the LinkTarget
655 * Must be called separately for Subject & Talk namespaces
657 * @param User $user
658 * @param LinkTarget $target
660 * @return bool success
661 * @throws DBUnexpectedError
662 * @throws MWException
664 public function removeWatch( User $user, LinkTarget $target ) {
665 // Only logged in user can have a watchlist
666 if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
667 return false;
670 $this->uncache( $user, $target );
672 $dbw = $this->getConnectionRef( DB_MASTER );
673 $dbw->delete( 'watchlist',
675 'wl_user' => $user->getId(),
676 'wl_namespace' => $target->getNamespace(),
677 'wl_title' => $target->getDBkey(),
678 ], __METHOD__
680 $success = (bool)$dbw->affectedRows();
682 return $success;
686 * @param User $user The user to set the timestamp for
687 * @param string|null $timestamp Set the update timestamp to this value
688 * @param LinkTarget[] $targets List of targets to update. Default to all targets
690 * @return bool success
692 public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
693 // Only loggedin user can have a watchlist
694 if ( $user->isAnon() ) {
695 return false;
698 $dbw = $this->getConnectionRef( DB_MASTER );
700 $conds = [ 'wl_user' => $user->getId() ];
701 if ( $targets ) {
702 $batch = new LinkBatch( $targets );
703 $conds[] = $batch->constructSet( 'wl', $dbw );
706 if ( $timestamp !== null ) {
707 $timestamp = $dbw->timestamp( $timestamp );
710 $success = $dbw->update(
711 'watchlist',
712 [ 'wl_notificationtimestamp' => $timestamp ],
713 $conds,
714 __METHOD__
717 $this->uncacheUser( $user );
719 return $success;
723 * @param User $editor The editor that triggered the update. Their notification
724 * timestamp will not be updated(they have already seen it)
725 * @param LinkTarget $target The target to update timestamps for
726 * @param string $timestamp Set the update timestamp to this value
728 * @return int[] Array of user IDs the timestamp has been updated for
730 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
731 $dbw = $this->getConnectionRef( DB_MASTER );
732 $uids = $dbw->selectFieldValues(
733 'watchlist',
734 'wl_user',
736 'wl_user != ' . intval( $editor->getId() ),
737 'wl_namespace' => $target->getNamespace(),
738 'wl_title' => $target->getDBkey(),
739 'wl_notificationtimestamp IS NULL',
741 __METHOD__
744 $watchers = array_map( 'intval', $uids );
745 if ( $watchers ) {
746 // Update wl_notificationtimestamp for all watching users except the editor
747 $fname = __METHOD__;
748 DeferredUpdates::addCallableUpdate(
749 function () use ( $timestamp, $watchers, $target, $fname ) {
750 global $wgUpdateRowsPerQuery;
752 $dbw = $this->getConnectionRef( DB_MASTER );
753 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
754 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
756 $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
757 foreach ( $watchersChunks as $watchersChunk ) {
758 $dbw->update( 'watchlist',
759 [ /* SET */
760 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
761 ], [ /* WHERE - TODO Use wl_id T130067 */
762 'wl_user' => $watchersChunk,
763 'wl_namespace' => $target->getNamespace(),
764 'wl_title' => $target->getDBkey(),
765 ], $fname
767 if ( count( $watchersChunks ) > 1 ) {
768 $factory->commitAndWaitForReplication(
769 __METHOD__, $ticket, [ 'wiki' => $dbw->getWikiID() ]
773 $this->uncacheLinkTarget( $target );
775 DeferredUpdates::POSTSEND,
776 $dbw
780 return $watchers;
784 * Reset the notification timestamp of this entry
786 * @param User $user
787 * @param Title $title
788 * @param string $force Whether to force the write query to be executed even if the
789 * page is not watched or the notification timestamp is already NULL.
790 * 'force' in order to force
791 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
793 * @return bool success
795 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
796 // Only loggedin user can have a watchlist
797 if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
798 return false;
801 $item = null;
802 if ( $force != 'force' ) {
803 $item = $this->loadWatchedItem( $user, $title );
804 if ( !$item || $item->getNotificationTimestamp() === null ) {
805 return false;
809 // If the page is watched by the user (or may be watched), update the timestamp
810 $job = new ActivityUpdateJob(
811 $title,
813 'type' => 'updateWatchlistNotification',
814 'userid' => $user->getId(),
815 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
816 'curTime' => time()
820 // Try to run this post-send
821 // Calls DeferredUpdates::addCallableUpdate in normal operation
822 call_user_func(
823 $this->deferredUpdatesAddCallableUpdateCallback,
824 function () use ( $job ) {
825 $job->run();
829 $this->uncache( $user, $title );
831 return true;
834 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
835 if ( !$oldid ) {
836 // No oldid given, assuming latest revision; clear the timestamp.
837 return null;
840 if ( !$title->getNextRevisionID( $oldid ) ) {
841 // Oldid given and is the latest revision for this title; clear the timestamp.
842 return null;
845 if ( $item === null ) {
846 $item = $this->loadWatchedItem( $user, $title );
849 if ( !$item ) {
850 // This can only happen if $force is enabled.
851 return null;
854 // Oldid given and isn't the latest; update the timestamp.
855 // This will result in no further notification emails being sent!
856 // Calls Revision::getTimestampFromId in normal operation
857 $notificationTimestamp = call_user_func(
858 $this->revisionGetTimestampFromIdCallback,
859 $title,
860 $oldid
863 // We need to go one second to the future because of various strict comparisons
864 // throughout the codebase
865 $ts = new MWTimestamp( $notificationTimestamp );
866 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
867 $notificationTimestamp = $ts->getTimestamp( TS_MW );
869 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
870 if ( $force != 'force' ) {
871 return false;
872 } else {
873 // This is a little silly…
874 return $item->getNotificationTimestamp();
878 return $notificationTimestamp;
882 * @param User $user
883 * @param int $unreadLimit
885 * @return int|bool The number of unread notifications
886 * true if greater than or equal to $unreadLimit
888 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
889 $queryOptions = [];
890 if ( $unreadLimit !== null ) {
891 $unreadLimit = (int)$unreadLimit;
892 $queryOptions['LIMIT'] = $unreadLimit;
895 $dbr = $this->getConnectionRef( DB_REPLICA );
896 $rowCount = $dbr->selectRowCount(
897 'watchlist',
898 '1',
900 'wl_user' => $user->getId(),
901 'wl_notificationtimestamp IS NOT NULL',
903 __METHOD__,
904 $queryOptions
907 if ( !isset( $unreadLimit ) ) {
908 return $rowCount;
911 if ( $rowCount >= $unreadLimit ) {
912 return true;
915 return $rowCount;
919 * Check if the given title already is watched by the user, and if so
920 * add a watch for the new title.
922 * To be used for page renames and such.
924 * @param LinkTarget $oldTarget
925 * @param LinkTarget $newTarget
927 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
928 $oldTarget = Title::newFromLinkTarget( $oldTarget );
929 $newTarget = Title::newFromLinkTarget( $newTarget );
931 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
932 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
936 * Check if the given title already is watched by the user, and if so
937 * add a watch for the new title.
939 * To be used for page renames and such.
940 * This must be called separately for Subject and Talk pages
942 * @param LinkTarget $oldTarget
943 * @param LinkTarget $newTarget
945 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
946 $dbw = $this->getConnectionRef( DB_MASTER );
948 $result = $dbw->select(
949 'watchlist',
950 [ 'wl_user', 'wl_notificationtimestamp' ],
952 'wl_namespace' => $oldTarget->getNamespace(),
953 'wl_title' => $oldTarget->getDBkey(),
955 __METHOD__,
956 [ 'FOR UPDATE' ]
959 $newNamespace = $newTarget->getNamespace();
960 $newDBkey = $newTarget->getDBkey();
962 # Construct array to replace into the watchlist
963 $values = [];
964 foreach ( $result as $row ) {
965 $values[] = [
966 'wl_user' => $row->wl_user,
967 'wl_namespace' => $newNamespace,
968 'wl_title' => $newDBkey,
969 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
973 if ( !empty( $values ) ) {
974 # Perform replace
975 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
976 # some other DBMSes, mostly due to poor simulation by us
977 $dbw->replace(
978 'watchlist',
979 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
980 $values,
981 __METHOD__