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 * Count the number of individual items that are watched by the user.
230 * If a subject and corresponding talk page are watched this will return 2.
236 public function countWatchedItems( User
$user ) {
237 $dbr = $this->getConnection( DB_SLAVE
);
238 $return = (int)$dbr->selectField(
242 'wl_user' => $user->getId()
246 $this->reuseConnection( $dbr );
252 * @param LinkTarget $target
256 public function countWatchers( LinkTarget
$target ) {
257 $dbr = $this->getConnection( DB_SLAVE
);
258 $return = (int)$dbr->selectField(
262 'wl_namespace' => $target->getNamespace(),
263 'wl_title' => $target->getDBkey(),
267 $this->reuseConnection( $dbr );
273 * Number of page watchers who also visited a "recent" edit
275 * @param LinkTarget $target
276 * @param mixed $threshold timestamp accepted by wfTimestamp
279 * @throws DBUnexpectedError
280 * @throws MWException
282 public function countVisitingWatchers( LinkTarget
$target, $threshold ) {
283 $dbr = $this->getConnection( DB_SLAVE
);
284 $visitingWatchers = (int)$dbr->selectField(
288 'wl_namespace' => $target->getNamespace(),
289 'wl_title' => $target->getDBkey(),
290 'wl_notificationtimestamp >= ' .
291 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
292 ' OR wl_notificationtimestamp IS NULL'
296 $this->reuseConnection( $dbr );
298 return $visitingWatchers;
302 * @param LinkTarget[] $targets
303 * @param array $options Allowed keys:
304 * 'minimumWatchers' => int
306 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
307 * All targets will be present in the result. 0 either means no watchers or the number
308 * of watchers was below the minimumWatchers option if passed.
310 public function countWatchersMultiple( array $targets, array $options = [] ) {
311 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
313 $dbr = $this->getConnection( DB_SLAVE
);
315 if ( array_key_exists( 'minimumWatchers', $options ) ) {
316 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
319 $lb = new LinkBatch( $targets );
322 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
323 [ $lb->constructSet( 'wl', $dbr ) ],
328 $this->reuseConnection( $dbr );
331 foreach ( $targets as $linkTarget ) {
332 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
335 foreach ( $res as $row ) {
336 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
343 * Get an item (may be cached)
346 * @param LinkTarget $target
348 * @return WatchedItem|false
350 public function getWatchedItem( User
$user, LinkTarget
$target ) {
351 if ( $user->isAnon() ) {
355 $cached = $this->getCached( $user, $target );
359 return $this->loadWatchedItem( $user, $target );
363 * Loads an item from the db
366 * @param LinkTarget $target
368 * @return WatchedItem|false
370 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
371 // Only loggedin user can have a watchlist
372 if ( $user->isAnon() ) {
376 $dbr = $this->getConnection( DB_SLAVE
);
377 $row = $dbr->selectRow(
379 'wl_notificationtimestamp',
380 $this->dbCond( $user, $target ),
383 $this->reuseConnection( $dbr );
389 $item = new WatchedItem(
392 $row->wl_notificationtimestamp
394 $this->cache( $item );
400 * Must be called separately for Subject & Talk namespaces
403 * @param LinkTarget $target
407 public function isWatched( User
$user, LinkTarget
$target ) {
408 return (bool)$this->getWatchedItem( $user, $target );
412 * Must be called separately for Subject & Talk namespaces
415 * @param LinkTarget $target
417 public function addWatch( User
$user, LinkTarget
$target ) {
418 $this->addWatchBatch( [ [ $user, $target ] ] );
422 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
424 * @return bool success
426 public function addWatchBatch( array $userTargetCombinations ) {
427 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
432 foreach ( $userTargetCombinations as list( $user, $target ) ) {
435 * @var LinkTarget $target
438 // Only loggedin user can have a watchlist
439 if ( $user->isAnon() ) {
443 'wl_user' => $user->getId(),
444 'wl_namespace' => $target->getNamespace(),
445 'wl_title' => $target->getDBkey(),
446 'wl_notificationtimestamp' => null,
448 $this->uncache( $user, $target );
455 $dbw = $this->getConnection( DB_MASTER
);
456 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
457 // Use INSERT IGNORE to avoid overwriting the notification timestamp
458 // if there's already an entry for this page
459 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
461 $this->reuseConnection( $dbw );
467 * Removes the an entry for the User watching the LinkTarget
468 * Must be called separately for Subject & Talk namespaces
471 * @param LinkTarget $target
473 * @return bool success
474 * @throws DBUnexpectedError
475 * @throws MWException
477 public function removeWatch( User
$user, LinkTarget
$target ) {
478 // Only logged in user can have a watchlist
479 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
483 $this->uncache( $user, $target );
485 $dbw = $this->getConnection( DB_MASTER
);
486 $dbw->delete( 'watchlist',
488 'wl_user' => $user->getId(),
489 'wl_namespace' => $target->getNamespace(),
490 'wl_title' => $target->getDBkey(),
493 $success = (bool)$dbw->affectedRows();
494 $this->reuseConnection( $dbw );
500 * @param User $editor The editor that triggered the update. Their notification
501 * timestamp will not be updated(they have already seen it)
502 * @param LinkTarget $target The target to update timestamps for
503 * @param string $timestamp Set the update timestamp to this value
505 * @return int[] Array of user IDs the timestamp has been updated for
507 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
508 $dbw = $this->getConnection( DB_MASTER
);
509 $res = $dbw->select( [ 'watchlist' ],
512 'wl_user != ' . intval( $editor->getId() ),
513 'wl_namespace' => $target->getNamespace(),
514 'wl_title' => $target->getDBkey(),
515 'wl_notificationtimestamp IS NULL',
520 foreach ( $res as $row ) {
521 $watchers[] = intval( $row->wl_user
);
525 // Update wl_notificationtimestamp for all watching users except the editor
527 $dbw->onTransactionIdle(
528 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
529 $dbw->update( 'watchlist',
531 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
533 'wl_user' => $watchers,
534 'wl_namespace' => $target->getNamespace(),
535 'wl_title' => $target->getDBkey(),
538 $this->uncacheLinkTarget( $target );
543 $this->reuseConnection( $dbw );
549 * Reset the notification timestamp of this entry
552 * @param Title $title
553 * @param string $force Whether to force the write query to be executed even if the
554 * page is not watched or the notification timestamp is already NULL.
555 * 'force' in order to force
556 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
558 * @return bool success
560 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
561 // Only loggedin user can have a watchlist
562 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
567 if ( $force != 'force' ) {
568 $item = $this->loadWatchedItem( $user, $title );
569 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
574 // If the page is watched by the user (or may be watched), update the timestamp
575 $job = new ActivityUpdateJob(
578 'type' => 'updateWatchlistNotification',
579 'userid' => $user->getId(),
580 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
585 // Try to run this post-send
586 // Calls DeferredUpdates::addCallableUpdate in normal operation
588 $this->deferredUpdatesAddCallableUpdateCallback
,
589 function() use ( $job ) {
594 $this->uncache( $user, $title );
599 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
601 // No oldid given, assuming latest revision; clear the timestamp.
605 if ( !$title->getNextRevisionID( $oldid ) ) {
606 // Oldid given and is the latest revision for this title; clear the timestamp.
610 if ( $item === null ) {
611 $item = $this->loadWatchedItem( $user, $title );
615 // This can only happen if $force is enabled.
619 // Oldid given and isn't the latest; update the timestamp.
620 // This will result in no further notification emails being sent!
621 // Calls Revision::getTimestampFromId in normal operation
622 $notificationTimestamp = call_user_func(
623 $this->revisionGetTimestampFromIdCallback
,
628 // We need to go one second to the future because of various strict comparisons
629 // throughout the codebase
630 $ts = new MWTimestamp( $notificationTimestamp );
631 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
632 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
634 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
635 if ( $force != 'force' ) {
638 // This is a little silly…
639 return $item->getNotificationTimestamp();
643 return $notificationTimestamp;
648 * @param int $unreadLimit
650 * @return int|bool The number of unread notifications
651 * true if greater than or equal to $unreadLimit
653 public function countUnreadNotifications( User
$user, $unreadLimit = null ) {
655 if ( $unreadLimit !== null ) {
656 $unreadLimit = (int)$unreadLimit;
657 $queryOptions['LIMIT'] = $unreadLimit;
660 $dbr = $this->getConnection( DB_SLAVE
);
661 $rowCount = $dbr->selectRowCount(
665 'wl_user' => $user->getId(),
666 'wl_notificationtimestamp IS NOT NULL',
671 $this->reuseConnection( $dbr );
673 if ( !isset( $unreadLimit ) ) {
677 if ( $rowCount >= $unreadLimit ) {
685 * Check if the given title already is watched by the user, and if so
686 * add a watch for the new title.
688 * To be used for page renames and such.
690 * @param LinkTarget $oldTarget
691 * @param LinkTarget $newTarget
693 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
694 if ( !$oldTarget instanceof Title
) {
695 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
697 if ( !$newTarget instanceof Title
) {
698 $newTarget = Title
::newFromLinkTarget( $newTarget );
701 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
702 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
706 * Check if the given title already is watched by the user, and if so
707 * add a watch for the new title.
709 * To be used for page renames and such.
710 * This must be called separately for Subject and Talk pages
712 * @param LinkTarget $oldTarget
713 * @param LinkTarget $newTarget
715 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
716 $dbw = $this->getConnection( DB_MASTER
);
718 $result = $dbw->select(
720 [ 'wl_user', 'wl_notificationtimestamp' ],
722 'wl_namespace' => $oldTarget->getNamespace(),
723 'wl_title' => $oldTarget->getDBkey(),
729 $newNamespace = $newTarget->getNamespace();
730 $newDBkey = $newTarget->getDBkey();
732 # Construct array to replace into the watchlist
734 foreach ( $result as $row ) {
736 'wl_user' => $row->wl_user
,
737 'wl_namespace' => $newNamespace,
738 'wl_title' => $newDBkey,
739 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
743 if ( !empty( $values ) ) {
745 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
746 # some other DBMSes, mostly due to poor simulation by us
749 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
755 $this->reuseConnection( $dbw );