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 if ( $user->isAnon() ) {
193 $cached = $this->getCached( $user, $target );
197 return $this->loadWatchedItem( $user, $target );
201 * Loads an item from the db
204 * @param LinkTarget $target
206 * @return WatchedItem|false
208 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
209 // Only loggedin user can have a watchlist
210 if ( $user->isAnon() ) {
214 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
215 $row = $dbr->selectRow(
217 'wl_notificationtimestamp',
218 $this->dbCond( $user, $target ),
221 $this->loadBalancer
->reuseConnection( $dbr );
227 $item = new WatchedItem(
230 $row->wl_notificationtimestamp
232 $this->cache( $item );
238 * Must be called separately for Subject & Talk namespaces
241 * @param LinkTarget $target
245 public function isWatched( User
$user, LinkTarget
$target ) {
246 return (bool)$this->getWatchedItem( $user, $target );
250 * Must be called separately for Subject & Talk namespaces
253 * @param LinkTarget $target
255 public function addWatch( User
$user, LinkTarget
$target ) {
256 $this->addWatchBatch( [ [ $user, $target ] ] );
260 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
262 * @return bool success
264 public function addWatchBatch( array $userTargetCombinations ) {
265 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
270 foreach ( $userTargetCombinations as list( $user, $target ) ) {
273 * @var LinkTarget $target
276 // Only loggedin user can have a watchlist
277 if ( $user->isAnon() ) {
281 'wl_user' => $user->getId(),
282 'wl_namespace' => $target->getNamespace(),
283 'wl_title' => $target->getDBkey(),
284 'wl_notificationtimestamp' => null,
286 $this->uncache( $user, $target );
293 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
294 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
295 // Use INSERT IGNORE to avoid overwriting the notification timestamp
296 // if there's already an entry for this page
297 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
299 $this->loadBalancer
->reuseConnection( $dbw );
305 * Removes the an entry for the User watching the LinkTarget
306 * Must be called separately for Subject & Talk namespaces
309 * @param LinkTarget $target
311 * @return bool success
312 * @throws DBUnexpectedError
313 * @throws MWException
315 public function removeWatch( User
$user, LinkTarget
$target ) {
316 // Only logged in user can have a watchlist
317 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
321 $this->uncache( $user, $target );
323 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
324 $dbw->delete( 'watchlist',
326 'wl_user' => $user->getId(),
327 'wl_namespace' => $target->getNamespace(),
328 'wl_title' => $target->getDBkey(),
331 $success = (bool)$dbw->affectedRows();
332 $this->loadBalancer
->reuseConnection( $dbw );
338 * @param User $editor The editor that triggered the update. Their notification
339 * timestamp will not be updated(they have already seen it)
340 * @param LinkTarget $target The target to update timestamps for
341 * @param string $timestamp Set the update timestamp to this value
343 * @return int[] Array of user IDs the timestamp has been updated for
345 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
346 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
347 $res = $dbw->select( [ 'watchlist' ],
350 'wl_user != ' . intval( $editor->getId() ),
351 'wl_namespace' => $target->getNamespace(),
352 'wl_title' => $target->getDBkey(),
353 'wl_notificationtimestamp IS NULL',
358 foreach ( $res as $row ) {
359 $watchers[] = intval( $row->wl_user
);
363 // Update wl_notificationtimestamp for all watching users except the editor
365 $dbw->onTransactionIdle(
366 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
367 $dbw->update( 'watchlist',
369 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
371 'wl_user' => $watchers,
372 'wl_namespace' => $target->getNamespace(),
373 'wl_title' => $target->getDBkey(),
376 $this->uncacheLinkTarget( $target );
381 $this->loadBalancer
->reuseConnection( $dbw );
387 * Reset the notification timestamp of this entry
390 * @param Title $title
391 * @param string $force Whether to force the write query to be executed even if the
392 * page is not watched or the notification timestamp is already NULL.
393 * 'force' in order to force
394 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
396 * @return bool success
398 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
399 // Only loggedin user can have a watchlist
400 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
405 if ( $force != 'force' ) {
406 $item = $this->loadWatchedItem( $user, $title );
407 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
412 // If the page is watched by the user (or may be watched), update the timestamp
413 $job = new ActivityUpdateJob(
416 'type' => 'updateWatchlistNotification',
417 'userid' => $user->getId(),
418 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
423 // Try to run this post-send
424 // Calls DeferredUpdates::addCallableUpdate in normal operation
426 $this->deferredUpdatesAddCallableUpdateCallback
,
427 function() use ( $job ) {
432 $this->uncache( $user, $title );
437 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
439 // No oldid given, assuming latest revision; clear the timestamp.
443 if ( !$title->getNextRevisionID( $oldid ) ) {
444 // Oldid given and is the latest revision for this title; clear the timestamp.
448 if ( $item === null ) {
449 $item = $this->loadWatchedItem( $user, $title );
453 // This can only happen if $force is enabled.
457 // Oldid given and isn't the latest; update the timestamp.
458 // This will result in no further notification emails being sent!
459 // Calls Revision::getTimestampFromId in normal operation
460 $notificationTimestamp = call_user_func(
461 $this->revisionGetTimestampFromIdCallback
,
466 // We need to go one second to the future because of various strict comparisons
467 // throughout the codebase
468 $ts = new MWTimestamp( $notificationTimestamp );
469 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
470 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
472 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
473 if ( $force != 'force' ) {
476 // This is a little silly…
477 return $item->getNotificationTimestamp();
481 return $notificationTimestamp;
485 * Check if the given title already is watched by the user, and if so
486 * add a watch for the new title.
488 * To be used for page renames and such.
490 * @param LinkTarget $oldTarget
491 * @param LinkTarget $newTarget
493 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
494 if ( !$oldTarget instanceof Title
) {
495 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
497 if ( !$newTarget instanceof Title
) {
498 $newTarget = Title
::newFromLinkTarget( $newTarget );
501 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
502 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
506 * Check if the given title already is watched by the user, and if so
507 * add a watch for the new title.
509 * To be used for page renames and such.
510 * This must be called separately for Subject and Talk pages
512 * @param LinkTarget $oldTarget
513 * @param LinkTarget $newTarget
515 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
516 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
518 $result = $dbw->select(
520 [ 'wl_user', 'wl_notificationtimestamp' ],
522 'wl_namespace' => $oldTarget->getNamespace(),
523 'wl_title' => $oldTarget->getDBkey(),
529 $newNamespace = $newTarget->getNamespace();
530 $newDBkey = $newTarget->getDBkey();
532 # Construct array to replace into the watchlist
534 foreach ( $result as $row ) {
536 'wl_user' => $row->wl_user
,
537 'wl_namespace' => $newNamespace,
538 'wl_title' => $newDBkey,
539 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
543 if ( !empty( $values ) ) {
545 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
546 # some other DBMSes, mostly due to poor simulation by us
549 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
555 $this->loadBalancer
->reuseConnection( $dbw );