Merge "Increase Opera minimum for Grades A and C to 15"
[lhc/web/wiklou.git] / includes / watcheditem / WatchedItemStore.php
1 <?php
2
3 use Wikimedia\Rdbms\IDatabase;
4 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
5 use MediaWiki\Linker\LinkTarget;
6 use MediaWiki\MediaWikiServices;
7 use Wikimedia\Assert\Assert;
8 use Wikimedia\ScopedCallback;
9 use Wikimedia\Rdbms\LoadBalancer;
10
11 /**
12 * Storage layer class for WatchedItems.
13 * Database interaction & caching
14 * TODO caching should be factored out into a CachingWatchedItemStore class
15 *
16 * Uses database because this uses User::isAnon
17 *
18 * @group Database
19 *
20 * @author Addshore
21 * @since 1.27
22 */
23 class WatchedItemStore implements WatchedItemStoreInterface, StatsdAwareInterface {
24
25 /**
26 * @var LoadBalancer
27 */
28 private $loadBalancer;
29
30 /**
31 * @var ReadOnlyMode
32 */
33 private $readOnlyMode;
34
35 /**
36 * @var HashBagOStuff
37 */
38 private $cache;
39
40 /**
41 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
42 * The index is needed so that on mass changes all relevant items can be un-cached.
43 * For example: Clearing a users watchlist of all items or updating notification timestamps
44 * for all users watching a single target.
45 */
46 private $cacheIndex = [];
47
48 /**
49 * @var callable|null
50 */
51 private $deferredUpdatesAddCallableUpdateCallback;
52
53 /**
54 * @var callable|null
55 */
56 private $revisionGetTimestampFromIdCallback;
57
58 /**
59 * @var StatsdDataFactoryInterface
60 */
61 private $stats;
62
63 /**
64 * @param LoadBalancer $loadBalancer
65 * @param HashBagOStuff $cache
66 * @param ReadOnlyMode $readOnlyMode
67 */
68 public function __construct(
69 LoadBalancer $loadBalancer,
70 HashBagOStuff $cache,
71 ReadOnlyMode $readOnlyMode
72 ) {
73 $this->loadBalancer = $loadBalancer;
74 $this->cache = $cache;
75 $this->readOnlyMode = $readOnlyMode;
76 $this->stats = new NullStatsdDataFactory();
77 $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
78 $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
79 }
80
81 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
82 $this->stats = $stats;
83 }
84
85 /**
86 * Overrides the DeferredUpdates::addCallableUpdate callback
87 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
88 *
89 * @param callable $callback
90 *
91 * @see DeferredUpdates::addCallableUpdate for callback signiture
92 *
93 * @return ScopedCallback to reset the overridden value
94 * @throws MWException
95 */
96 public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
97 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
98 throw new MWException(
99 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
100 );
101 }
102 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback;
103 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
104 return new ScopedCallback( function () use ( $previousValue ) {
105 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
106 } );
107 }
108
109 /**
110 * Overrides the Revision::getTimestampFromId callback
111 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
112 *
113 * @param callable $callback
114 * @see Revision::getTimestampFromId for callback signiture
115 *
116 * @return ScopedCallback to reset the overridden value
117 * @throws MWException
118 */
119 public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
120 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
121 throw new MWException(
122 'Cannot override Revision::getTimestampFromId callback in operation.'
123 );
124 }
125 $previousValue = $this->revisionGetTimestampFromIdCallback;
126 $this->revisionGetTimestampFromIdCallback = $callback;
127 return new ScopedCallback( function () use ( $previousValue ) {
128 $this->revisionGetTimestampFromIdCallback = $previousValue;
129 } );
130 }
131
132 private function getCacheKey( User $user, LinkTarget $target ) {
133 return $this->cache->makeKey(
134 (string)$target->getNamespace(),
135 $target->getDBkey(),
136 (string)$user->getId()
137 );
138 }
139
140 private function cache( WatchedItem $item ) {
141 $user = $item->getUser();
142 $target = $item->getLinkTarget();
143 $key = $this->getCacheKey( $user, $target );
144 $this->cache->set( $key, $item );
145 $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
146 $this->stats->increment( 'WatchedItemStore.cache' );
147 }
148
149 private function uncache( User $user, LinkTarget $target ) {
150 $this->cache->delete( $this->getCacheKey( $user, $target ) );
151 unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
152 $this->stats->increment( 'WatchedItemStore.uncache' );
153 }
154
155 private function uncacheLinkTarget( LinkTarget $target ) {
156 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
157 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
158 return;
159 }
160 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
161 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
162 $this->cache->delete( $key );
163 }
164 }
165
166 private function uncacheUser( User $user ) {
167 $this->stats->increment( 'WatchedItemStore.uncacheUser' );
168 foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
169 foreach ( $dbKeyArray as $dbKey => $userArray ) {
170 if ( isset( $userArray[$user->getId()] ) ) {
171 $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
172 $this->cache->delete( $userArray[$user->getId()] );
173 }
174 }
175 }
176 }
177
178 /**
179 * @param User $user
180 * @param LinkTarget $target
181 *
182 * @return WatchedItem|false
183 */
184 private function getCached( User $user, LinkTarget $target ) {
185 return $this->cache->get( $this->getCacheKey( $user, $target ) );
186 }
187
188 /**
189 * Return an array of conditions to select or update the appropriate database
190 * row.
191 *
192 * @param User $user
193 * @param LinkTarget $target
194 *
195 * @return array
196 */
197 private function dbCond( User $user, LinkTarget $target ) {
198 return [
199 'wl_user' => $user->getId(),
200 'wl_namespace' => $target->getNamespace(),
201 'wl_title' => $target->getDBkey(),
202 ];
203 }
204
205 /**
206 * @param int $dbIndex DB_MASTER or DB_REPLICA
207 *
208 * @return IDatabase
209 * @throws MWException
210 */
211 private function getConnectionRef( $dbIndex ) {
212 return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
213 }
214
215 /**
216 * Queues a job that will clear the users watchlist using the Job Queue.
217 *
218 * @since 1.31
219 *
220 * @param User $user
221 */
222 public function clearUserWatchedItemsUsingJobQueue( User $user ) {
223 $job = ClearUserWatchlistJob::newForUser( $user, $this->getMaxId() );
224 // TODO inject me.
225 JobQueueGroup::singleton()->push( $job );
226 }
227
228 /**
229 * @since 1.31
230 * @return int The maximum current wl_id
231 */
232 public function getMaxId() {
233 $dbr = $this->getConnectionRef( DB_REPLICA );
234 return (int)$dbr->selectField(
235 'watchlist',
236 'MAX(wl_id)',
237 '',
238 __METHOD__
239 );
240 }
241
242 /**
243 * @since 1.31
244 */
245 public function countWatchedItems( User $user ) {
246 $dbr = $this->getConnectionRef( DB_REPLICA );
247 $return = (int)$dbr->selectField(
248 'watchlist',
249 'COUNT(*)',
250 [
251 'wl_user' => $user->getId()
252 ],
253 __METHOD__
254 );
255
256 return $return;
257 }
258
259 /**
260 * @since 1.27
261 */
262 public function countWatchers( LinkTarget $target ) {
263 $dbr = $this->getConnectionRef( DB_REPLICA );
264 $return = (int)$dbr->selectField(
265 'watchlist',
266 'COUNT(*)',
267 [
268 'wl_namespace' => $target->getNamespace(),
269 'wl_title' => $target->getDBkey(),
270 ],
271 __METHOD__
272 );
273
274 return $return;
275 }
276
277 /**
278 * @since 1.27
279 */
280 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
281 $dbr = $this->getConnectionRef( DB_REPLICA );
282 $visitingWatchers = (int)$dbr->selectField(
283 'watchlist',
284 'COUNT(*)',
285 [
286 'wl_namespace' => $target->getNamespace(),
287 'wl_title' => $target->getDBkey(),
288 'wl_notificationtimestamp >= ' .
289 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
290 ' OR wl_notificationtimestamp IS NULL'
291 ],
292 __METHOD__
293 );
294
295 return $visitingWatchers;
296 }
297
298 /**
299 * @since 1.27
300 */
301 public function countWatchersMultiple( array $targets, array $options = [] ) {
302 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
303
304 $dbr = $this->getConnectionRef( DB_REPLICA );
305
306 if ( array_key_exists( 'minimumWatchers', $options ) ) {
307 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
308 }
309
310 $lb = new LinkBatch( $targets );
311 $res = $dbr->select(
312 'watchlist',
313 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
314 [ $lb->constructSet( 'wl', $dbr ) ],
315 __METHOD__,
316 $dbOptions
317 );
318
319 $watchCounts = [];
320 foreach ( $targets as $linkTarget ) {
321 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
322 }
323
324 foreach ( $res as $row ) {
325 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
326 }
327
328 return $watchCounts;
329 }
330
331 /**
332 * @since 1.27
333 */
334 public function countVisitingWatchersMultiple(
335 array $targetsWithVisitThresholds,
336 $minimumWatchers = null
337 ) {
338 $dbr = $this->getConnectionRef( DB_REPLICA );
339
340 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
341
342 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
343 if ( $minimumWatchers !== null ) {
344 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
345 }
346 $res = $dbr->select(
347 'watchlist',
348 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
349 $conds,
350 __METHOD__,
351 $dbOptions
352 );
353
354 $watcherCounts = [];
355 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
356 /* @var LinkTarget $target */
357 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
358 }
359
360 foreach ( $res as $row ) {
361 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
362 }
363
364 return $watcherCounts;
365 }
366
367 /**
368 * Generates condition for the query used in a batch count visiting watchers.
369 *
370 * @param IDatabase $db
371 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
372 * @return string
373 */
374 private function getVisitingWatchersCondition(
375 IDatabase $db,
376 array $targetsWithVisitThresholds
377 ) {
378 $missingTargets = [];
379 $namespaceConds = [];
380 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
381 if ( $threshold === null ) {
382 $missingTargets[] = $target;
383 continue;
384 }
385 /* @var LinkTarget $target */
386 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
387 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
388 $db->makeList( [
389 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
390 'wl_notificationtimestamp IS NULL'
391 ], LIST_OR )
392 ], LIST_AND );
393 }
394
395 $conds = [];
396 foreach ( $namespaceConds as $namespace => $pageConds ) {
397 $conds[] = $db->makeList( [
398 'wl_namespace = ' . $namespace,
399 '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
400 ], LIST_AND );
401 }
402
403 if ( $missingTargets ) {
404 $lb = new LinkBatch( $missingTargets );
405 $conds[] = $lb->constructSet( 'wl', $db );
406 }
407
408 return $db->makeList( $conds, LIST_OR );
409 }
410
411 /**
412 * @since 1.27
413 */
414 public function getWatchedItem( User $user, LinkTarget $target ) {
415 if ( $user->isAnon() ) {
416 return false;
417 }
418
419 $cached = $this->getCached( $user, $target );
420 if ( $cached ) {
421 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
422 return $cached;
423 }
424 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
425 return $this->loadWatchedItem( $user, $target );
426 }
427
428 /**
429 * @since 1.27
430 */
431 public function loadWatchedItem( User $user, LinkTarget $target ) {
432 // Only loggedin user can have a watchlist
433 if ( $user->isAnon() ) {
434 return false;
435 }
436
437 $dbr = $this->getConnectionRef( DB_REPLICA );
438 $row = $dbr->selectRow(
439 'watchlist',
440 'wl_notificationtimestamp',
441 $this->dbCond( $user, $target ),
442 __METHOD__
443 );
444
445 if ( !$row ) {
446 return false;
447 }
448
449 $item = new WatchedItem(
450 $user,
451 $target,
452 wfTimestampOrNull( TS_MW, $row->wl_notificationtimestamp )
453 );
454 $this->cache( $item );
455
456 return $item;
457 }
458
459 /**
460 * @since 1.27
461 */
462 public function getWatchedItemsForUser( User $user, array $options = [] ) {
463 $options += [ 'forWrite' => false ];
464
465 $dbOptions = [];
466 if ( array_key_exists( 'sort', $options ) ) {
467 Assert::parameter(
468 ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
469 '$options[\'sort\']',
470 'must be SORT_ASC or SORT_DESC'
471 );
472 $dbOptions['ORDER BY'] = [
473 "wl_namespace {$options['sort']}",
474 "wl_title {$options['sort']}"
475 ];
476 }
477 $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
478
479 $res = $db->select(
480 'watchlist',
481 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
482 [ 'wl_user' => $user->getId() ],
483 __METHOD__,
484 $dbOptions
485 );
486
487 $watchedItems = [];
488 foreach ( $res as $row ) {
489 // @todo: Should we add these to the process cache?
490 $watchedItems[] = new WatchedItem(
491 $user,
492 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
493 $row->wl_notificationtimestamp
494 );
495 }
496
497 return $watchedItems;
498 }
499
500 /**
501 * @since 1.27
502 */
503 public function isWatched( User $user, LinkTarget $target ) {
504 return (bool)$this->getWatchedItem( $user, $target );
505 }
506
507 /**
508 * @since 1.27
509 */
510 public function getNotificationTimestampsBatch( User $user, array $targets ) {
511 $timestamps = [];
512 foreach ( $targets as $target ) {
513 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
514 }
515
516 if ( $user->isAnon() ) {
517 return $timestamps;
518 }
519
520 $targetsToLoad = [];
521 foreach ( $targets as $target ) {
522 $cachedItem = $this->getCached( $user, $target );
523 if ( $cachedItem ) {
524 $timestamps[$target->getNamespace()][$target->getDBkey()] =
525 $cachedItem->getNotificationTimestamp();
526 } else {
527 $targetsToLoad[] = $target;
528 }
529 }
530
531 if ( !$targetsToLoad ) {
532 return $timestamps;
533 }
534
535 $dbr = $this->getConnectionRef( DB_REPLICA );
536
537 $lb = new LinkBatch( $targetsToLoad );
538 $res = $dbr->select(
539 'watchlist',
540 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
541 [
542 $lb->constructSet( 'wl', $dbr ),
543 'wl_user' => $user->getId(),
544 ],
545 __METHOD__
546 );
547
548 foreach ( $res as $row ) {
549 $timestamps[$row->wl_namespace][$row->wl_title] =
550 wfTimestampOrNull( TS_MW, $row->wl_notificationtimestamp );
551 }
552
553 return $timestamps;
554 }
555
556 /**
557 * @since 1.27
558 */
559 public function addWatch( User $user, LinkTarget $target ) {
560 $this->addWatchBatchForUser( $user, [ $target ] );
561 }
562
563 /**
564 * @since 1.27
565 */
566 public function addWatchBatchForUser( User $user, array $targets ) {
567 if ( $this->readOnlyMode->isReadOnly() ) {
568 return false;
569 }
570 // Only loggedin user can have a watchlist
571 if ( $user->isAnon() ) {
572 return false;
573 }
574
575 if ( !$targets ) {
576 return true;
577 }
578
579 $rows = [];
580 $items = [];
581 foreach ( $targets as $target ) {
582 $rows[] = [
583 'wl_user' => $user->getId(),
584 'wl_namespace' => $target->getNamespace(),
585 'wl_title' => $target->getDBkey(),
586 'wl_notificationtimestamp' => null,
587 ];
588 $items[] = new WatchedItem(
589 $user,
590 $target,
591 null
592 );
593 $this->uncache( $user, $target );
594 }
595
596 $dbw = $this->getConnectionRef( DB_MASTER );
597 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
598 // Use INSERT IGNORE to avoid overwriting the notification timestamp
599 // if there's already an entry for this page
600 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
601 }
602 // Update process cache to ensure skin doesn't claim that the current
603 // page is unwatched in the response of action=watch itself (T28292).
604 // This would otherwise be re-queried from a slave by isWatched().
605 foreach ( $items as $item ) {
606 $this->cache( $item );
607 }
608
609 return true;
610 }
611
612 /**
613 * @since 1.27
614 */
615 public function removeWatch( User $user, LinkTarget $target ) {
616 // Only logged in user can have a watchlist
617 if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
618 return false;
619 }
620
621 $this->uncache( $user, $target );
622
623 $dbw = $this->getConnectionRef( DB_MASTER );
624 $dbw->delete( 'watchlist',
625 [
626 'wl_user' => $user->getId(),
627 'wl_namespace' => $target->getNamespace(),
628 'wl_title' => $target->getDBkey(),
629 ], __METHOD__
630 );
631 $success = (bool)$dbw->affectedRows();
632
633 return $success;
634 }
635
636 /**
637 * @since 1.27
638 */
639 public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
640 // Only loggedin user can have a watchlist
641 if ( $user->isAnon() ) {
642 return false;
643 }
644
645 $dbw = $this->getConnectionRef( DB_MASTER );
646
647 $conds = [ 'wl_user' => $user->getId() ];
648 if ( $targets ) {
649 $batch = new LinkBatch( $targets );
650 $conds[] = $batch->constructSet( 'wl', $dbw );
651 }
652
653 if ( $timestamp !== null ) {
654 $timestamp = $dbw->timestamp( $timestamp );
655 }
656
657 $success = $dbw->update(
658 'watchlist',
659 [ 'wl_notificationtimestamp' => $timestamp ],
660 $conds,
661 __METHOD__
662 );
663
664 $this->uncacheUser( $user );
665
666 return $success;
667 }
668
669 /**
670 * @since 1.27
671 */
672 public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
673 $dbw = $this->getConnectionRef( DB_MASTER );
674 $uids = $dbw->selectFieldValues(
675 'watchlist',
676 'wl_user',
677 [
678 'wl_user != ' . intval( $editor->getId() ),
679 'wl_namespace' => $target->getNamespace(),
680 'wl_title' => $target->getDBkey(),
681 'wl_notificationtimestamp IS NULL',
682 ],
683 __METHOD__
684 );
685
686 $watchers = array_map( 'intval', $uids );
687 if ( $watchers ) {
688 // Update wl_notificationtimestamp for all watching users except the editor
689 $fname = __METHOD__;
690 DeferredUpdates::addCallableUpdate(
691 function () use ( $timestamp, $watchers, $target, $fname ) {
692 global $wgUpdateRowsPerQuery;
693
694 $dbw = $this->getConnectionRef( DB_MASTER );
695 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
696 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
697
698 $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
699 foreach ( $watchersChunks as $watchersChunk ) {
700 $dbw->update( 'watchlist',
701 [ /* SET */
702 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
703 ], [ /* WHERE - TODO Use wl_id T130067 */
704 'wl_user' => $watchersChunk,
705 'wl_namespace' => $target->getNamespace(),
706 'wl_title' => $target->getDBkey(),
707 ], $fname
708 );
709 if ( count( $watchersChunks ) > 1 ) {
710 $factory->commitAndWaitForReplication(
711 __METHOD__, $ticket, [ 'domain' => $dbw->getDomainID() ]
712 );
713 }
714 }
715 $this->uncacheLinkTarget( $target );
716 },
717 DeferredUpdates::POSTSEND,
718 $dbw
719 );
720 }
721
722 return $watchers;
723 }
724
725 /**
726 * @since 1.27
727 */
728 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
729 // Only loggedin user can have a watchlist
730 if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
731 return false;
732 }
733
734 $item = null;
735 if ( $force != 'force' ) {
736 $item = $this->loadWatchedItem( $user, $title );
737 if ( !$item || $item->getNotificationTimestamp() === null ) {
738 return false;
739 }
740 }
741
742 // If the page is watched by the user (or may be watched), update the timestamp
743 $job = new ActivityUpdateJob(
744 $title,
745 [
746 'type' => 'updateWatchlistNotification',
747 'userid' => $user->getId(),
748 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
749 'curTime' => time()
750 ]
751 );
752
753 // Try to run this post-send
754 // Calls DeferredUpdates::addCallableUpdate in normal operation
755 call_user_func(
756 $this->deferredUpdatesAddCallableUpdateCallback,
757 function () use ( $job ) {
758 $job->run();
759 }
760 );
761
762 $this->uncache( $user, $title );
763
764 return true;
765 }
766
767 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
768 if ( !$oldid ) {
769 // No oldid given, assuming latest revision; clear the timestamp.
770 return null;
771 }
772
773 if ( !$title->getNextRevisionID( $oldid ) ) {
774 // Oldid given and is the latest revision for this title; clear the timestamp.
775 return null;
776 }
777
778 if ( $item === null ) {
779 $item = $this->loadWatchedItem( $user, $title );
780 }
781
782 if ( !$item ) {
783 // This can only happen if $force is enabled.
784 return null;
785 }
786
787 // Oldid given and isn't the latest; update the timestamp.
788 // This will result in no further notification emails being sent!
789 // Calls Revision::getTimestampFromId in normal operation
790 $notificationTimestamp = call_user_func(
791 $this->revisionGetTimestampFromIdCallback,
792 $title,
793 $oldid
794 );
795
796 // We need to go one second to the future because of various strict comparisons
797 // throughout the codebase
798 $ts = new MWTimestamp( $notificationTimestamp );
799 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
800 $notificationTimestamp = $ts->getTimestamp( TS_MW );
801
802 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
803 if ( $force != 'force' ) {
804 return false;
805 } else {
806 // This is a little silly…
807 return $item->getNotificationTimestamp();
808 }
809 }
810
811 return $notificationTimestamp;
812 }
813
814 /**
815 * @since 1.27
816 */
817 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
818 $queryOptions = [];
819 if ( $unreadLimit !== null ) {
820 $unreadLimit = (int)$unreadLimit;
821 $queryOptions['LIMIT'] = $unreadLimit;
822 }
823
824 $dbr = $this->getConnectionRef( DB_REPLICA );
825 $rowCount = $dbr->selectRowCount(
826 'watchlist',
827 '1',
828 [
829 'wl_user' => $user->getId(),
830 'wl_notificationtimestamp IS NOT NULL',
831 ],
832 __METHOD__,
833 $queryOptions
834 );
835
836 if ( !isset( $unreadLimit ) ) {
837 return $rowCount;
838 }
839
840 if ( $rowCount >= $unreadLimit ) {
841 return true;
842 }
843
844 return $rowCount;
845 }
846
847 /**
848 * @since 1.27
849 */
850 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
851 $oldTarget = Title::newFromLinkTarget( $oldTarget );
852 $newTarget = Title::newFromLinkTarget( $newTarget );
853
854 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
855 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
856 }
857
858 /**
859 * @since 1.27
860 */
861 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
862 $dbw = $this->getConnectionRef( DB_MASTER );
863
864 $result = $dbw->select(
865 'watchlist',
866 [ 'wl_user', 'wl_notificationtimestamp' ],
867 [
868 'wl_namespace' => $oldTarget->getNamespace(),
869 'wl_title' => $oldTarget->getDBkey(),
870 ],
871 __METHOD__,
872 [ 'FOR UPDATE' ]
873 );
874
875 $newNamespace = $newTarget->getNamespace();
876 $newDBkey = $newTarget->getDBkey();
877
878 # Construct array to replace into the watchlist
879 $values = [];
880 foreach ( $result as $row ) {
881 $values[] = [
882 'wl_user' => $row->wl_user,
883 'wl_namespace' => $newNamespace,
884 'wl_title' => $newDBkey,
885 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
886 ];
887 }
888
889 if ( !empty( $values ) ) {
890 # Perform replace
891 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
892 # some other DBMSes, mostly due to poor simulation by us
893 $dbw->replace(
894 'watchlist',
895 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
896 $values,
897 __METHOD__
898 );
899 }
900 }
901
902 }