Uncache things in WatchedItemStore::updateNotificationTimestamp
[lhc/web/wiklou.git] / includes / WatchedItemStore.php
1 <?php
2
3 use Wikimedia\Assert\Assert;
4
5 /**
6 * Storage layer class for WatchedItems.
7 * Database interaction.
8 *
9 * @author Addshore
10 *
11 * @since 1.27
12 */
13 class WatchedItemStore {
14
15 /**
16 * @var LoadBalancer
17 */
18 private $loadBalancer;
19
20 /**
21 * @var HashBagOStuff
22 */
23 private $cache;
24
25 /**
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.
30 */
31 private $cacheIndex = [];
32
33 /**
34 * @var callable|null
35 */
36 private $deferredUpdatesAddCallableUpdateCallback;
37
38 /**
39 * @var callable|null
40 */
41 private $revisionGetTimestampFromIdCallback;
42
43 /**
44 * @var self|null
45 */
46 private static $instance;
47
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' ];
53 }
54
55 /**
56 * Overrides the DeferredUpdates::addCallableUpdate callback
57 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
58 *
59 * @param callable $callback
60 * @see DeferredUpdates::addCallableUpdate for callback signiture
61 *
62 * @throws MWException
63 */
64 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
65 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
66 throw new MWException(
67 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
68 );
69 }
70 Assert::parameterType( 'callable', $callback, '$callback' );
71 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
72 }
73
74 /**
75 * Overrides the Revision::getTimestampFromId callback
76 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
77 *
78 * @param callable $callback
79 * @see Revision::getTimestampFromId for callback signiture
80 *
81 * @throws MWException
82 */
83 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
84 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
85 throw new MWException(
86 'Cannot override Revision::getTimestampFromId callback in operation.'
87 );
88 }
89 Assert::parameterType( 'callable', $callback, '$callback' );
90 $this->revisionGetTimestampFromIdCallback = $callback;
91 }
92
93 /**
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.
96 *
97 * @param WatchedItemStore $store
98 *
99 * @throws MWException
100 */
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.'
105 );
106 }
107 self::$instance = $store;
108 }
109
110 /**
111 * @return self
112 */
113 public static function getDefaultInstance() {
114 if ( !self::$instance ) {
115 self::$instance = new self(
116 wfGetLB(),
117 new HashBagOStuff( [ 'maxKeys' => 100 ] )
118 );
119 }
120 return self::$instance;
121 }
122
123 private function getCacheKey( User $user, LinkTarget $target ) {
124 return $this->cache->makeKey(
125 (string)$target->getNamespace(),
126 $target->getDBkey(),
127 (string)$user->getId()
128 );
129 }
130
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;
137 }
138
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()] );
142 }
143
144 private function uncacheLinkTarget( LinkTarget $target ) {
145 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
146 return;
147 }
148 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
149 $this->cache->delete( $key );
150 }
151 }
152
153 /**
154 * @param User $user
155 * @param LinkTarget $target
156 *
157 * @return WatchedItem|null
158 */
159 private function getCached( User $user, LinkTarget $target ) {
160 return $this->cache->get( $this->getCacheKey( $user, $target ) );
161 }
162
163 /**
164 * Return an array of conditions to select or update the appropriate database
165 * row.
166 *
167 * @param User $user
168 * @param LinkTarget $target
169 *
170 * @return array
171 */
172 private function dbCond( User $user, LinkTarget $target ) {
173 return [
174 'wl_user' => $user->getId(),
175 'wl_namespace' => $target->getNamespace(),
176 'wl_title' => $target->getDBkey(),
177 ];
178 }
179
180 /**
181 * Get an item (may be cached)
182 *
183 * @param User $user
184 * @param LinkTarget $target
185 *
186 * @return WatchedItem|false
187 */
188 public function getWatchedItem( User $user, LinkTarget $target ) {
189 $cached = $this->getCached( $user, $target );
190 if ( $cached ) {
191 return $cached;
192 }
193 return $this->loadWatchedItem( $user, $target );
194 }
195
196 /**
197 * Loads an item from the db
198 *
199 * @param User $user
200 * @param LinkTarget $target
201 *
202 * @return WatchedItem|false
203 */
204 public function loadWatchedItem( User $user, LinkTarget $target ) {
205 // Only loggedin user can have a watchlist
206 if ( $user->isAnon() ) {
207 return false;
208 }
209
210 $dbr = $this->loadBalancer->getConnection( DB_SLAVE, [ 'watchlist' ] );
211 $row = $dbr->selectRow(
212 'watchlist',
213 'wl_notificationtimestamp',
214 $this->dbCond( $user, $target ),
215 __METHOD__
216 );
217 $this->loadBalancer->reuseConnection( $dbr );
218
219 if ( !$row ) {
220 return false;
221 }
222
223 $item = new WatchedItem(
224 $user,
225 $target,
226 $row->wl_notificationtimestamp
227 );
228 $this->cache( $item );
229
230 return $item;
231 }
232
233 /**
234 * Must be called separately for Subject & Talk namespaces
235 *
236 * @param User $user
237 * @param LinkTarget $target
238 *
239 * @return bool
240 */
241 public function isWatched( User $user, LinkTarget $target ) {
242 return (bool)$this->getWatchedItem( $user, $target );
243 }
244
245 /**
246 * Must be called separately for Subject & Talk namespaces
247 *
248 * @param User $user
249 * @param LinkTarget $target
250 */
251 public function addWatch( User $user, LinkTarget $target ) {
252 $this->addWatchBatch( [ [ $user, $target ] ] );
253 }
254
255 /**
256 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
257 *
258 * @return bool success
259 */
260 public function addWatchBatch( array $userTargetCombinations ) {
261 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
262 return false;
263 }
264
265 $rows = [];
266 foreach ( $userTargetCombinations as list( $user, $target ) ) {
267 /**
268 * @var User $user
269 * @var LinkTarget $target
270 */
271
272 // Only loggedin user can have a watchlist
273 if ( $user->isAnon() ) {
274 continue;
275 }
276 $rows[] = [
277 'wl_user' => $user->getId(),
278 'wl_namespace' => $target->getNamespace(),
279 'wl_title' => $target->getDBkey(),
280 'wl_notificationtimestamp' => null,
281 ];
282 $this->uncache( $user, $target );
283 }
284
285 if ( !$rows ) {
286 return false;
287 }
288
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' );
294 }
295 $this->loadBalancer->reuseConnection( $dbw );
296
297 return true;
298 }
299
300 /**
301 * Removes the an entry for the User watching the LinkTarget
302 * Must be called separately for Subject & Talk namespaces
303 *
304 * @param User $user
305 * @param LinkTarget $target
306 *
307 * @return bool success
308 * @throws DBUnexpectedError
309 * @throws MWException
310 */
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() ) {
314 return false;
315 }
316
317 $this->uncache( $user, $target );
318
319 $dbw = $this->loadBalancer->getConnection( DB_MASTER, [ 'watchlist' ] );
320 $dbw->delete( 'watchlist',
321 [
322 'wl_user' => $user->getId(),
323 'wl_namespace' => $target->getNamespace(),
324 'wl_title' => $target->getDBkey(),
325 ], __METHOD__
326 );
327 $success = (bool)$dbw->affectedRows();
328 $this->loadBalancer->reuseConnection( $dbw );
329
330 return $success;
331 }
332
333 /**
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
338 *
339 * @return int[] Array of user IDs the timestamp has been updated for
340 */
341 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
342 $dbw = $this->loadBalancer->getConnection( DB_MASTER, [ 'watchlist' ] );
343 $res = $dbw->select( [ 'watchlist' ],
344 [ 'wl_user' ],
345 [
346 'wl_user != ' . intval( $editor->getId() ),
347 'wl_namespace' => $target->getNamespace(),
348 'wl_title' => $target->getDBkey(),
349 'wl_notificationtimestamp IS NULL',
350 ], __METHOD__
351 );
352
353 $watchers = [];
354 foreach ( $res as $row ) {
355 $watchers[] = intval( $row->wl_user );
356 }
357
358 if ( $watchers ) {
359 // Update wl_notificationtimestamp for all watching users except the editor
360 $fname = __METHOD__;
361 $dbw->onTransactionIdle(
362 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
363 $dbw->update( 'watchlist',
364 [ /* SET */
365 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
366 ], [ /* WHERE */
367 'wl_user' => $watchers,
368 'wl_namespace' => $target->getNamespace(),
369 'wl_title' => $target->getDBkey(),
370 ], $fname
371 );
372 $this->uncacheLinkTarget( $target );
373 }
374 );
375 }
376
377 $this->loadBalancer->reuseConnection( $dbw );
378
379 return $watchers;
380 }
381
382 /**
383 * Reset the notification timestamp of this entry
384 *
385 * @param User $user
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.
391 *
392 * @return bool success
393 */
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() ) {
397 return false;
398 }
399
400 $item = null;
401 if ( $force != 'force' ) {
402 $item = $this->loadWatchedItem( $user, $title );
403 if ( !$item || $item->getNotificationTimestamp() === null ) {
404 return false;
405 }
406 }
407
408 // If the page is watched by the user (or may be watched), update the timestamp
409 $job = new ActivityUpdateJob(
410 $title,
411 [
412 'type' => 'updateWatchlistNotification',
413 'userid' => $user->getId(),
414 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
415 'curTime' => time()
416 ]
417 );
418
419 // Try to run this post-send
420 // Calls DeferredUpdates::addCallableUpdate in normal operation
421 call_user_func(
422 $this->deferredUpdatesAddCallableUpdateCallback,
423 function() use ( $job ) {
424 $job->run();
425 }
426 );
427
428 $this->uncache( $user, $title );
429
430 return true;
431 }
432
433 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
434 if ( !$oldid ) {
435 // No oldid given, assuming latest revision; clear the timestamp.
436 return null;
437 }
438
439 if ( !$title->getNextRevisionID( $oldid ) ) {
440 // Oldid given and is the latest revision for this title; clear the timestamp.
441 return null;
442 }
443
444 if ( $item === null ) {
445 $item = $this->loadWatchedItem( $user, $title );
446 }
447
448 if ( !$item ) {
449 // This can only happen if $force is enabled.
450 return null;
451 }
452
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,
458 $title,
459 $oldid
460 );
461
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 );
467
468 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
469 if ( $force != 'force' ) {
470 return false;
471 } else {
472 // This is a little silly…
473 return $item->getNotificationTimestamp();
474 }
475 }
476
477 return $notificationTimestamp;
478 }
479
480 /**
481 * Check if the given title already is watched by the user, and if so
482 * add a watch for the new title.
483 *
484 * To be used for page renames and such.
485 *
486 * @param LinkTarget $oldTarget
487 * @param LinkTarget $newTarget
488 */
489 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
490 if ( !$oldTarget instanceof Title ) {
491 $oldTarget = Title::newFromLinkTarget( $oldTarget );
492 }
493 if ( !$newTarget instanceof Title ) {
494 $newTarget = Title::newFromLinkTarget( $newTarget );
495 }
496
497 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
498 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
499 }
500
501 /**
502 * Check if the given title already is watched by the user, and if so
503 * add a watch for the new title.
504 *
505 * To be used for page renames and such.
506 * This must be called separately for Subject and Talk pages
507 *
508 * @param LinkTarget $oldTarget
509 * @param LinkTarget $newTarget
510 */
511 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
512 $dbw = $this->loadBalancer->getConnection( DB_MASTER, [ 'watchlist' ] );
513
514 $result = $dbw->select(
515 'watchlist',
516 [ 'wl_user', 'wl_notificationtimestamp' ],
517 [
518 'wl_namespace' => $oldTarget->getNamespace(),
519 'wl_title' => $oldTarget->getDBkey(),
520 ],
521 __METHOD__,
522 [ 'FOR UPDATE' ]
523 );
524
525 $newNamespace = $newTarget->getNamespace();
526 $newDBkey = $newTarget->getDBkey();
527
528 # Construct array to replace into the watchlist
529 $values = [];
530 foreach ( $result as $row ) {
531 $values[] = [
532 'wl_user' => $row->wl_user,
533 'wl_namespace' => $newNamespace,
534 'wl_title' => $newDBkey,
535 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
536 ];
537 }
538
539 if ( !empty( $values ) ) {
540 # Perform replace
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
543 $dbw->replace(
544 'watchlist',
545 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
546 $values,
547 __METHOD__
548 );
549 }
550
551 $this->loadBalancer->reuseConnection( $dbw );
552 }
553
554 }