Merge "Move WatchedItem logic to WatchedItemStore"
[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 BagOStuff
22 */
23 private $cache;
24
25 /**
26 * @var callable|null
27 */
28 private $deferredUpdatesAddCallableUpdateCallback;
29
30 /**
31 * @var callable|null
32 */
33 private $revisionGetTimestampFromIdCallback;
34
35 /**
36 * @var self|null
37 */
38 private static $instance;
39
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' ];
45 }
46
47 /**
48 * Overrides the DeferredUpdates::addCallableUpdate callback
49 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
50 *
51 * @param callable $callback
52 * @see DeferredUpdates::addCallableUpdate for callback signiture
53 *
54 * @throws MWException
55 */
56 public function overrideDeferredUpdatesAddCallableUpdateCallback( $callback ) {
57 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
58 throw new MWException(
59 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
60 );
61 }
62 Assert::parameterType( 'callable', $callback, '$callback' );
63 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
64 }
65
66 /**
67 * Overrides the Revision::getTimestampFromId callback
68 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
69 *
70 * @param callable $callback
71 * @see Revision::getTimestampFromId for callback signiture
72 *
73 * @throws MWException
74 */
75 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
76 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
77 throw new MWException(
78 'Cannot override Revision::getTimestampFromId callback in operation.'
79 );
80 }
81 Assert::parameterType( 'callable', $callback, '$callback' );
82 $this->revisionGetTimestampFromIdCallback = $callback;
83 }
84
85 /**
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.
88 *
89 * @param WatchedItemStore $store
90 *
91 * @throws MWException
92 */
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.'
97 );
98 }
99 self::$instance = $store;
100 }
101
102 /**
103 * @return self
104 */
105 public static function getDefaultInstance() {
106 if ( !self::$instance ) {
107 self::$instance = new self(
108 wfGetLB(),
109 new HashBagOStuff( [ 'maxKeys' => 100 ] )
110 );
111 }
112 return self::$instance;
113 }
114
115 private function getCacheKey( User $user, LinkTarget $target ) {
116 return $this->cache->makeKey(
117 (string)$target->getNamespace(),
118 $target->getDBkey(),
119 (string)$user->getId()
120 );
121 }
122
123 private function cache( WatchedItem $item ) {
124 $this->cache->set(
125 $this->getCacheKey( $item->getUser(), $item->getLinkTarget() ),
126 $item
127 );
128 }
129
130 private function uncache( User $user, LinkTarget $target ) {
131 $this->cache->delete( $this->getCacheKey( $user, $target ) );
132 }
133
134 /**
135 * @param User $user
136 * @param LinkTarget $target
137 *
138 * @return WatchedItem|null
139 */
140 private function getCached( User $user, LinkTarget $target ) {
141 return $this->cache->get( $this->getCacheKey( $user, $target ) );
142 }
143
144 /**
145 * Return an array of conditions to select or update the appropriate database
146 * row.
147 *
148 * @param User $user
149 * @param LinkTarget $target
150 *
151 * @return array
152 */
153 private function dbCond( User $user, LinkTarget $target ) {
154 return [
155 'wl_user' => $user->getId(),
156 'wl_namespace' => $target->getNamespace(),
157 'wl_title' => $target->getDBkey(),
158 ];
159 }
160
161 /**
162 * Get an item (may be cached)
163 *
164 * @param User $user
165 * @param LinkTarget $target
166 *
167 * @return WatchedItem|false
168 */
169 public function getWatchedItem( User $user, LinkTarget $target ) {
170 $cached = $this->getCached( $user, $target );
171 if ( $cached ) {
172 return $cached;
173 }
174 return $this->loadWatchedItem( $user, $target );
175 }
176
177 /**
178 * Loads an item from the db
179 *
180 * @param User $user
181 * @param LinkTarget $target
182 *
183 * @return WatchedItem|false
184 */
185 public function loadWatchedItem( User $user, LinkTarget $target ) {
186 // Only loggedin user can have a watchlist
187 if ( $user->isAnon() ) {
188 return false;
189 }
190
191 $dbr = $this->loadBalancer->getConnection( DB_SLAVE, [ 'watchlist' ] );
192 $row = $dbr->selectRow(
193 'watchlist',
194 'wl_notificationtimestamp',
195 $this->dbCond( $user, $target ),
196 __METHOD__
197 );
198 $this->loadBalancer->reuseConnection( $dbr );
199
200 if ( !$row ) {
201 return false;
202 }
203
204 $item = new WatchedItem(
205 $user,
206 $target,
207 $row->wl_notificationtimestamp
208 );
209 $this->cache( $item );
210
211 return $item;
212 }
213
214 /**
215 * Must be called separately for Subject & Talk namespaces
216 *
217 * @param User $user
218 * @param LinkTarget $target
219 *
220 * @return bool
221 */
222 public function isWatched( User $user, LinkTarget $target ) {
223 return (bool)$this->getWatchedItem( $user, $target );
224 }
225
226 /**
227 * Must be called separately for Subject & Talk namespaces
228 *
229 * @param User $user
230 * @param LinkTarget $target
231 */
232 public function addWatch( User $user, LinkTarget $target ) {
233 $this->addWatchBatch( [ [ $user, $target ] ] );
234 }
235
236 /**
237 * @param array[] $userTargetCombinations array of arrays containing [0] => User [1] => LinkTarget
238 *
239 * @return bool success
240 */
241 public function addWatchBatch( array $userTargetCombinations ) {
242 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
243 return false;
244 }
245
246 $rows = [];
247 foreach ( $userTargetCombinations as list( $user, $target ) ) {
248 /**
249 * @var User $user
250 * @var LinkTarget $target
251 */
252
253 // Only loggedin user can have a watchlist
254 if ( $user->isAnon() ) {
255 continue;
256 }
257 $rows[] = [
258 'wl_user' => $user->getId(),
259 'wl_namespace' => $target->getNamespace(),
260 'wl_title' => $target->getDBkey(),
261 'wl_notificationtimestamp' => null,
262 ];
263 $this->uncache( $user, $target );
264 }
265
266 if ( !$rows ) {
267 return false;
268 }
269
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' );
275 }
276 $this->loadBalancer->reuseConnection( $dbw );
277
278 return true;
279 }
280
281 /**
282 * Removes the an entry for the User watching the LinkTarget
283 * Must be called separately for Subject & Talk namespaces
284 *
285 * @param User $user
286 * @param LinkTarget $target
287 *
288 * @return bool success
289 * @throws DBUnexpectedError
290 * @throws MWException
291 */
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() ) {
295 return false;
296 }
297
298 $this->uncache( $user, $target );
299
300 $dbw = $this->loadBalancer->getConnection( DB_MASTER, [ 'watchlist' ] );
301 $dbw->delete( 'watchlist',
302 [
303 'wl_user' => $user->getId(),
304 'wl_namespace' => $target->getNamespace(),
305 'wl_title' => $target->getDBkey(),
306 ], __METHOD__
307 );
308 $success = (bool)$dbw->affectedRows();
309 $this->loadBalancer->reuseConnection( $dbw );
310
311 return $success;
312 }
313
314 /**
315 * Reset the notification timestamp of this entry
316 *
317 * @param User $user
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.
323 *
324 * @return bool success
325 */
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() ) {
329 return false;
330 }
331
332 $item = null;
333 if ( $force != 'force' ) {
334 $item = $this->loadWatchedItem( $user, $title );
335 if ( !$item || $item->getNotificationTimestamp() === null ) {
336 return false;
337 }
338 }
339
340 // If the page is watched by the user (or may be watched), update the timestamp
341 $job = new ActivityUpdateJob(
342 $title,
343 [
344 'type' => 'updateWatchlistNotification',
345 'userid' => $user->getId(),
346 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
347 'curTime' => time()
348 ]
349 );
350
351 // Try to run this post-send
352 // Calls DeferredUpdates::addCallableUpdate in normal operation
353 call_user_func(
354 $this->deferredUpdatesAddCallableUpdateCallback,
355 function() use ( $job ) {
356 $job->run();
357 }
358 );
359
360 $this->uncache( $user, $title );
361
362 return true;
363 }
364
365 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
366 if ( !$oldid ) {
367 // No oldid given, assuming latest revision; clear the timestamp.
368 return null;
369 }
370
371 if ( !$title->getNextRevisionID( $oldid ) ) {
372 // Oldid given and is the latest revision for this title; clear the timestamp.
373 return null;
374 }
375
376 if ( $item === null ) {
377 $item = $this->loadWatchedItem( $user, $title );
378 }
379
380 if ( !$item ) {
381 // This can only happen if $force is enabled.
382 return null;
383 }
384
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,
390 $title,
391 $oldid
392 );
393
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 );
399
400 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
401 if ( $force != 'force' ) {
402 return false;
403 } else {
404 // This is a little silly…
405 return $item->getNotificationTimestamp();
406 }
407 }
408
409 return $notificationTimestamp;
410 }
411
412 /**
413 * Check if the given title already is watched by the user, and if so
414 * add a watch for the new title.
415 *
416 * To be used for page renames and such.
417 *
418 * @param LinkTarget $oldTarget
419 * @param LinkTarget $newTarget
420 */
421 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
422 if ( !$oldTarget instanceof Title ) {
423 $oldTarget = Title::newFromLinkTarget( $oldTarget );
424 }
425 if ( !$newTarget instanceof Title ) {
426 $newTarget = Title::newFromLinkTarget( $newTarget );
427 }
428
429 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
430 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
431 }
432
433 /**
434 * Check if the given title already is watched by the user, and if so
435 * add a watch for the new title.
436 *
437 * To be used for page renames and such.
438 * This must be called separately for Subject and Talk pages
439 *
440 * @param LinkTarget $oldTarget
441 * @param LinkTarget $newTarget
442 */
443 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
444 $dbw = $this->loadBalancer->getConnection( DB_MASTER, [ 'watchlist' ] );
445
446 $result = $dbw->select(
447 'watchlist',
448 [ 'wl_user', 'wl_notificationtimestamp' ],
449 [
450 'wl_namespace' => $oldTarget->getNamespace(),
451 'wl_title' => $oldTarget->getDBkey(),
452 ],
453 __METHOD__,
454 [ 'FOR UPDATE' ]
455 );
456
457 $newNamespace = $newTarget->getNamespace();
458 $newDBkey = $newTarget->getDBkey();
459
460 # Construct array to replace into the watchlist
461 $values = [];
462 foreach ( $result as $row ) {
463 $values[] = [
464 'wl_user' => $row->wl_user,
465 'wl_namespace' => $newNamespace,
466 'wl_title' => $newDBkey,
467 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
468 ];
469 }
470
471 if ( !empty( $values ) ) {
472 # Perform replace
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
475 $dbw->replace(
476 'watchlist',
477 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
478 $values,
479 __METHOD__
480 );
481 }
482
483 $this->loadBalancer->reuseConnection( $dbw );
484 }
485
486 }