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 LinkTarget $target
214 public function countWatchers( LinkTarget
$target ) {
215 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
216 $return = (int)$dbr->selectField(
220 'wl_namespace' => $target->getNamespace(),
221 'wl_title' => $target->getDBkey(),
225 $this->loadBalancer
->reuseConnection( $dbr );
231 * Number of page watchers who also visited a "recent" edit
233 * @param LinkTarget $target
234 * @param mixed $threshold timestamp accepted by wfTimestamp
237 * @throws DBUnexpectedError
238 * @throws MWException
240 public function countVisitingWatchers( LinkTarget
$target, $threshold ) {
241 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
242 $visitingWatchers = (int)$dbr->selectField(
246 'wl_namespace' => $target->getNamespace(),
247 'wl_title' => $target->getDBkey(),
248 'wl_notificationtimestamp >= ' .
249 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
250 ' OR wl_notificationtimestamp IS NULL'
254 $this->loadBalancer
->reuseConnection( $dbr );
256 return $visitingWatchers;
260 * @param LinkTarget[] $targets
261 * @param array $options Allowed keys:
262 * 'minimumWatchers' => int
264 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
265 * All targets will be present in the result. 0 either means no watchers or the number
266 * of watchers was below the minimumWatchers option if passed.
268 public function countWatchersMultiple( array $targets, array $options = [] ) {
269 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
271 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
273 if ( array_key_exists( 'minimumWatchers', $options ) ) {
274 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
277 $lb = new LinkBatch( $targets );
280 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
281 [ $lb->constructSet( 'wl', $dbr ) ],
286 $this->loadBalancer
->reuseConnection( $dbr );
289 foreach ( $targets as $linkTarget ) {
290 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
293 foreach ( $res as $row ) {
294 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
301 * Get an item (may be cached)
304 * @param LinkTarget $target
306 * @return WatchedItem|false
308 public function getWatchedItem( User
$user, LinkTarget
$target ) {
309 if ( $user->isAnon() ) {
313 $cached = $this->getCached( $user, $target );
317 return $this->loadWatchedItem( $user, $target );
321 * Loads an item from the db
324 * @param LinkTarget $target
326 * @return WatchedItem|false
328 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
329 // Only loggedin user can have a watchlist
330 if ( $user->isAnon() ) {
334 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
335 $row = $dbr->selectRow(
337 'wl_notificationtimestamp',
338 $this->dbCond( $user, $target ),
341 $this->loadBalancer
->reuseConnection( $dbr );
347 $item = new WatchedItem(
350 $row->wl_notificationtimestamp
352 $this->cache( $item );
358 * Must be called separately for Subject & Talk namespaces
361 * @param LinkTarget $target
365 public function isWatched( User
$user, LinkTarget
$target ) {
366 return (bool)$this->getWatchedItem( $user, $target );
370 * Must be called separately for Subject & Talk namespaces
373 * @param LinkTarget $target
375 public function addWatch( User
$user, LinkTarget
$target ) {
376 $this->addWatchBatch( [ [ $user, $target ] ] );
380 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
382 * @return bool success
384 public function addWatchBatch( array $userTargetCombinations ) {
385 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
390 foreach ( $userTargetCombinations as list( $user, $target ) ) {
393 * @var LinkTarget $target
396 // Only loggedin user can have a watchlist
397 if ( $user->isAnon() ) {
401 'wl_user' => $user->getId(),
402 'wl_namespace' => $target->getNamespace(),
403 'wl_title' => $target->getDBkey(),
404 'wl_notificationtimestamp' => null,
406 $this->uncache( $user, $target );
413 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
414 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
415 // Use INSERT IGNORE to avoid overwriting the notification timestamp
416 // if there's already an entry for this page
417 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
419 $this->loadBalancer
->reuseConnection( $dbw );
425 * Removes the an entry for the User watching the LinkTarget
426 * Must be called separately for Subject & Talk namespaces
429 * @param LinkTarget $target
431 * @return bool success
432 * @throws DBUnexpectedError
433 * @throws MWException
435 public function removeWatch( User
$user, LinkTarget
$target ) {
436 // Only logged in user can have a watchlist
437 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
441 $this->uncache( $user, $target );
443 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
444 $dbw->delete( 'watchlist',
446 'wl_user' => $user->getId(),
447 'wl_namespace' => $target->getNamespace(),
448 'wl_title' => $target->getDBkey(),
451 $success = (bool)$dbw->affectedRows();
452 $this->loadBalancer
->reuseConnection( $dbw );
458 * @param User $editor The editor that triggered the update. Their notification
459 * timestamp will not be updated(they have already seen it)
460 * @param LinkTarget $target The target to update timestamps for
461 * @param string $timestamp Set the update timestamp to this value
463 * @return int[] Array of user IDs the timestamp has been updated for
465 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
466 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
467 $res = $dbw->select( [ 'watchlist' ],
470 'wl_user != ' . intval( $editor->getId() ),
471 'wl_namespace' => $target->getNamespace(),
472 'wl_title' => $target->getDBkey(),
473 'wl_notificationtimestamp IS NULL',
478 foreach ( $res as $row ) {
479 $watchers[] = intval( $row->wl_user
);
483 // Update wl_notificationtimestamp for all watching users except the editor
485 $dbw->onTransactionIdle(
486 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
487 $dbw->update( 'watchlist',
489 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
491 'wl_user' => $watchers,
492 'wl_namespace' => $target->getNamespace(),
493 'wl_title' => $target->getDBkey(),
496 $this->uncacheLinkTarget( $target );
501 $this->loadBalancer
->reuseConnection( $dbw );
507 * Reset the notification timestamp of this entry
510 * @param Title $title
511 * @param string $force Whether to force the write query to be executed even if the
512 * page is not watched or the notification timestamp is already NULL.
513 * 'force' in order to force
514 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
516 * @return bool success
518 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
519 // Only loggedin user can have a watchlist
520 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
525 if ( $force != 'force' ) {
526 $item = $this->loadWatchedItem( $user, $title );
527 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
532 // If the page is watched by the user (or may be watched), update the timestamp
533 $job = new ActivityUpdateJob(
536 'type' => 'updateWatchlistNotification',
537 'userid' => $user->getId(),
538 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
543 // Try to run this post-send
544 // Calls DeferredUpdates::addCallableUpdate in normal operation
546 $this->deferredUpdatesAddCallableUpdateCallback
,
547 function() use ( $job ) {
552 $this->uncache( $user, $title );
557 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
559 // No oldid given, assuming latest revision; clear the timestamp.
563 if ( !$title->getNextRevisionID( $oldid ) ) {
564 // Oldid given and is the latest revision for this title; clear the timestamp.
568 if ( $item === null ) {
569 $item = $this->loadWatchedItem( $user, $title );
573 // This can only happen if $force is enabled.
577 // Oldid given and isn't the latest; update the timestamp.
578 // This will result in no further notification emails being sent!
579 // Calls Revision::getTimestampFromId in normal operation
580 $notificationTimestamp = call_user_func(
581 $this->revisionGetTimestampFromIdCallback
,
586 // We need to go one second to the future because of various strict comparisons
587 // throughout the codebase
588 $ts = new MWTimestamp( $notificationTimestamp );
589 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
590 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
592 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
593 if ( $force != 'force' ) {
596 // This is a little silly…
597 return $item->getNotificationTimestamp();
601 return $notificationTimestamp;
606 * @param int $unreadLimit
608 * @return int|bool The number of unread notifications
609 * true if greater than or equal to $unreadLimit
611 public function countUnreadNotifications( User
$user, $unreadLimit = null ) {
613 if ( $unreadLimit !== null ) {
614 $unreadLimit = (int)$unreadLimit;
615 $queryOptions['LIMIT'] = $unreadLimit;
618 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
619 $rowCount = $dbr->selectRowCount(
623 'wl_user' => $user->getId(),
624 'wl_notificationtimestamp IS NOT NULL',
629 $this->loadBalancer
->reuseConnection( $dbr );
631 if ( !isset( $unreadLimit ) ) {
635 if ( $rowCount >= $unreadLimit ) {
643 * Check if the given title already is watched by the user, and if so
644 * add a watch for the new title.
646 * To be used for page renames and such.
648 * @param LinkTarget $oldTarget
649 * @param LinkTarget $newTarget
651 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
652 if ( !$oldTarget instanceof Title
) {
653 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
655 if ( !$newTarget instanceof Title
) {
656 $newTarget = Title
::newFromLinkTarget( $newTarget );
659 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
660 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
664 * Check if the given title already is watched by the user, and if so
665 * add a watch for the new title.
667 * To be used for page renames and such.
668 * This must be called separately for Subject and Talk pages
670 * @param LinkTarget $oldTarget
671 * @param LinkTarget $newTarget
673 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
674 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
676 $result = $dbw->select(
678 [ 'wl_user', 'wl_notificationtimestamp' ],
680 'wl_namespace' => $oldTarget->getNamespace(),
681 'wl_title' => $oldTarget->getDBkey(),
687 $newNamespace = $newTarget->getNamespace();
688 $newDBkey = $newTarget->getDBkey();
690 # Construct array to replace into the watchlist
692 foreach ( $result as $row ) {
694 'wl_user' => $row->wl_user
,
695 'wl_namespace' => $newNamespace,
696 'wl_title' => $newDBkey,
697 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
701 if ( !empty( $values ) ) {
703 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
704 # some other DBMSes, mostly due to poor simulation by us
707 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
713 $this->loadBalancer
->reuseConnection( $dbw );