3 use Wikimedia\Assert\Assert
;
6 * Storage layer class for WatchedItems.
7 * Database interaction.
13 class WatchedItemStore
{
18 private $loadBalancer;
26 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
27 * The index is needed so that on mass changes all relevant items can be un-cached.
28 * For example: Clearing a users watchlist of all items or updating notification timestamps
29 * for all users watching a single target.
31 private $cacheIndex = [];
36 private $deferredUpdatesAddCallableUpdateCallback;
41 private $revisionGetTimestampFromIdCallback;
46 private static $instance;
49 * @param LoadBalancer $loadBalancer
50 * @param HashBagOStuff $cache
52 public function __construct(
53 LoadBalancer
$loadBalancer,
56 $this->loadBalancer
= $loadBalancer;
57 $this->cache
= $cache;
58 $this->deferredUpdatesAddCallableUpdateCallback
= [ 'DeferredUpdates', 'addCallableUpdate' ];
59 $this->revisionGetTimestampFromIdCallback
= [ 'Revision', 'getTimestampFromId' ];
63 * Overrides the DeferredUpdates::addCallableUpdate callback
64 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
66 * @param callable $callback
68 * @see DeferredUpdates::addCallableUpdate for callback signiture
70 * @return ScopedCallback to reset the overridden value
73 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
74 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
75 throw new MWException(
76 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
79 Assert
::parameterType( 'callable', $callback, '$callback' );
81 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback
;
82 $this->deferredUpdatesAddCallableUpdateCallback
= $callback;
83 return new ScopedCallback( function() use ( $previousValue ) {
84 $this->deferredUpdatesAddCallableUpdateCallback
= $previousValue;
89 * Overrides the Revision::getTimestampFromId callback
90 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
92 * @param callable $callback
93 * @see Revision::getTimestampFromId for callback signiture
95 * @return ScopedCallback to reset the overridden value
98 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
99 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
100 throw new MWException(
101 'Cannot override Revision::getTimestampFromId callback in operation.'
104 Assert
::parameterType( 'callable', $callback, '$callback' );
106 $previousValue = $this->revisionGetTimestampFromIdCallback
;
107 $this->revisionGetTimestampFromIdCallback
= $callback;
108 return new ScopedCallback( function() use ( $previousValue ) {
109 $this->revisionGetTimestampFromIdCallback
= $previousValue;
114 * Overrides the default instance of this class
115 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
117 * If this method is used it MUST also be called with null after a test to ensure a new
118 * default instance is created next time getDefaultInstance is called.
120 * @param WatchedItemStore|null $store
122 * @return ScopedCallback to reset the overridden value
123 * @throws MWException
125 public static function overrideDefaultInstance( WatchedItemStore
$store = null ) {
126 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
127 throw new MWException(
128 'Cannot override ' . __CLASS__
. 'default instance in operation.'
132 $previousValue = self
::$instance;
133 self
::$instance = $store;
134 return new ScopedCallback( function() use ( $previousValue ) {
135 self
::$instance = $previousValue;
142 public static function getDefaultInstance() {
143 if ( !self
::$instance ) {
144 self
::$instance = new self(
146 new HashBagOStuff( [ 'maxKeys' => 100 ] )
149 return self
::$instance;
152 private function getCacheKey( User
$user, LinkTarget
$target ) {
153 return $this->cache
->makeKey(
154 (string)$target->getNamespace(),
156 (string)$user->getId()
160 private function cache( WatchedItem
$item ) {
161 $user = $item->getUser();
162 $target = $item->getLinkTarget();
163 $key = $this->getCacheKey( $user, $target );
164 $this->cache
->set( $key, $item );
165 $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
168 private function uncache( User
$user, LinkTarget
$target ) {
169 $this->cache
->delete( $this->getCacheKey( $user, $target ) );
170 unset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
173 private function uncacheLinkTarget( LinkTarget
$target ) {
174 if ( !isset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] ) ) {
177 foreach ( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] as $key ) {
178 $this->cache
->delete( $key );
184 * @param LinkTarget $target
186 * @return WatchedItem|null
188 private function getCached( User
$user, LinkTarget
$target ) {
189 return $this->cache
->get( $this->getCacheKey( $user, $target ) );
193 * Return an array of conditions to select or update the appropriate database
197 * @param LinkTarget $target
201 private function dbCond( User
$user, LinkTarget
$target ) {
203 'wl_user' => $user->getId(),
204 'wl_namespace' => $target->getNamespace(),
205 'wl_title' => $target->getDBkey(),
210 * @param int $slaveOrMaster DB_MASTER or DB_SLAVE
212 * @return DatabaseBase
213 * @throws MWException
215 private function getConnection( $slaveOrMaster ) {
216 return $this->loadBalancer
->getConnection( $slaveOrMaster, [ 'watchlist' ] );
220 * @param DatabaseBase $connection
222 * @throws MWException
224 private function reuseConnection( $connection ) {
225 $this->loadBalancer
->reuseConnection( $connection );
229 * @param LinkTarget $target
233 public function countWatchers( LinkTarget
$target ) {
234 $dbr = $this->getConnection( DB_SLAVE
);
235 $return = (int)$dbr->selectField(
239 'wl_namespace' => $target->getNamespace(),
240 'wl_title' => $target->getDBkey(),
244 $this->reuseConnection( $dbr );
250 * Number of page watchers who also visited a "recent" edit
252 * @param LinkTarget $target
253 * @param mixed $threshold timestamp accepted by wfTimestamp
256 * @throws DBUnexpectedError
257 * @throws MWException
259 public function countVisitingWatchers( LinkTarget
$target, $threshold ) {
260 $dbr = $this->getConnection( DB_SLAVE
);
261 $visitingWatchers = (int)$dbr->selectField(
265 'wl_namespace' => $target->getNamespace(),
266 'wl_title' => $target->getDBkey(),
267 'wl_notificationtimestamp >= ' .
268 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
269 ' OR wl_notificationtimestamp IS NULL'
273 $this->reuseConnection( $dbr );
275 return $visitingWatchers;
279 * @param LinkTarget[] $targets
280 * @param array $options Allowed keys:
281 * 'minimumWatchers' => int
283 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
284 * All targets will be present in the result. 0 either means no watchers or the number
285 * of watchers was below the minimumWatchers option if passed.
287 public function countWatchersMultiple( array $targets, array $options = [] ) {
288 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
290 $dbr = $this->getConnection( DB_SLAVE
);
292 if ( array_key_exists( 'minimumWatchers', $options ) ) {
293 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
296 $lb = new LinkBatch( $targets );
299 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
300 [ $lb->constructSet( 'wl', $dbr ) ],
305 $this->reuseConnection( $dbr );
308 foreach ( $targets as $linkTarget ) {
309 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
312 foreach ( $res as $row ) {
313 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
320 * Get an item (may be cached)
323 * @param LinkTarget $target
325 * @return WatchedItem|false
327 public function getWatchedItem( User
$user, LinkTarget
$target ) {
328 if ( $user->isAnon() ) {
332 $cached = $this->getCached( $user, $target );
336 return $this->loadWatchedItem( $user, $target );
340 * Loads an item from the db
343 * @param LinkTarget $target
345 * @return WatchedItem|false
347 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
348 // Only loggedin user can have a watchlist
349 if ( $user->isAnon() ) {
353 $dbr = $this->getConnection( DB_SLAVE
);
354 $row = $dbr->selectRow(
356 'wl_notificationtimestamp',
357 $this->dbCond( $user, $target ),
360 $this->reuseConnection( $dbr );
366 $item = new WatchedItem(
369 $row->wl_notificationtimestamp
371 $this->cache( $item );
377 * Must be called separately for Subject & Talk namespaces
380 * @param LinkTarget $target
384 public function isWatched( User
$user, LinkTarget
$target ) {
385 return (bool)$this->getWatchedItem( $user, $target );
389 * Must be called separately for Subject & Talk namespaces
392 * @param LinkTarget $target
394 public function addWatch( User
$user, LinkTarget
$target ) {
395 $this->addWatchBatch( [ [ $user, $target ] ] );
399 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
401 * @return bool success
403 public function addWatchBatch( array $userTargetCombinations ) {
404 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
409 foreach ( $userTargetCombinations as list( $user, $target ) ) {
412 * @var LinkTarget $target
415 // Only loggedin user can have a watchlist
416 if ( $user->isAnon() ) {
420 'wl_user' => $user->getId(),
421 'wl_namespace' => $target->getNamespace(),
422 'wl_title' => $target->getDBkey(),
423 'wl_notificationtimestamp' => null,
425 $this->uncache( $user, $target );
432 $dbw = $this->getConnection( DB_MASTER
);
433 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
434 // Use INSERT IGNORE to avoid overwriting the notification timestamp
435 // if there's already an entry for this page
436 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
438 $this->reuseConnection( $dbw );
444 * Removes the an entry for the User watching the LinkTarget
445 * Must be called separately for Subject & Talk namespaces
448 * @param LinkTarget $target
450 * @return bool success
451 * @throws DBUnexpectedError
452 * @throws MWException
454 public function removeWatch( User
$user, LinkTarget
$target ) {
455 // Only logged in user can have a watchlist
456 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
460 $this->uncache( $user, $target );
462 $dbw = $this->getConnection( DB_MASTER
);
463 $dbw->delete( 'watchlist',
465 'wl_user' => $user->getId(),
466 'wl_namespace' => $target->getNamespace(),
467 'wl_title' => $target->getDBkey(),
470 $success = (bool)$dbw->affectedRows();
471 $this->reuseConnection( $dbw );
477 * @param User $editor The editor that triggered the update. Their notification
478 * timestamp will not be updated(they have already seen it)
479 * @param LinkTarget $target The target to update timestamps for
480 * @param string $timestamp Set the update timestamp to this value
482 * @return int[] Array of user IDs the timestamp has been updated for
484 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
485 $dbw = $this->getConnection( DB_MASTER
);
486 $res = $dbw->select( [ 'watchlist' ],
489 'wl_user != ' . intval( $editor->getId() ),
490 'wl_namespace' => $target->getNamespace(),
491 'wl_title' => $target->getDBkey(),
492 'wl_notificationtimestamp IS NULL',
497 foreach ( $res as $row ) {
498 $watchers[] = intval( $row->wl_user
);
502 // Update wl_notificationtimestamp for all watching users except the editor
504 $dbw->onTransactionIdle(
505 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
506 $dbw->update( 'watchlist',
508 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
510 'wl_user' => $watchers,
511 'wl_namespace' => $target->getNamespace(),
512 'wl_title' => $target->getDBkey(),
515 $this->uncacheLinkTarget( $target );
520 $this->reuseConnection( $dbw );
526 * Reset the notification timestamp of this entry
529 * @param Title $title
530 * @param string $force Whether to force the write query to be executed even if the
531 * page is not watched or the notification timestamp is already NULL.
532 * 'force' in order to force
533 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
535 * @return bool success
537 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
538 // Only loggedin user can have a watchlist
539 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
544 if ( $force != 'force' ) {
545 $item = $this->loadWatchedItem( $user, $title );
546 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
551 // If the page is watched by the user (or may be watched), update the timestamp
552 $job = new ActivityUpdateJob(
555 'type' => 'updateWatchlistNotification',
556 'userid' => $user->getId(),
557 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
562 // Try to run this post-send
563 // Calls DeferredUpdates::addCallableUpdate in normal operation
565 $this->deferredUpdatesAddCallableUpdateCallback
,
566 function() use ( $job ) {
571 $this->uncache( $user, $title );
576 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
578 // No oldid given, assuming latest revision; clear the timestamp.
582 if ( !$title->getNextRevisionID( $oldid ) ) {
583 // Oldid given and is the latest revision for this title; clear the timestamp.
587 if ( $item === null ) {
588 $item = $this->loadWatchedItem( $user, $title );
592 // This can only happen if $force is enabled.
596 // Oldid given and isn't the latest; update the timestamp.
597 // This will result in no further notification emails being sent!
598 // Calls Revision::getTimestampFromId in normal operation
599 $notificationTimestamp = call_user_func(
600 $this->revisionGetTimestampFromIdCallback
,
605 // We need to go one second to the future because of various strict comparisons
606 // throughout the codebase
607 $ts = new MWTimestamp( $notificationTimestamp );
608 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
609 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
611 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
612 if ( $force != 'force' ) {
615 // This is a little silly…
616 return $item->getNotificationTimestamp();
620 return $notificationTimestamp;
625 * @param int $unreadLimit
627 * @return int|bool The number of unread notifications
628 * true if greater than or equal to $unreadLimit
630 public function countUnreadNotifications( User
$user, $unreadLimit = null ) {
632 if ( $unreadLimit !== null ) {
633 $unreadLimit = (int)$unreadLimit;
634 $queryOptions['LIMIT'] = $unreadLimit;
637 $dbr = $this->getConnection( DB_SLAVE
);
638 $rowCount = $dbr->selectRowCount(
642 'wl_user' => $user->getId(),
643 'wl_notificationtimestamp IS NOT NULL',
648 $this->reuseConnection( $dbr );
650 if ( !isset( $unreadLimit ) ) {
654 if ( $rowCount >= $unreadLimit ) {
662 * Check if the given title already is watched by the user, and if so
663 * add a watch for the new title.
665 * To be used for page renames and such.
667 * @param LinkTarget $oldTarget
668 * @param LinkTarget $newTarget
670 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
671 if ( !$oldTarget instanceof Title
) {
672 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
674 if ( !$newTarget instanceof Title
) {
675 $newTarget = Title
::newFromLinkTarget( $newTarget );
678 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
679 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
683 * Check if the given title already is watched by the user, and if so
684 * add a watch for the new title.
686 * To be used for page renames and such.
687 * This must be called separately for Subject and Talk pages
689 * @param LinkTarget $oldTarget
690 * @param LinkTarget $newTarget
692 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
693 $dbw = $this->getConnection( DB_MASTER
);
695 $result = $dbw->select(
697 [ 'wl_user', 'wl_notificationtimestamp' ],
699 'wl_namespace' => $oldTarget->getNamespace(),
700 'wl_title' => $oldTarget->getDBkey(),
706 $newNamespace = $newTarget->getNamespace();
707 $newDBkey = $newTarget->getDBkey();
709 # Construct array to replace into the watchlist
711 foreach ( $result as $row ) {
713 'wl_user' => $row->wl_user
,
714 'wl_namespace' => $newNamespace,
715 'wl_title' => $newDBkey,
716 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
720 if ( !empty( $values ) ) {
722 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
723 # some other DBMSes, mostly due to poor simulation by us
726 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
732 $this->reuseConnection( $dbw );