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 * @param LinkTarget[] $targets
210 * @param array $options Allowed keys:
211 * 'minimumWatchers' => int
213 * @return array multi dimensional like $return[$namespaceId][$titleString] = int $watchers
214 * All targets will be present in the result. 0 either means no watchers or the number
215 * of watchers was below the minimumWatchers option if passed.
217 public function countWatchersMultiple( array $targets, array $options = [] ) {
218 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
220 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
222 if ( array_key_exists( 'minimumWatchers', $options ) ) {
223 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
226 $lb = new LinkBatch( $targets );
229 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
230 [ $lb->constructSet( 'wl', $dbr ) ],
235 $this->loadBalancer
->reuseConnection( $dbr );
238 foreach ( $targets as $linkTarget ) {
239 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
242 foreach ( $res as $row ) {
243 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
250 * Get an item (may be cached)
253 * @param LinkTarget $target
255 * @return WatchedItem|false
257 public function getWatchedItem( User
$user, LinkTarget
$target ) {
258 if ( $user->isAnon() ) {
262 $cached = $this->getCached( $user, $target );
266 return $this->loadWatchedItem( $user, $target );
270 * Loads an item from the db
273 * @param LinkTarget $target
275 * @return WatchedItem|false
277 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
278 // Only loggedin user can have a watchlist
279 if ( $user->isAnon() ) {
283 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
284 $row = $dbr->selectRow(
286 'wl_notificationtimestamp',
287 $this->dbCond( $user, $target ),
290 $this->loadBalancer
->reuseConnection( $dbr );
296 $item = new WatchedItem(
299 $row->wl_notificationtimestamp
301 $this->cache( $item );
307 * Must be called separately for Subject & Talk namespaces
310 * @param LinkTarget $target
314 public function isWatched( User
$user, LinkTarget
$target ) {
315 return (bool)$this->getWatchedItem( $user, $target );
319 * Must be called separately for Subject & Talk namespaces
322 * @param LinkTarget $target
324 public function addWatch( User
$user, LinkTarget
$target ) {
325 $this->addWatchBatch( [ [ $user, $target ] ] );
329 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
331 * @return bool success
333 public function addWatchBatch( array $userTargetCombinations ) {
334 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
339 foreach ( $userTargetCombinations as list( $user, $target ) ) {
342 * @var LinkTarget $target
345 // Only loggedin user can have a watchlist
346 if ( $user->isAnon() ) {
350 'wl_user' => $user->getId(),
351 'wl_namespace' => $target->getNamespace(),
352 'wl_title' => $target->getDBkey(),
353 'wl_notificationtimestamp' => null,
355 $this->uncache( $user, $target );
362 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
363 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
364 // Use INSERT IGNORE to avoid overwriting the notification timestamp
365 // if there's already an entry for this page
366 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
368 $this->loadBalancer
->reuseConnection( $dbw );
374 * Removes the an entry for the User watching the LinkTarget
375 * Must be called separately for Subject & Talk namespaces
378 * @param LinkTarget $target
380 * @return bool success
381 * @throws DBUnexpectedError
382 * @throws MWException
384 public function removeWatch( User
$user, LinkTarget
$target ) {
385 // Only logged in user can have a watchlist
386 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
390 $this->uncache( $user, $target );
392 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
393 $dbw->delete( 'watchlist',
395 'wl_user' => $user->getId(),
396 'wl_namespace' => $target->getNamespace(),
397 'wl_title' => $target->getDBkey(),
400 $success = (bool)$dbw->affectedRows();
401 $this->loadBalancer
->reuseConnection( $dbw );
407 * @param User $editor The editor that triggered the update. Their notification
408 * timestamp will not be updated(they have already seen it)
409 * @param LinkTarget $target The target to update timestamps for
410 * @param string $timestamp Set the update timestamp to this value
412 * @return int[] Array of user IDs the timestamp has been updated for
414 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
415 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
416 $res = $dbw->select( [ 'watchlist' ],
419 'wl_user != ' . intval( $editor->getId() ),
420 'wl_namespace' => $target->getNamespace(),
421 'wl_title' => $target->getDBkey(),
422 'wl_notificationtimestamp IS NULL',
427 foreach ( $res as $row ) {
428 $watchers[] = intval( $row->wl_user
);
432 // Update wl_notificationtimestamp for all watching users except the editor
434 $dbw->onTransactionIdle(
435 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
436 $dbw->update( 'watchlist',
438 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
440 'wl_user' => $watchers,
441 'wl_namespace' => $target->getNamespace(),
442 'wl_title' => $target->getDBkey(),
445 $this->uncacheLinkTarget( $target );
450 $this->loadBalancer
->reuseConnection( $dbw );
456 * Reset the notification timestamp of this entry
459 * @param Title $title
460 * @param string $force Whether to force the write query to be executed even if the
461 * page is not watched or the notification timestamp is already NULL.
462 * 'force' in order to force
463 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
465 * @return bool success
467 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
468 // Only loggedin user can have a watchlist
469 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
474 if ( $force != 'force' ) {
475 $item = $this->loadWatchedItem( $user, $title );
476 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
481 // If the page is watched by the user (or may be watched), update the timestamp
482 $job = new ActivityUpdateJob(
485 'type' => 'updateWatchlistNotification',
486 'userid' => $user->getId(),
487 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
492 // Try to run this post-send
493 // Calls DeferredUpdates::addCallableUpdate in normal operation
495 $this->deferredUpdatesAddCallableUpdateCallback
,
496 function() use ( $job ) {
501 $this->uncache( $user, $title );
506 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
508 // No oldid given, assuming latest revision; clear the timestamp.
512 if ( !$title->getNextRevisionID( $oldid ) ) {
513 // Oldid given and is the latest revision for this title; clear the timestamp.
517 if ( $item === null ) {
518 $item = $this->loadWatchedItem( $user, $title );
522 // This can only happen if $force is enabled.
526 // Oldid given and isn't the latest; update the timestamp.
527 // This will result in no further notification emails being sent!
528 // Calls Revision::getTimestampFromId in normal operation
529 $notificationTimestamp = call_user_func(
530 $this->revisionGetTimestampFromIdCallback
,
535 // We need to go one second to the future because of various strict comparisons
536 // throughout the codebase
537 $ts = new MWTimestamp( $notificationTimestamp );
538 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
539 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
541 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
542 if ( $force != 'force' ) {
545 // This is a little silly…
546 return $item->getNotificationTimestamp();
550 return $notificationTimestamp;
554 * Check if the given title already is watched by the user, and if so
555 * add a watch for the new title.
557 * To be used for page renames and such.
559 * @param LinkTarget $oldTarget
560 * @param LinkTarget $newTarget
562 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
563 if ( !$oldTarget instanceof Title
) {
564 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
566 if ( !$newTarget instanceof Title
) {
567 $newTarget = Title
::newFromLinkTarget( $newTarget );
570 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
571 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
575 * Check if the given title already is watched by the user, and if so
576 * add a watch for the new title.
578 * To be used for page renames and such.
579 * This must be called separately for Subject and Talk pages
581 * @param LinkTarget $oldTarget
582 * @param LinkTarget $newTarget
584 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
585 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
587 $result = $dbw->select(
589 [ 'wl_user', 'wl_notificationtimestamp' ],
591 'wl_namespace' => $oldTarget->getNamespace(),
592 'wl_title' => $oldTarget->getDBkey(),
598 $newNamespace = $newTarget->getNamespace();
599 $newDBkey = $newTarget->getDBkey();
601 # Construct array to replace into the watchlist
603 foreach ( $result as $row ) {
605 'wl_user' => $row->wl_user
,
606 'wl_namespace' => $newNamespace,
607 'wl_title' => $newDBkey,
608 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
612 if ( !empty( $values ) ) {
614 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
615 # some other DBMSes, mostly due to poor simulation by us
618 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
624 $this->loadBalancer
->reuseConnection( $dbw );