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 * Reset the notification timestamp of this entry
318 * @param Title $title
319 * @param string $force Whether to force the write query to be executed even if the
320 * page is not watched or the notification timestamp is already NULL.
321 * 'force' in order to force
322 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
324 * @return bool success
326 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
327 // Only loggedin user can have a watchlist
328 if ( $this->loadBalancer
->getReadOnlyReason() !== false ||
$user->isAnon() ) {
333 if ( $force != 'force' ) {
334 $item = $this->loadWatchedItem( $user, $title );
335 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
340 // If the page is watched by the user (or may be watched), update the timestamp
341 $job = new ActivityUpdateJob(
344 'type' => 'updateWatchlistNotification',
345 'userid' => $user->getId(),
346 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
351 // Try to run this post-send
352 // Calls DeferredUpdates::addCallableUpdate in normal operation
354 $this->deferredUpdatesAddCallableUpdateCallback
,
355 function() use ( $job ) {
360 $this->uncache( $user, $title );
365 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
367 // No oldid given, assuming latest revision; clear the timestamp.
371 if ( !$title->getNextRevisionID( $oldid ) ) {
372 // Oldid given and is the latest revision for this title; clear the timestamp.
376 if ( $item === null ) {
377 $item = $this->loadWatchedItem( $user, $title );
381 // This can only happen if $force is enabled.
385 // Oldid given and isn't the latest; update the timestamp.
386 // This will result in no further notification emails being sent!
387 // Calls Revision::getTimestampFromId in normal operation
388 $notificationTimestamp = call_user_func(
389 $this->revisionGetTimestampFromIdCallback
,
394 // We need to go one second to the future because of various strict comparisons
395 // throughout the codebase
396 $ts = new MWTimestamp( $notificationTimestamp );
397 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
398 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
400 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
401 if ( $force != 'force' ) {
404 // This is a little silly…
405 return $item->getNotificationTimestamp();
409 return $notificationTimestamp;
413 * Check if the given title already is watched by the user, and if so
414 * add a watch for the new title.
416 * To be used for page renames and such.
418 * @param LinkTarget $oldTarget
419 * @param LinkTarget $newTarget
421 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
422 if ( !$oldTarget instanceof Title
) {
423 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
425 if ( !$newTarget instanceof Title
) {
426 $newTarget = Title
::newFromLinkTarget( $newTarget );
429 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
430 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
434 * Check if the given title already is watched by the user, and if so
435 * add a watch for the new title.
437 * To be used for page renames and such.
438 * This must be called separately for Subject and Talk pages
440 * @param LinkTarget $oldTarget
441 * @param LinkTarget $newTarget
443 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
444 $dbw = $this->loadBalancer
->getConnection( DB_MASTER
, [ 'watchlist' ] );
446 $result = $dbw->select(
448 [ 'wl_user', 'wl_notificationtimestamp' ],
450 'wl_namespace' => $oldTarget->getNamespace(),
451 'wl_title' => $oldTarget->getDBkey(),
457 $newNamespace = $newTarget->getNamespace();
458 $newDBkey = $newTarget->getDBkey();
460 # Construct array to replace into the watchlist
462 foreach ( $result as $row ) {
464 'wl_user' => $row->wl_user
,
465 'wl_namespace' => $newNamespace,
466 'wl_title' => $newDBkey,
467 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
471 if ( !empty( $values ) ) {
473 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
474 # some other DBMSes, mostly due to poor simulation by us
477 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
483 $this->loadBalancer
->reuseConnection( $dbw );