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
67 * @see DeferredUpdates::addCallableUpdate for callback signiture
71 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
72 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
73 throw new MWException(
74 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
77 Assert
::parameterType( 'callable', $callback, '$callback' );
78 $this->deferredUpdatesAddCallableUpdateCallback
= $callback;
82 * Overrides the Revision::getTimestampFromId callback
83 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
85 * @param callable $callback
86 * @see Revision::getTimestampFromId for callback signiture
90 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
91 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
92 throw new MWException(
93 'Cannot override Revision::getTimestampFromId callback in operation.'
96 Assert
::parameterType( 'callable', $callback, '$callback' );
97 $this->revisionGetTimestampFromIdCallback
= $callback;
101 * Overrides the default instance of this class
102 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
104 * @param WatchedItemStore $store
106 * @throws MWException
108 public static function overrideDefaultInstance( WatchedItemStore
$store ) {
109 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
110 throw new MWException(
111 'Cannot override ' . __CLASS__
. 'default instance in operation.'
114 self
::$instance = $store;
120 public static function getDefaultInstance() {
121 if ( !self
::$instance ) {
122 self
::$instance = new self(
124 new HashBagOStuff( [ 'maxKeys' => 100 ] )
127 return self
::$instance;
130 private function getCacheKey( User
$user, LinkTarget
$target ) {
131 return $this->cache
->makeKey(
132 (string)$target->getNamespace(),
134 (string)$user->getId()
138 private function cache( WatchedItem
$item ) {
139 $user = $item->getUser();
140 $target = $item->getLinkTarget();
141 $key = $this->getCacheKey( $user, $target );
142 $this->cache
->set( $key, $item );
143 $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
146 private function uncache( User
$user, LinkTarget
$target ) {
147 $this->cache
->delete( $this->getCacheKey( $user, $target ) );
148 unset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
151 private function uncacheLinkTarget( LinkTarget
$target ) {
152 if ( !isset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] ) ) {
155 foreach ( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] as $key ) {
156 $this->cache
->delete( $key );
162 * @param LinkTarget $target
164 * @return WatchedItem|null
166 private function getCached( User
$user, LinkTarget
$target ) {
167 return $this->cache
->get( $this->getCacheKey( $user, $target ) );
171 * Return an array of conditions to select or update the appropriate database
175 * @param LinkTarget $target
179 private function dbCond( User
$user, LinkTarget
$target ) {
181 'wl_user' => $user->getId(),
182 'wl_namespace' => $target->getNamespace(),
183 'wl_title' => $target->getDBkey(),
188 * @param LinkTarget $target
192 public function countWatchers( LinkTarget
$target ) {
193 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
194 $return = (int)$dbr->selectField(
198 'wl_namespace' => $target->getNamespace(),
199 'wl_title' => $target->getDBkey(),
203 $this->loadBalancer
->reuseConnection( $dbr );
209 * Number of page watchers who also visited a "recent" edit
211 * @param LinkTarget $target
212 * @param mixed $threshold timestamp accepted by wfTimestamp
215 * @throws DBUnexpectedError
216 * @throws MWException
218 public function countVisitingWatchers( LinkTarget
$target, $threshold ) {
219 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
220 $visitingWatchers = (int)$dbr->selectField(
224 'wl_namespace' => $target->getNamespace(),
225 'wl_title' => $target->getDBkey(),
226 'wl_notificationtimestamp >= ' .
227 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
228 ' OR wl_notificationtimestamp IS NULL'
232 $this->loadBalancer
->reuseConnection( $dbr );
234 return $visitingWatchers;
238 * @param LinkTarget[] $targets
239 * @param array $options Allowed keys:
240 * 'minimumWatchers' => int
242 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
243 * All targets will be present in the result. 0 either means no watchers or the number
244 * of watchers was below the minimumWatchers option if passed.
246 public function countWatchersMultiple( array $targets, array $options = [] ) {
247 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
249 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
251 if ( array_key_exists( 'minimumWatchers', $options ) ) {
252 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
255 $lb = new LinkBatch( $targets );
258 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
259 [ $lb->constructSet( 'wl', $dbr ) ],
264 $this->loadBalancer
->reuseConnection( $dbr );
267 foreach ( $targets as $linkTarget ) {
268 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
271 foreach ( $res as $row ) {
272 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
279 * Get an item (may be cached)
282 * @param LinkTarget $target
284 * @return WatchedItem|false
286 public function getWatchedItem( User
$user, LinkTarget
$target ) {
287 if ( $user->isAnon() ) {
291 $cached = $this->getCached( $user, $target );
295 return $this->loadWatchedItem( $user, $target );
299 * Loads an item from the db
302 * @param LinkTarget $target
304 * @return WatchedItem|false
306 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
307 // Only loggedin user can have a watchlist
308 if ( $user->isAnon() ) {
312 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
313 $row = $dbr->selectRow(
315 'wl_notificationtimestamp',
316 $this->dbCond( $user, $target ),
319 $this->loadBalancer
->reuseConnection( $dbr );
325 $item = new WatchedItem(
328 $row->wl_notificationtimestamp
330 $this->cache( $item );
336 * Must be called separately for Subject & Talk namespaces
339 * @param LinkTarget $target
343 public function isWatched( User
$user, LinkTarget
$target ) {
344 return (bool)$this->getWatchedItem( $user, $target );
348 * Must be called separately for Subject & Talk namespaces
351 * @param LinkTarget $target
353 public function addWatch( User
$user, LinkTarget
$target ) {
354 $this->addWatchBatch( [ [ $user, $target ] ] );
358 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
360 * @return bool success
362 public function addWatchBatch( array $userTargetCombinations ) {
363 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
368 foreach ( $userTargetCombinations as list( $user, $target ) ) {
371 * @var LinkTarget $target
374 // Only loggedin user can have a watchlist
375 if ( $user->isAnon() ) {
379 'wl_user' => $user->getId(),
380 'wl_namespace' => $target->getNamespace(),
381 'wl_title' => $target->getDBkey(),
382 'wl_notificationtimestamp' => null,
384 $this->uncache( $user, $target );
391 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
392 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
393 // Use INSERT IGNORE to avoid overwriting the notification timestamp
394 // if there's already an entry for this page
395 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
397 $this->loadBalancer
->reuseConnection( $dbw );
403 * Removes the an entry for the User watching the LinkTarget
404 * Must be called separately for Subject & Talk namespaces
407 * @param LinkTarget $target
409 * @return bool success
410 * @throws DBUnexpectedError
411 * @throws MWException
413 public function removeWatch( User
$user, LinkTarget
$target ) {
414 // Only logged in user can have a watchlist
415 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
419 $this->uncache( $user, $target );
421 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
422 $dbw->delete( 'watchlist',
424 'wl_user' => $user->getId(),
425 'wl_namespace' => $target->getNamespace(),
426 'wl_title' => $target->getDBkey(),
429 $success = (bool)$dbw->affectedRows();
430 $this->loadBalancer
->reuseConnection( $dbw );
436 * @param User $editor The editor that triggered the update. Their notification
437 * timestamp will not be updated(they have already seen it)
438 * @param LinkTarget $target The target to update timestamps for
439 * @param string $timestamp Set the update timestamp to this value
441 * @return int[] Array of user IDs the timestamp has been updated for
443 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
444 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
445 $res = $dbw->select( [ 'watchlist' ],
448 'wl_user != ' . intval( $editor->getId() ),
449 'wl_namespace' => $target->getNamespace(),
450 'wl_title' => $target->getDBkey(),
451 'wl_notificationtimestamp IS NULL',
456 foreach ( $res as $row ) {
457 $watchers[] = intval( $row->wl_user
);
461 // Update wl_notificationtimestamp for all watching users except the editor
463 $dbw->onTransactionIdle(
464 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
465 $dbw->update( 'watchlist',
467 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
469 'wl_user' => $watchers,
470 'wl_namespace' => $target->getNamespace(),
471 'wl_title' => $target->getDBkey(),
474 $this->uncacheLinkTarget( $target );
479 $this->loadBalancer
->reuseConnection( $dbw );
485 * Reset the notification timestamp of this entry
488 * @param Title $title
489 * @param string $force Whether to force the write query to be executed even if the
490 * page is not watched or the notification timestamp is already NULL.
491 * 'force' in order to force
492 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
494 * @return bool success
496 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
497 // Only loggedin user can have a watchlist
498 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
503 if ( $force != 'force' ) {
504 $item = $this->loadWatchedItem( $user, $title );
505 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
510 // If the page is watched by the user (or may be watched), update the timestamp
511 $job = new ActivityUpdateJob(
514 'type' => 'updateWatchlistNotification',
515 'userid' => $user->getId(),
516 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
521 // Try to run this post-send
522 // Calls DeferredUpdates::addCallableUpdate in normal operation
524 $this->deferredUpdatesAddCallableUpdateCallback
,
525 function() use ( $job ) {
530 $this->uncache( $user, $title );
535 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
537 // No oldid given, assuming latest revision; clear the timestamp.
541 if ( !$title->getNextRevisionID( $oldid ) ) {
542 // Oldid given and is the latest revision for this title; clear the timestamp.
546 if ( $item === null ) {
547 $item = $this->loadWatchedItem( $user, $title );
551 // This can only happen if $force is enabled.
555 // Oldid given and isn't the latest; update the timestamp.
556 // This will result in no further notification emails being sent!
557 // Calls Revision::getTimestampFromId in normal operation
558 $notificationTimestamp = call_user_func(
559 $this->revisionGetTimestampFromIdCallback
,
564 // We need to go one second to the future because of various strict comparisons
565 // throughout the codebase
566 $ts = new MWTimestamp( $notificationTimestamp );
567 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
568 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
570 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
571 if ( $force != 'force' ) {
574 // This is a little silly…
575 return $item->getNotificationTimestamp();
579 return $notificationTimestamp;
584 * @param int $unreadLimit
586 * @return int|bool The number of unread notifications
587 * true if greater than or equal to $unreadLimit
589 public function countUnreadNotifications( User
$user, $unreadLimit = null ) {
591 if ( $unreadLimit !== null ) {
592 $unreadLimit = (int)$unreadLimit;
593 $queryOptions['LIMIT'] = $unreadLimit;
596 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
597 $rowCount = $dbr->selectRowCount(
601 'wl_user' => $user->getId(),
602 'wl_notificationtimestamp IS NOT NULL',
607 $this->loadBalancer
->reuseConnection( $dbr );
609 if ( !isset( $unreadLimit ) ) {
613 if ( $rowCount >= $unreadLimit ) {
621 * Check if the given title already is watched by the user, and if so
622 * add a watch for the new title.
624 * To be used for page renames and such.
626 * @param LinkTarget $oldTarget
627 * @param LinkTarget $newTarget
629 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
630 if ( !$oldTarget instanceof Title
) {
631 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
633 if ( !$newTarget instanceof Title
) {
634 $newTarget = Title
::newFromLinkTarget( $newTarget );
637 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
638 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
642 * Check if the given title already is watched by the user, and if so
643 * add a watch for the new title.
645 * To be used for page renames and such.
646 * This must be called separately for Subject and Talk pages
648 * @param LinkTarget $oldTarget
649 * @param LinkTarget $newTarget
651 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
652 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
654 $result = $dbw->select(
656 [ 'wl_user', 'wl_notificationtimestamp' ],
658 'wl_namespace' => $oldTarget->getNamespace(),
659 'wl_title' => $oldTarget->getDBkey(),
665 $newNamespace = $newTarget->getNamespace();
666 $newDBkey = $newTarget->getDBkey();
668 # Construct array to replace into the watchlist
670 foreach ( $result as $row ) {
672 'wl_user' => $row->wl_user
,
673 'wl_namespace' => $newNamespace,
674 'wl_title' => $newDBkey,
675 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
679 if ( !empty( $values ) ) {
681 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
682 # some other DBMSes, mostly due to poor simulation by us
685 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
691 $this->loadBalancer
->reuseConnection( $dbw );