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;
48 public function __construct( LoadBalancer
$loadBalancer, HashBagOStuff
$cache ) {
49 $this->loadBalancer
= $loadBalancer;
50 $this->cache
= $cache;
51 $this->deferredUpdatesAddCallableUpdateCallback
= [ 'DeferredUpdates', 'addCallableUpdate' ];
52 $this->revisionGetTimestampFromIdCallback
= [ 'Revision', 'getTimestampFromId' ];
56 * Overrides the DeferredUpdates::addCallableUpdate callback
57 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
59 * @param callable $callback
60 * @see DeferredUpdates::addCallableUpdate for callback signiture
64 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
65 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
66 throw new MWException(
67 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
70 Assert
::parameterType( 'callable', $callback, '$callback' );
71 $this->deferredUpdatesAddCallableUpdateCallback
= $callback;
75 * Overrides the Revision::getTimestampFromId callback
76 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
78 * @param callable $callback
79 * @see Revision::getTimestampFromId for callback signiture
83 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
84 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
85 throw new MWException(
86 'Cannot override Revision::getTimestampFromId callback in operation.'
89 Assert
::parameterType( 'callable', $callback, '$callback' );
90 $this->revisionGetTimestampFromIdCallback
= $callback;
94 * Overrides the default instance of this class
95 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
97 * @param WatchedItemStore $store
101 public static function overrideDefaultInstance( WatchedItemStore
$store ) {
102 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
103 throw new MWException(
104 'Cannot override ' . __CLASS__
. 'default instance in operation.'
107 self
::$instance = $store;
113 public static function getDefaultInstance() {
114 if ( !self
::$instance ) {
115 self
::$instance = new self(
117 new HashBagOStuff( [ 'maxKeys' => 100 ] )
120 return self
::$instance;
123 private function getCacheKey( User
$user, LinkTarget
$target ) {
124 return $this->cache
->makeKey(
125 (string)$target->getNamespace(),
127 (string)$user->getId()
131 private function cache( WatchedItem
$item ) {
132 $user = $item->getUser();
133 $target = $item->getLinkTarget();
134 $key = $this->getCacheKey( $user, $target );
135 $this->cache
->set( $key, $item );
136 $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
139 private function uncache( User
$user, LinkTarget
$target ) {
140 $this->cache
->delete( $this->getCacheKey( $user, $target ) );
141 unset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
144 private function uncacheLinkTarget( LinkTarget
$target ) {
145 if ( !isset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] ) ) {
148 foreach ( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] as $key ) {
149 $this->cache
->delete( $key );
155 * @param LinkTarget $target
157 * @return WatchedItem|null
159 private function getCached( User
$user, LinkTarget
$target ) {
160 return $this->cache
->get( $this->getCacheKey( $user, $target ) );
164 * Return an array of conditions to select or update the appropriate database
168 * @param LinkTarget $target
172 private function dbCond( User
$user, LinkTarget
$target ) {
174 'wl_user' => $user->getId(),
175 'wl_namespace' => $target->getNamespace(),
176 'wl_title' => $target->getDBkey(),
181 * Get an item (may be cached)
184 * @param LinkTarget $target
186 * @return WatchedItem|false
188 public function getWatchedItem( User
$user, LinkTarget
$target ) {
189 $cached = $this->getCached( $user, $target );
193 return $this->loadWatchedItem( $user, $target );
197 * Loads an item from the db
200 * @param LinkTarget $target
202 * @return WatchedItem|false
204 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
205 // Only loggedin user can have a watchlist
206 if ( $user->isAnon() ) {
210 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
211 $row = $dbr->selectRow(
213 'wl_notificationtimestamp',
214 $this->dbCond( $user, $target ),
217 $this->loadBalancer
->reuseConnection( $dbr );
223 $item = new WatchedItem(
226 $row->wl_notificationtimestamp
228 $this->cache( $item );
234 * Must be called separately for Subject & Talk namespaces
237 * @param LinkTarget $target
241 public function isWatched( User
$user, LinkTarget
$target ) {
242 return (bool)$this->getWatchedItem( $user, $target );
246 * Must be called separately for Subject & Talk namespaces
249 * @param LinkTarget $target
251 public function addWatch( User
$user, LinkTarget
$target ) {
252 $this->addWatchBatch( [ [ $user, $target ] ] );
256 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
258 * @return bool success
260 public function addWatchBatch( array $userTargetCombinations ) {
261 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
266 foreach ( $userTargetCombinations as list( $user, $target ) ) {
269 * @var LinkTarget $target
272 // Only loggedin user can have a watchlist
273 if ( $user->isAnon() ) {
277 'wl_user' => $user->getId(),
278 'wl_namespace' => $target->getNamespace(),
279 'wl_title' => $target->getDBkey(),
280 'wl_notificationtimestamp' => null,
282 $this->uncache( $user, $target );
289 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
290 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
291 // Use INSERT IGNORE to avoid overwriting the notification timestamp
292 // if there's already an entry for this page
293 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
295 $this->loadBalancer
->reuseConnection( $dbw );
301 * Removes the an entry for the User watching the LinkTarget
302 * Must be called separately for Subject & Talk namespaces
305 * @param LinkTarget $target
307 * @return bool success
308 * @throws DBUnexpectedError
309 * @throws MWException
311 public function removeWatch( User
$user, LinkTarget
$target ) {
312 // Only logged in user can have a watchlist
313 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
317 $this->uncache( $user, $target );
319 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
320 $dbw->delete( 'watchlist',
322 'wl_user' => $user->getId(),
323 'wl_namespace' => $target->getNamespace(),
324 'wl_title' => $target->getDBkey(),
327 $success = (bool)$dbw->affectedRows();
328 $this->loadBalancer
->reuseConnection( $dbw );
334 * @param User $editor The editor that triggered the update. Their notification
335 * timestamp will not be updated(they have already seen it)
336 * @param LinkTarget $target The target to update timestamps for
337 * @param string $timestamp Set the update timestamp to this value
339 * @return int[] Array of user IDs the timestamp has been updated for
341 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
342 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
343 $res = $dbw->select( [ 'watchlist' ],
346 'wl_user != ' . intval( $editor->getId() ),
347 'wl_namespace' => $target->getNamespace(),
348 'wl_title' => $target->getDBkey(),
349 'wl_notificationtimestamp IS NULL',
354 foreach ( $res as $row ) {
355 $watchers[] = intval( $row->wl_user
);
359 // Update wl_notificationtimestamp for all watching users except the editor
361 $dbw->onTransactionIdle(
362 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
363 $dbw->update( 'watchlist',
365 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
367 'wl_user' => $watchers,
368 'wl_namespace' => $target->getNamespace(),
369 'wl_title' => $target->getDBkey(),
372 $this->uncacheLinkTarget( $target );
377 $this->loadBalancer
->reuseConnection( $dbw );
383 * Reset the notification timestamp of this entry
386 * @param Title $title
387 * @param string $force Whether to force the write query to be executed even if the
388 * page is not watched or the notification timestamp is already NULL.
389 * 'force' in order to force
390 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
392 * @return bool success
394 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
395 // Only loggedin user can have a watchlist
396 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
401 if ( $force != 'force' ) {
402 $item = $this->loadWatchedItem( $user, $title );
403 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
408 // If the page is watched by the user (or may be watched), update the timestamp
409 $job = new ActivityUpdateJob(
412 'type' => 'updateWatchlistNotification',
413 'userid' => $user->getId(),
414 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
419 // Try to run this post-send
420 // Calls DeferredUpdates::addCallableUpdate in normal operation
422 $this->deferredUpdatesAddCallableUpdateCallback
,
423 function() use ( $job ) {
428 $this->uncache( $user, $title );
433 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
435 // No oldid given, assuming latest revision; clear the timestamp.
439 if ( !$title->getNextRevisionID( $oldid ) ) {
440 // Oldid given and is the latest revision for this title; clear the timestamp.
444 if ( $item === null ) {
445 $item = $this->loadWatchedItem( $user, $title );
449 // This can only happen if $force is enabled.
453 // Oldid given and isn't the latest; update the timestamp.
454 // This will result in no further notification emails being sent!
455 // Calls Revision::getTimestampFromId in normal operation
456 $notificationTimestamp = call_user_func(
457 $this->revisionGetTimestampFromIdCallback
,
462 // We need to go one second to the future because of various strict comparisons
463 // throughout the codebase
464 $ts = new MWTimestamp( $notificationTimestamp );
465 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
466 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
468 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
469 if ( $force != 'force' ) {
472 // This is a little silly…
473 return $item->getNotificationTimestamp();
477 return $notificationTimestamp;
481 * Check if the given title already is watched by the user, and if so
482 * add a watch for the new title.
484 * To be used for page renames and such.
486 * @param LinkTarget $oldTarget
487 * @param LinkTarget $newTarget
489 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
490 if ( !$oldTarget instanceof Title
) {
491 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
493 if ( !$newTarget instanceof Title
) {
494 $newTarget = Title
::newFromLinkTarget( $newTarget );
497 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
498 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
502 * Check if the given title already is watched by the user, and if so
503 * add a watch for the new title.
505 * To be used for page renames and such.
506 * This must be called separately for Subject and Talk pages
508 * @param LinkTarget $oldTarget
509 * @param LinkTarget $newTarget
511 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
512 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
514 $result = $dbw->select(
516 [ 'wl_user', 'wl_notificationtimestamp' ],
518 'wl_namespace' => $oldTarget->getNamespace(),
519 'wl_title' => $oldTarget->getDBkey(),
525 $newNamespace = $newTarget->getNamespace();
526 $newDBkey = $newTarget->getDBkey();
528 # Construct array to replace into the watchlist
530 foreach ( $result as $row ) {
532 'wl_user' => $row->wl_user
,
533 'wl_namespace' => $newNamespace,
534 'wl_title' => $newDBkey,
535 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
539 if ( !empty( $values ) ) {
541 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
542 # some other DBMSes, mostly due to poor simulation by us
545 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
551 $this->loadBalancer
->reuseConnection( $dbw );