3 use Wikimedia\Rdbms\IDatabase
;
4 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
5 use MediaWiki\Linker\LinkTarget
;
6 use Wikimedia\Assert\Assert
;
7 use Wikimedia\ScopedCallback
;
8 use Wikimedia\Rdbms\ILBFactory
;
9 use Wikimedia\Rdbms\LoadBalancer
;
12 * Storage layer class for WatchedItems.
13 * Database interaction & caching
14 * TODO caching should be factored out into a CachingWatchedItemStore class
19 class WatchedItemStore
implements WatchedItemStoreInterface
, StatsdAwareInterface
{
29 private $loadBalancer;
34 private $readOnlyMode;
42 * @var array[] Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key'
43 * The index is needed so that on mass changes all relevant items can be un-cached.
44 * For example: Clearing a users watchlist of all items or updating notification timestamps
45 * for all users watching a single target.
47 private $cacheIndex = [];
52 private $deferredUpdatesAddCallableUpdateCallback;
57 private $revisionGetTimestampFromIdCallback;
62 private $updateRowsPerQuery;
65 * @var StatsdDataFactoryInterface
70 * @param ILBFactory $lbFactory
71 * @param HashBagOStuff $cache
72 * @param ReadOnlyMode $readOnlyMode
73 * @param int $updateRowsPerQuery
75 public function __construct(
76 ILBFactory
$lbFactory,
78 ReadOnlyMode
$readOnlyMode,
81 $this->lbFactory
= $lbFactory;
82 $this->loadBalancer
= $lbFactory->getMainLB();
83 $this->cache
= $cache;
84 $this->readOnlyMode
= $readOnlyMode;
85 $this->stats
= new NullStatsdDataFactory();
86 $this->deferredUpdatesAddCallableUpdateCallback
=
87 [ DeferredUpdates
::class, 'addCallableUpdate' ];
88 $this->revisionGetTimestampFromIdCallback
=
89 [ Revision
::class, 'getTimestampFromId' ];
90 $this->updateRowsPerQuery
= $updateRowsPerQuery;
94 * @param StatsdDataFactoryInterface $stats
96 public function setStatsdDataFactory( StatsdDataFactoryInterface
$stats ) {
97 $this->stats
= $stats;
101 * Overrides the DeferredUpdates::addCallableUpdate callback
102 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
104 * @param callable $callback
106 * @see DeferredUpdates::addCallableUpdate for callback signiture
108 * @return ScopedCallback to reset the overridden value
109 * @throws MWException
111 public function overrideDeferredUpdatesAddCallableUpdateCallback( callable
$callback ) {
112 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
113 throw new MWException(
114 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
117 $previousValue = $this->deferredUpdatesAddCallableUpdateCallback
;
118 $this->deferredUpdatesAddCallableUpdateCallback
= $callback;
119 return new ScopedCallback( function () use ( $previousValue ) {
120 $this->deferredUpdatesAddCallableUpdateCallback
= $previousValue;
125 * Overrides the Revision::getTimestampFromId callback
126 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
128 * @param callable $callback
129 * @see Revision::getTimestampFromId for callback signiture
131 * @return ScopedCallback to reset the overridden value
132 * @throws MWException
134 public function overrideRevisionGetTimestampFromIdCallback( callable
$callback ) {
135 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
136 throw new MWException(
137 'Cannot override Revision::getTimestampFromId callback in operation.'
140 $previousValue = $this->revisionGetTimestampFromIdCallback
;
141 $this->revisionGetTimestampFromIdCallback
= $callback;
142 return new ScopedCallback( function () use ( $previousValue ) {
143 $this->revisionGetTimestampFromIdCallback
= $previousValue;
147 private function getCacheKey( User
$user, LinkTarget
$target ) {
148 return $this->cache
->makeKey(
149 (string)$target->getNamespace(),
151 (string)$user->getId()
155 private function cache( WatchedItem
$item ) {
156 $user = $item->getUser();
157 $target = $item->getLinkTarget();
158 $key = $this->getCacheKey( $user, $target );
159 $this->cache
->set( $key, $item );
160 $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
161 $this->stats
->increment( 'WatchedItemStore.cache' );
164 private function uncache( User
$user, LinkTarget
$target ) {
165 $this->cache
->delete( $this->getCacheKey( $user, $target ) );
166 unset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
167 $this->stats
->increment( 'WatchedItemStore.uncache' );
170 private function uncacheLinkTarget( LinkTarget
$target ) {
171 $this->stats
->increment( 'WatchedItemStore.uncacheLinkTarget' );
172 if ( !isset( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] ) ) {
175 foreach ( $this->cacheIndex
[$target->getNamespace()][$target->getDBkey()] as $key ) {
176 $this->stats
->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
177 $this->cache
->delete( $key );
181 private function uncacheUser( User
$user ) {
182 $this->stats
->increment( 'WatchedItemStore.uncacheUser' );
183 foreach ( $this->cacheIndex
as $ns => $dbKeyArray ) {
184 foreach ( $dbKeyArray as $dbKey => $userArray ) {
185 if ( isset( $userArray[$user->getId()] ) ) {
186 $this->stats
->increment( 'WatchedItemStore.uncacheUser.items' );
187 $this->cache
->delete( $userArray[$user->getId()] );
195 * @param LinkTarget $target
197 * @return WatchedItem|false
199 private function getCached( User
$user, LinkTarget
$target ) {
200 return $this->cache
->get( $this->getCacheKey( $user, $target ) );
204 * Return an array of conditions to select or update the appropriate database
208 * @param LinkTarget $target
212 private function dbCond( User
$user, LinkTarget
$target ) {
214 'wl_user' => $user->getId(),
215 'wl_namespace' => $target->getNamespace(),
216 'wl_title' => $target->getDBkey(),
221 * @param int $dbIndex DB_MASTER or DB_REPLICA
224 * @throws MWException
226 private function getConnectionRef( $dbIndex ) {
227 return $this->loadBalancer
->getConnectionRef( $dbIndex, [ 'watchlist' ] );
231 * Deletes ALL watched items for the given user when under
232 * $updateRowsPerQuery entries exist.
238 * @return bool true on success, false when too many items are watched
240 public function clearUserWatchedItems( User
$user ) {
241 if ( $this->countWatchedItems( $user ) > $this->updateRowsPerQuery
) {
245 $dbw = $this->loadBalancer
->getConnectionRef( DB_MASTER
);
248 [ 'wl_user' => $user->getId() ],
251 $this->uncacheAllItemsForUser( $user );
256 private function uncacheAllItemsForUser( User
$user ) {
257 $userId = $user->getId();
258 foreach ( $this->cacheIndex
as $ns => $dbKeyIndex ) {
259 foreach ( $dbKeyIndex as $dbKey => $userIndex ) {
260 if ( array_key_exists( $userId, $userIndex ) ) {
261 $this->cache
->delete( $userIndex[$userId] );
262 unset( $this->cacheIndex
[$ns][$dbKey][$userId] );
267 // Cleanup empty cache keys
268 foreach ( $this->cacheIndex
as $ns => $dbKeyIndex ) {
269 foreach ( $dbKeyIndex as $dbKey => $userIndex ) {
270 if ( empty( $this->cacheIndex
[$ns][$dbKey] ) ) {
271 unset( $this->cacheIndex
[$ns][$dbKey] );
274 if ( empty( $this->cacheIndex
[$ns] ) ) {
275 unset( $this->cacheIndex
[$ns] );
281 * Queues a job that will clear the users watchlist using the Job Queue.
287 public function clearUserWatchedItemsUsingJobQueue( User
$user ) {
288 $job = ClearUserWatchlistJob
::newForUser( $user, $this->getMaxId() );
290 JobQueueGroup
::singleton()->push( $job );
295 * @return int The maximum current wl_id
297 public function getMaxId() {
298 $dbr = $this->getConnectionRef( DB_REPLICA
);
299 return (int)$dbr->selectField(
312 public function countWatchedItems( User
$user ) {
313 $dbr = $this->getConnectionRef( DB_REPLICA
);
314 $return = (int)$dbr->selectField(
318 'wl_user' => $user->getId()
328 * @param LinkTarget $target
331 public function countWatchers( LinkTarget
$target ) {
332 $dbr = $this->getConnectionRef( DB_REPLICA
);
333 $return = (int)$dbr->selectField(
337 'wl_namespace' => $target->getNamespace(),
338 'wl_title' => $target->getDBkey(),
348 * @param LinkTarget $target
349 * @param string|int $threshold
352 public function countVisitingWatchers( LinkTarget
$target, $threshold ) {
353 $dbr = $this->getConnectionRef( DB_REPLICA
);
354 $visitingWatchers = (int)$dbr->selectField(
358 'wl_namespace' => $target->getNamespace(),
359 'wl_title' => $target->getDBkey(),
360 'wl_notificationtimestamp >= ' .
361 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
362 ' OR wl_notificationtimestamp IS NULL'
367 return $visitingWatchers;
372 * @param TitleValue[] $titles
374 * @throws MWException
376 public function removeWatchBatchForUser( User
$user, array $titles ) {
377 if ( $this->readOnlyMode
->isReadOnly() ) {
380 if ( $user->isAnon() ) {
387 $rows = $this->getTitleDbKeysGroupedByNamespace( $titles );
388 $this->uncacheTitlesForUser( $user, $titles );
390 $dbw = $this->getConnectionRef( DB_MASTER
);
391 $ticket = count( $titles ) > $this->updateRowsPerQuery ?
392 $this->lbFactory
->getEmptyTransactionTicket( __METHOD__
) : null;
395 // Batch delete items per namespace.
396 foreach ( $rows as $namespace => $namespaceTitles ) {
397 $rowBatches = array_chunk( $namespaceTitles, $this->updateRowsPerQuery
);
398 foreach ( $rowBatches as $toDelete ) {
399 $dbw->delete( 'watchlist', [
400 'wl_user' => $user->getId(),
401 'wl_namespace' => $namespace,
402 'wl_title' => $toDelete
404 $affectedRows +
= $dbw->affectedRows();
406 $this->lbFactory
->commitAndWaitForReplication( __METHOD__
, $ticket );
411 return (bool)$affectedRows;
416 * @param LinkTarget[] $targets
417 * @param array $options
420 public function countWatchersMultiple( array $targets, array $options = [] ) {
421 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
423 $dbr = $this->getConnectionRef( DB_REPLICA
);
425 if ( array_key_exists( 'minimumWatchers', $options ) ) {
426 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
429 $lb = new LinkBatch( $targets );
432 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
433 [ $lb->constructSet( 'wl', $dbr ) ],
439 foreach ( $targets as $linkTarget ) {
440 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
443 foreach ( $res as $row ) {
444 $watchCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
452 * @param array $targetsWithVisitThresholds
453 * @param int|null $minimumWatchers
456 public function countVisitingWatchersMultiple(
457 array $targetsWithVisitThresholds,
458 $minimumWatchers = null
460 if ( $targetsWithVisitThresholds === [] ) {
461 // No titles requested => no results returned
465 $dbr = $this->getConnectionRef( DB_REPLICA
);
467 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
469 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
470 if ( $minimumWatchers !== null ) {
471 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
475 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
482 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
483 /* @var LinkTarget $target */
484 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
487 foreach ( $res as $row ) {
488 $watcherCounts[$row->wl_namespace
][$row->wl_title
] = (int)$row->watchers
;
491 return $watcherCounts;
495 * Generates condition for the query used in a batch count visiting watchers.
497 * @param IDatabase $db
498 * @param array $targetsWithVisitThresholds array of pairs (LinkTarget, last visit threshold)
501 private function getVisitingWatchersCondition(
503 array $targetsWithVisitThresholds
505 $missingTargets = [];
506 $namespaceConds = [];
507 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
508 if ( $threshold === null ) {
509 $missingTargets[] = $target;
512 /* @var LinkTarget $target */
513 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
514 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
516 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
517 'wl_notificationtimestamp IS NULL'
523 foreach ( $namespaceConds as $namespace => $pageConds ) {
524 $conds[] = $db->makeList( [
525 'wl_namespace = ' . $namespace,
526 '(' . $db->makeList( $pageConds, LIST_OR
) . ')'
530 if ( $missingTargets ) {
531 $lb = new LinkBatch( $missingTargets );
532 $conds[] = $lb->constructSet( 'wl', $db );
535 return $db->makeList( $conds, LIST_OR
);
541 * @param LinkTarget $target
544 public function getWatchedItem( User
$user, LinkTarget
$target ) {
545 if ( $user->isAnon() ) {
549 $cached = $this->getCached( $user, $target );
551 $this->stats
->increment( 'WatchedItemStore.getWatchedItem.cached' );
554 $this->stats
->increment( 'WatchedItemStore.getWatchedItem.load' );
555 return $this->loadWatchedItem( $user, $target );
561 * @param LinkTarget $target
562 * @return WatchedItem|bool
564 public function loadWatchedItem( User
$user, LinkTarget
$target ) {
565 // Only loggedin user can have a watchlist
566 if ( $user->isAnon() ) {
570 $dbr = $this->getConnectionRef( DB_REPLICA
);
571 $row = $dbr->selectRow(
573 'wl_notificationtimestamp',
574 $this->dbCond( $user, $target ),
582 $item = new WatchedItem(
585 wfTimestampOrNull( TS_MW
, $row->wl_notificationtimestamp
)
587 $this->cache( $item );
595 * @param array $options
596 * @return WatchedItem[]
598 public function getWatchedItemsForUser( User
$user, array $options = [] ) {
599 $options +
= [ 'forWrite' => false ];
602 if ( array_key_exists( 'sort', $options ) ) {
604 ( in_array( $options['sort'], [ self
::SORT_ASC
, self
::SORT_DESC
] ) ),
605 '$options[\'sort\']',
606 'must be SORT_ASC or SORT_DESC'
608 $dbOptions['ORDER BY'] = [
609 "wl_namespace {$options['sort']}",
610 "wl_title {$options['sort']}"
613 $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER
: DB_REPLICA
);
617 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
618 [ 'wl_user' => $user->getId() ],
624 foreach ( $res as $row ) {
625 // @todo: Should we add these to the process cache?
626 $watchedItems[] = new WatchedItem(
628 new TitleValue( (int)$row->wl_namespace
, $row->wl_title
),
629 $row->wl_notificationtimestamp
633 return $watchedItems;
639 * @param LinkTarget $target
642 public function isWatched( User
$user, LinkTarget
$target ) {
643 return (bool)$this->getWatchedItem( $user, $target );
649 * @param LinkTarget[] $targets
652 public function getNotificationTimestampsBatch( User
$user, array $targets ) {
654 foreach ( $targets as $target ) {
655 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
658 if ( $user->isAnon() ) {
663 foreach ( $targets as $target ) {
664 $cachedItem = $this->getCached( $user, $target );
666 $timestamps[$target->getNamespace()][$target->getDBkey()] =
667 $cachedItem->getNotificationTimestamp();
669 $targetsToLoad[] = $target;
673 if ( !$targetsToLoad ) {
677 $dbr = $this->getConnectionRef( DB_REPLICA
);
679 $lb = new LinkBatch( $targetsToLoad );
682 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
684 $lb->constructSet( 'wl', $dbr ),
685 'wl_user' => $user->getId(),
690 foreach ( $res as $row ) {
691 $timestamps[$row->wl_namespace
][$row->wl_title
] =
692 wfTimestampOrNull( TS_MW
, $row->wl_notificationtimestamp
);
701 * @param LinkTarget $target
702 * @throws MWException
704 public function addWatch( User
$user, LinkTarget
$target ) {
705 $this->addWatchBatchForUser( $user, [ $target ] );
711 * @param LinkTarget[] $targets
713 * @throws MWException
715 public function addWatchBatchForUser( User
$user, array $targets ) {
716 if ( $this->readOnlyMode
->isReadOnly() ) {
719 // Only logged-in user can have a watchlist
720 if ( $user->isAnon() ) {
730 foreach ( $targets as $target ) {
732 'wl_user' => $user->getId(),
733 'wl_namespace' => $target->getNamespace(),
734 'wl_title' => $target->getDBkey(),
735 'wl_notificationtimestamp' => null,
737 $items[] = new WatchedItem(
742 $this->uncache( $user, $target );
745 $dbw = $this->getConnectionRef( DB_MASTER
);
746 $ticket = count( $targets ) > $this->updateRowsPerQuery ?
747 $this->lbFactory
->getEmptyTransactionTicket( __METHOD__
) : null;
749 $rowBatches = array_chunk( $rows, $this->updateRowsPerQuery
);
750 foreach ( $rowBatches as $toInsert ) {
751 // Use INSERT IGNORE to avoid overwriting the notification timestamp
752 // if there's already an entry for this page
753 $dbw->insert( 'watchlist', $toInsert, __METHOD__
, 'IGNORE' );
754 $affectedRows +
= $dbw->affectedRows();
756 $this->lbFactory
->commitAndWaitForReplication( __METHOD__
, $ticket );
759 // Update process cache to ensure skin doesn't claim that the current
760 // page is unwatched in the response of action=watch itself (T28292).
761 // This would otherwise be re-queried from a replica by isWatched().
762 foreach ( $items as $item ) {
763 $this->cache( $item );
766 return (bool)$affectedRows;
772 * @param LinkTarget $target
774 * @throws MWException
776 public function removeWatch( User
$user, LinkTarget
$target ) {
777 return $this->removeWatchBatchForUser( $user, [ $target ] );
783 * @param string|int $timestamp
784 * @param LinkTarget[] $targets
787 public function setNotificationTimestampsForUser( User
$user, $timestamp, array $targets = [] ) {
788 // Only loggedin user can have a watchlist
789 if ( $user->isAnon() ) {
793 $dbw = $this->getConnectionRef( DB_MASTER
);
795 $conds = [ 'wl_user' => $user->getId() ];
797 $batch = new LinkBatch( $targets );
798 $conds[] = $batch->constructSet( 'wl', $dbw );
801 if ( $timestamp !== null ) {
802 $timestamp = $dbw->timestamp( $timestamp );
805 $success = $dbw->update(
807 [ 'wl_notificationtimestamp' => $timestamp ],
812 $this->uncacheUser( $user );
817 public function resetAllNotificationTimestampsForUser( User
$user ) {
818 // Only loggedin user can have a watchlist
819 if ( $user->isAnon() ) {
823 // If the page is watched by the user (or may be watched), update the timestamp
824 $job = new ClearWatchlistNotificationsJob(
825 $user->getUserPage(),
826 [ 'userId' => $user->getId(), 'casTime' => time() ]
829 // Try to run this post-send
830 // Calls DeferredUpdates::addCallableUpdate in normal operation
832 $this->deferredUpdatesAddCallableUpdateCallback
,
833 function () use ( $job ) {
841 * @param User $editor
842 * @param LinkTarget $target
843 * @param string|int $timestamp
846 public function updateNotificationTimestamp( User
$editor, LinkTarget
$target, $timestamp ) {
847 $dbw = $this->getConnectionRef( DB_MASTER
);
848 $uids = $dbw->selectFieldValues(
852 'wl_user != ' . intval( $editor->getId() ),
853 'wl_namespace' => $target->getNamespace(),
854 'wl_title' => $target->getDBkey(),
855 'wl_notificationtimestamp IS NULL',
860 $watchers = array_map( 'intval', $uids );
862 // Update wl_notificationtimestamp for all watching users except the editor
864 DeferredUpdates
::addCallableUpdate(
865 function () use ( $timestamp, $watchers, $target, $fname ) {
866 $dbw = $this->getConnectionRef( DB_MASTER
);
867 $ticket = $this->lbFactory
->getEmptyTransactionTicket( $fname );
869 $watchersChunks = array_chunk( $watchers, $this->updateRowsPerQuery
);
870 foreach ( $watchersChunks as $watchersChunk ) {
871 $dbw->update( 'watchlist',
873 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
874 ], [ /* WHERE - TODO Use wl_id T130067 */
875 'wl_user' => $watchersChunk,
876 'wl_namespace' => $target->getNamespace(),
877 'wl_title' => $target->getDBkey(),
880 if ( count( $watchersChunks ) > 1 ) {
881 $this->lbFactory
->commitAndWaitForReplication(
882 $fname, $ticket, [ 'domain' => $dbw->getDomainID() ]
886 $this->uncacheLinkTarget( $target );
888 DeferredUpdates
::POSTSEND
,
899 * @param Title $title
900 * @param string $force
904 public function resetNotificationTimestamp( User
$user, Title
$title, $force = '', $oldid = 0 ) {
905 // Only loggedin user can have a watchlist
906 if ( $this->readOnlyMode
->isReadOnly() ||
$user->isAnon() ) {
910 if ( !Hooks
::run( 'BeforeResetNotificationTimestamp', [ &$user, &$title, $force, &$oldid ] ) ) {
915 if ( $force != 'force' ) {
916 $item = $this->loadWatchedItem( $user, $title );
917 if ( !$item ||
$item->getNotificationTimestamp() === null ) {
922 // If the page is watched by the user (or may be watched), update the timestamp
923 $job = new ActivityUpdateJob(
926 'type' => 'updateWatchlistNotification',
927 'userid' => $user->getId(),
928 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
933 // Try to run this post-send
934 // Calls DeferredUpdates::addCallableUpdate in normal operation
936 $this->deferredUpdatesAddCallableUpdateCallback
,
937 function () use ( $job ) {
942 $this->uncache( $user, $title );
947 private function getNotificationTimestamp( User
$user, Title
$title, $item, $force, $oldid ) {
949 // No oldid given, assuming latest revision; clear the timestamp.
953 if ( !$title->getNextRevisionID( $oldid ) ) {
954 // Oldid given and is the latest revision for this title; clear the timestamp.
958 if ( $item === null ) {
959 $item = $this->loadWatchedItem( $user, $title );
963 // This can only happen if $force is enabled.
967 // Oldid given and isn't the latest; update the timestamp.
968 // This will result in no further notification emails being sent!
969 // Calls Revision::getTimestampFromId in normal operation
970 $notificationTimestamp = call_user_func(
971 $this->revisionGetTimestampFromIdCallback
,
976 // We need to go one second to the future because of various strict comparisons
977 // throughout the codebase
978 $ts = new MWTimestamp( $notificationTimestamp );
979 $ts->timestamp
->add( new DateInterval( 'PT1S' ) );
980 $notificationTimestamp = $ts->getTimestamp( TS_MW
);
982 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
983 if ( $force != 'force' ) {
986 // This is a little silly…
987 return $item->getNotificationTimestamp();
991 return $notificationTimestamp;
997 * @param int|null $unreadLimit
1000 public function countUnreadNotifications( User
$user, $unreadLimit = null ) {
1002 if ( $unreadLimit !== null ) {
1003 $unreadLimit = (int)$unreadLimit;
1004 $queryOptions['LIMIT'] = $unreadLimit;
1007 $dbr = $this->getConnectionRef( DB_REPLICA
);
1008 $rowCount = $dbr->selectRowCount(
1012 'wl_user' => $user->getId(),
1013 'wl_notificationtimestamp IS NOT NULL',
1019 if ( !isset( $unreadLimit ) ) {
1023 if ( $rowCount >= $unreadLimit ) {
1032 * @param LinkTarget $oldTarget
1033 * @param LinkTarget $newTarget
1035 public function duplicateAllAssociatedEntries( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
1036 $oldTarget = Title
::newFromLinkTarget( $oldTarget );
1037 $newTarget = Title
::newFromLinkTarget( $newTarget );
1039 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
1040 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
1045 * @param LinkTarget $oldTarget
1046 * @param LinkTarget $newTarget
1048 public function duplicateEntry( LinkTarget
$oldTarget, LinkTarget
$newTarget ) {
1049 $dbw = $this->getConnectionRef( DB_MASTER
);
1051 $result = $dbw->select(
1053 [ 'wl_user', 'wl_notificationtimestamp' ],
1055 'wl_namespace' => $oldTarget->getNamespace(),
1056 'wl_title' => $oldTarget->getDBkey(),
1062 $newNamespace = $newTarget->getNamespace();
1063 $newDBkey = $newTarget->getDBkey();
1065 # Construct array to replace into the watchlist
1067 foreach ( $result as $row ) {
1069 'wl_user' => $row->wl_user
,
1070 'wl_namespace' => $newNamespace,
1071 'wl_title' => $newDBkey,
1072 'wl_notificationtimestamp' => $row->wl_notificationtimestamp
,
1076 if ( !empty( $values ) ) {
1078 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
1079 # some other DBMSes, mostly due to poor simulation by us
1082 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
1090 * @param TitleValue[] $titles
1093 private function getTitleDbKeysGroupedByNamespace( array $titles ) {
1095 foreach ( $titles as $title ) {
1096 // Group titles by namespace.
1097 $rows[ $title->getNamespace() ][] = $title->getDBkey();
1104 * @param Title[] $titles
1106 private function uncacheTitlesForUser( User
$user, array $titles ) {
1107 foreach ( $titles as $title ) {
1108 $this->uncache( $user, $title );