3 use Wikimedia\Assert\Assert
;
6 * Storage layer class for WatchedItems.
7 * Database interaction.
13 class WatchedItemStore
{
18 private $loadBalancer;
28 private $deferredUpdatesAddCallableUpdateCallback;
33 private $revisionGetTimestampFromIdCallback;
38 private static $instance;
40 public function __construct( LoadBalancer
$loadBalancer, BagOStuff
$cache ) {
41 $this->loadBalancer
= $loadBalancer;
42 $this->cache
= $cache;
43 $this->deferredUpdatesAddCallableUpdateCallback
= [ 'DeferredUpdates', 'addCallableUpdate' ];
44 $this->revisionGetTimestampFromIdCallback
= [ 'Revision', 'getTimestampFromId' ];
48 * Overrides the DeferredUpdates::addCallableUpdate callback
49 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
51 * @param callable $callback
52 * @see DeferredUpdates::addCallableUpdate for callback signiture
56 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
57 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
58 throw new MWException(
59 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
62 Assert
::parameterType( 'callable', $callback, '$callback' );
63 $this->deferredUpdatesAddCallableUpdateCallback
= $callback;
67 * Overrides the Revision::getTimestampFromId callback
68 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
70 * @param callable $callback
71 * @see Revision::getTimestampFromId for callback signiture
75 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
76 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
77 throw new MWException(
78 'Cannot override Revision::getTimestampFromId callback in operation.'
81 Assert
::parameterType( 'callable', $callback, '$callback' );
82 $this->revisionGetTimestampFromIdCallback
= $callback;
86 * Overrides the default instance of this class
87 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
89 * @param WatchedItemStore $store
93 public static function overrideDefaultInstance( WatchedItemStore
$store ) {
94 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
95 throw new MWException(
96 'Cannot override ' . __CLASS__
. 'default instance in operation.'
99 self
::$instance = $store;
105 public static function getDefaultInstance() {
106 if ( !self
::$instance ) {
107 self
::$instance = new self(
109 new HashBagOStuff( [ 'maxKeys' => 100 ] )
112 return self
::$instance;
115 private function getCacheKey( User
$user, LinkTarget
$target ) {
116 return $this->cache
->makeKey(
117 (string)$target->getNamespace(),
119 (string)$user->getId()
123 private function cache( WatchedItem
$item ) {
125 $this->getCacheKey( $item->getUser(), $item->getLinkTarget() ),
130 private function uncache( User
$user, LinkTarget
$target ) {
131 $this->cache
->delete( $this->getCacheKey( $user, $target ) );
136 * @param LinkTarget $target
138 * @return WatchedItem|null
140 private function getCached( User
$user, LinkTarget
$target ) {
141 return $this->cache
->get( $this->getCacheKey( $user, $target ) );
145 * Return an array of conditions to select or update the appropriate database
149 * @param LinkTarget $target
153 private function dbCond( User
$user, LinkTarget
$target ) {
155 'wl_user' => $user->getId(),
156 'wl_namespace' => $target->getNamespace(),
157 'wl_title' => $target->getDBkey(),
162 * Get an item (may be cached)
165 * @param LinkTarget $target
167 * @return WatchedItem|false
169 public function getWatchedItem( User
$user, LinkTarget
$target ) {
170 $cached = $this->getCached( $user, $target );
174 return $this->loadWatchedItem( $user, $target );
178 * Loads an item from the db
181 * @param LinkTarget $target
183 * @return WatchedItem|false
185 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
186 // Only loggedin user can have a watchlist
187 if ( $user->isAnon() ) {
191 $dbr = $this->loadBalancer
->getConnection( DB_SLAVE
, [ 'watchlist' ] );
192 $row = $dbr->selectRow(
194 'wl_notificationtimestamp',
195 $this->dbCond( $user, $target ),
198 $this->loadBalancer
->reuseConnection( $dbr );
204 $item = new WatchedItem(
207 $row->wl_notificationtimestamp
209 $this->cache( $item );
215 * Must be called separately for Subject & Talk namespaces
218 * @param LinkTarget $target
222 public function isWatched( User
$user, LinkTarget
$target ) {
223 return (bool)$this->getWatchedItem( $user, $target );
227 * Must be called separately for Subject & Talk namespaces
230 * @param LinkTarget $target
232 public function addWatch( User
$user, LinkTarget
$target ) {
233 $this->addWatchBatch( [ [ $user, $target ] ] );
237 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
239 * @return bool success
241 public function addWatchBatch( array $userTargetCombinations ) {
242 if ( $this->loadBalancer
->getReadOnlyReason() !== false ) {
247 foreach ( $userTargetCombinations as list( $user, $target ) ) {
250 * @var LinkTarget $target
253 // Only loggedin user can have a watchlist
254 if ( $user->isAnon() ) {
258 'wl_user' => $user->getId(),
259 'wl_namespace' => $target->getNamespace(),
260 'wl_title' => $target->getDBkey(),
261 'wl_notificationtimestamp' => null,
263 $this->uncache( $user, $target );
270 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
271 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
272 // Use INSERT IGNORE to avoid overwriting the notification timestamp
273 // if there's already an entry for this page
274 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
276 $this->loadBalancer
->reuseConnection( $dbw );
282 * Removes the an entry for the User watching the LinkTarget
283 * Must be called separately for Subject & Talk namespaces
286 * @param LinkTarget $target
288 * @return bool success
289 * @throws DBUnexpectedError
290 * @throws MWException
292 public function removeWatch( User
$user, LinkTarget
$target ) {
293 // Only logged in user can have a watchlist
294 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
298 $this->uncache( $user, $target );
300 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
301 $dbw->delete( 'watchlist',
303 'wl_user' => $user->getId(),
304 'wl_namespace' => $target->getNamespace(),
305 'wl_title' => $target->getDBkey(),
308 $success = (bool)$dbw->affectedRows();
309 $this->loadBalancer
->reuseConnection( $dbw );
315 * @param User $editor The editor that triggered the update. Their notification
316 * timestamp will not be updated(they have already seen it)
317 * @param LinkTarget $target The target to update timestamps for
318 * @param string $timestamp Set the update timestamp to this value
320 * @return int[] Array of user IDs the timestamp has been updated for
322 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
323 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
324 $res = $dbw->select( [ 'watchlist' ],
327 'wl_user != ' . intval( $editor->getId() ),
328 'wl_namespace' => $target->getNamespace(),
329 'wl_title' => $target->getDBkey(),
330 'wl_notificationtimestamp IS NULL',
335 foreach ( $res as $row ) {
336 $watchers[] = intval( $row->wl_user
);
340 // Update wl_notificationtimestamp for all watching users except the editor
342 $dbw->onTransactionIdle(
343 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
344 $dbw->update( 'watchlist',
346 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
348 'wl_user' => $watchers,
349 'wl_namespace' => $target->getNamespace(),
350 'wl_title' => $target->getDBkey(),
357 $this->loadBalancer
->reuseConnection( $dbw );
363 * Reset the notification timestamp of this entry
366 * @param Title $title
367 * @param string $force Whether to force the write query to be executed even if the
368 * page is not watched or the notification timestamp is already NULL.
369 * 'force' in order to force
370 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
372 * @return bool success
374 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
375 // Only loggedin user can have a watchlist
376 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
381 if ( $force != 'force' ) {
382 $item = $this->loadWatchedItem( $user, $title );
383 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
388 // If the page is watched by the user (or may be watched), update the timestamp
389 $job = new ActivityUpdateJob(
392 'type' => 'updateWatchlistNotification',
393 'userid' => $user->getId(),
394 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
399 // Try to run this post-send
400 // Calls DeferredUpdates::addCallableUpdate in normal operation
402 $this->deferredUpdatesAddCallableUpdateCallback
,
403 function() use ( $job ) {
408 $this->uncache( $user, $title );
413 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
415 // No oldid given, assuming latest revision; clear the timestamp.
419 if ( !$title->getNextRevisionID( $oldid ) ) {
420 // Oldid given and is the latest revision for this title; clear the timestamp.
424 if ( $item === null ) {
425 $item = $this->loadWatchedItem( $user, $title );
429 // This can only happen if $force is enabled.
433 // Oldid given and isn't the latest; update the timestamp.
434 // This will result in no further notification emails being sent!
435 // Calls Revision::getTimestampFromId in normal operation
436 $notificationTimestamp = call_user_func(
437 $this->revisionGetTimestampFromIdCallback
,
442 // We need to go one second to the future because of various strict comparisons
443 // throughout the codebase
444 $ts = new MWTimestamp( $notificationTimestamp );
445 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
446 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
448 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
449 if ( $force != 'force' ) {
452 // This is a little silly…
453 return $item->getNotificationTimestamp();
457 return $notificationTimestamp;
461 * Check if the given title already is watched by the user, and if so
462 * add a watch for the new title.
464 * To be used for page renames and such.
466 * @param LinkTarget $oldTarget
467 * @param LinkTarget $newTarget
469 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
470 if ( !$oldTarget instanceof Title
) {
471 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
473 if ( !$newTarget instanceof Title
) {
474 $newTarget = Title
::newFromLinkTarget( $newTarget );
477 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
478 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
482 * Check if the given title already is watched by the user, and if so
483 * add a watch for the new title.
485 * To be used for page renames and such.
486 * This must be called separately for Subject and Talk pages
488 * @param LinkTarget $oldTarget
489 * @param LinkTarget $newTarget
491 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
492 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
494 $result = $dbw->select(
496 [ 'wl_user', 'wl_notificationtimestamp' ],
498 'wl_namespace' => $oldTarget->getNamespace(),
499 'wl_title' => $oldTarget->getDBkey(),
505 $newNamespace = $newTarget->getNamespace();
506 $newDBkey = $newTarget->getDBkey();
508 # Construct array to replace into the watchlist
510 foreach ( $result as $row ) {
512 'wl_user' => $row->wl_user
,
513 'wl_namespace' => $newNamespace,
514 'wl_title' => $newDBkey,
515 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
519 if ( !empty( $values ) ) {
521 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
522 # some other DBMSes, mostly due to poor simulation by us
525 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
531 $this->loadBalancer
->reuseConnection( $dbw );