MediaWiki  master
WatchedItemStore.php
Go to the documentation of this file.
1 <?php
2 
10 
20 
24  private $lbFactory;
25 
29  private $loadBalancer;
30 
34  private $queueGroup;
35 
39  private $stash;
40 
44  private $readOnlyMode;
45 
49  private $cache;
50 
55 
62  private $cacheIndex = [];
63 
68 
73 
78 
82  private $stats;
83 
92  public function __construct(
99  ) {
100  $this->lbFactory = $lbFactory;
101  $this->loadBalancer = $lbFactory->getMainLB();
102  $this->queueGroup = $queueGroup;
103  $this->stash = $stash;
104  $this->cache = $cache;
105  $this->readOnlyMode = $readOnlyMode;
106  $this->stats = new NullStatsdDataFactory();
107  $this->deferredUpdatesAddCallableUpdateCallback =
108  [ DeferredUpdates::class, 'addCallableUpdate' ];
109  $this->revisionGetTimestampFromIdCallback =
110  [ Revision::class, 'getTimestampFromId' ];
111  $this->updateRowsPerQuery = $updateRowsPerQuery;
112 
113  $this->latestUpdateCache = new HashBagOStuff( [ 'maxKeys' => 3 ] );
114  }
115 
119  public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
120  $this->stats = $stats;
121  }
122 
134  public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
135  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
136  throw new MWException(
137  'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
138  );
139  }
141  $this->deferredUpdatesAddCallableUpdateCallback = $callback;
142  return new ScopedCallback( function () use ( $previousValue ) {
143  $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
144  } );
145  }
146 
157  public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
158  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
159  throw new MWException(
160  'Cannot override Revision::getTimestampFromId callback in operation.'
161  );
162  }
164  $this->revisionGetTimestampFromIdCallback = $callback;
165  return new ScopedCallback( function () use ( $previousValue ) {
166  $this->revisionGetTimestampFromIdCallback = $previousValue;
167  } );
168  }
169 
170  private function getCacheKey( User $user, LinkTarget $target ) {
171  return $this->cache->makeKey(
172  (string)$target->getNamespace(),
173  $target->getDBkey(),
174  (string)$user->getId()
175  );
176  }
177 
178  private function cache( WatchedItem $item ) {
179  $user = $item->getUser();
180  $target = $item->getLinkTarget();
181  $key = $this->getCacheKey( $user, $target );
182  $this->cache->set( $key, $item );
183  $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
184  $this->stats->increment( 'WatchedItemStore.cache' );
185  }
186 
187  private function uncache( User $user, LinkTarget $target ) {
188  $this->cache->delete( $this->getCacheKey( $user, $target ) );
189  unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
190  $this->stats->increment( 'WatchedItemStore.uncache' );
191  }
192 
193  private function uncacheLinkTarget( LinkTarget $target ) {
194  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
195  if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
196  return;
197  }
198  foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
199  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
200  $this->cache->delete( $key );
201  }
202  }
203 
204  private function uncacheUser( User $user ) {
205  $this->stats->increment( 'WatchedItemStore.uncacheUser' );
206  foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
207  foreach ( $dbKeyArray as $dbKey => $userArray ) {
208  if ( isset( $userArray[$user->getId()] ) ) {
209  $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
210  $this->cache->delete( $userArray[$user->getId()] );
211  }
212  }
213  }
214 
215  $pageSeenKey = $this->getPageSeenTimestampsKey( $user );
216  $this->latestUpdateCache->delete( $pageSeenKey );
217  $this->stash->delete( $pageSeenKey );
218  }
219 
226  private function getCached( User $user, LinkTarget $target ) {
227  return $this->cache->get( $this->getCacheKey( $user, $target ) );
228  }
229 
239  private function dbCond( User $user, LinkTarget $target ) {
240  return [
241  'wl_user' => $user->getId(),
242  'wl_namespace' => $target->getNamespace(),
243  'wl_title' => $target->getDBkey(),
244  ];
245  }
246 
253  private function getConnectionRef( $dbIndex ) {
254  return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
255  }
256 
267  public function clearUserWatchedItems( User $user ) {
268  if ( $this->countWatchedItems( $user ) > $this->updateRowsPerQuery ) {
269  return false;
270  }
271 
272  $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
273  $dbw->delete(
274  'watchlist',
275  [ 'wl_user' => $user->getId() ],
276  __METHOD__
277  );
278  $this->uncacheAllItemsForUser( $user );
279 
280  return true;
281  }
282 
283  private function uncacheAllItemsForUser( User $user ) {
284  $userId = $user->getId();
285  foreach ( $this->cacheIndex as $ns => $dbKeyIndex ) {
286  foreach ( $dbKeyIndex as $dbKey => $userIndex ) {
287  if ( array_key_exists( $userId, $userIndex ) ) {
288  $this->cache->delete( $userIndex[$userId] );
289  unset( $this->cacheIndex[$ns][$dbKey][$userId] );
290  }
291  }
292  }
293 
294  // Cleanup empty cache keys
295  foreach ( $this->cacheIndex as $ns => $dbKeyIndex ) {
296  foreach ( $dbKeyIndex as $dbKey => $userIndex ) {
297  if ( empty( $this->cacheIndex[$ns][$dbKey] ) ) {
298  unset( $this->cacheIndex[$ns][$dbKey] );
299  }
300  }
301  if ( empty( $this->cacheIndex[$ns] ) ) {
302  unset( $this->cacheIndex[$ns] );
303  }
304  }
305  }
306 
315  $job = ClearUserWatchlistJob::newForUser( $user, $this->getMaxId() );
316  $this->queueGroup->push( $job );
317  }
318 
323  public function getMaxId() {
324  $dbr = $this->getConnectionRef( DB_REPLICA );
325  return (int)$dbr->selectField(
326  'watchlist',
327  'MAX(wl_id)',
328  '',
329  __METHOD__
330  );
331  }
332 
338  public function countWatchedItems( User $user ) {
339  $dbr = $this->getConnectionRef( DB_REPLICA );
340  $return = (int)$dbr->selectField(
341  'watchlist',
342  'COUNT(*)',
343  [
344  'wl_user' => $user->getId()
345  ],
346  __METHOD__
347  );
348 
349  return $return;
350  }
351 
357  public function countWatchers( LinkTarget $target ) {
358  $dbr = $this->getConnectionRef( DB_REPLICA );
359  $return = (int)$dbr->selectField(
360  'watchlist',
361  'COUNT(*)',
362  [
363  'wl_namespace' => $target->getNamespace(),
364  'wl_title' => $target->getDBkey(),
365  ],
366  __METHOD__
367  );
368 
369  return $return;
370  }
371 
378  public function countVisitingWatchers( LinkTarget $target, $threshold ) {
379  $dbr = $this->getConnectionRef( DB_REPLICA );
380  $visitingWatchers = (int)$dbr->selectField(
381  'watchlist',
382  'COUNT(*)',
383  [
384  'wl_namespace' => $target->getNamespace(),
385  'wl_title' => $target->getDBkey(),
386  'wl_notificationtimestamp >= ' .
387  $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
388  ' OR wl_notificationtimestamp IS NULL'
389  ],
390  __METHOD__
391  );
392 
393  return $visitingWatchers;
394  }
395 
403  if ( $this->readOnlyMode->isReadOnly() ) {
404  return false;
405  }
406  if ( $user->isAnon() ) {
407  return false;
408  }
409  if ( !$titles ) {
410  return true;
411  }
412 
413  $rows = $this->getTitleDbKeysGroupedByNamespace( $titles );
414  $this->uncacheTitlesForUser( $user, $titles );
415 
416  $dbw = $this->getConnectionRef( DB_MASTER );
417  $ticket = count( $titles ) > $this->updateRowsPerQuery ?
418  $this->lbFactory->getEmptyTransactionTicket( __METHOD__ ) : null;
419  $affectedRows = 0;
420 
421  // Batch delete items per namespace.
422  foreach ( $rows as $namespace => $namespaceTitles ) {
423  $rowBatches = array_chunk( $namespaceTitles, $this->updateRowsPerQuery );
424  foreach ( $rowBatches as $toDelete ) {
425  $dbw->delete( 'watchlist', [
426  'wl_user' => $user->getId(),
427  'wl_namespace' => $namespace,
428  'wl_title' => $toDelete
429  ], __METHOD__ );
430  $affectedRows += $dbw->affectedRows();
431  if ( $ticket ) {
432  $this->lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
433  }
434  }
435  }
436 
437  return (bool)$affectedRows;
438  }
439 
446  public function countWatchersMultiple( array $targets, array $options = [] ) {
447  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
448 
449  $dbr = $this->getConnectionRef( DB_REPLICA );
450 
451  if ( array_key_exists( 'minimumWatchers', $options ) ) {
452  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
453  }
454 
455  $lb = new LinkBatch( $targets );
456  $res = $dbr->select(
457  'watchlist',
458  [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
459  [ $lb->constructSet( 'wl', $dbr ) ],
460  __METHOD__,
461  $dbOptions
462  );
463 
464  $watchCounts = [];
465  foreach ( $targets as $linkTarget ) {
466  $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
467  }
468 
469  foreach ( $res as $row ) {
470  $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
471  }
472 
473  return $watchCounts;
474  }
475 
483  array $targetsWithVisitThresholds,
484  $minimumWatchers = null
485  ) {
486  if ( $targetsWithVisitThresholds === [] ) {
487  // No titles requested => no results returned
488  return [];
489  }
490 
491  $dbr = $this->getConnectionRef( DB_REPLICA );
492 
493  $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
494 
495  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
496  if ( $minimumWatchers !== null ) {
497  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
498  }
499  $res = $dbr->select(
500  'watchlist',
501  [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
502  $conds,
503  __METHOD__,
504  $dbOptions
505  );
506 
507  $watcherCounts = [];
508  foreach ( $targetsWithVisitThresholds as list( $target ) ) {
509  /* @var LinkTarget $target */
510  $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
511  }
512 
513  foreach ( $res as $row ) {
514  $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
515  }
516 
517  return $watcherCounts;
518  }
519 
528  IDatabase $db,
529  array $targetsWithVisitThresholds
530  ) {
531  $missingTargets = [];
532  $namespaceConds = [];
533  foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
534  if ( $threshold === null ) {
535  $missingTargets[] = $target;
536  continue;
537  }
538  /* @var LinkTarget $target */
539  $namespaceConds[$target->getNamespace()][] = $db->makeList( [
540  'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
541  $db->makeList( [
542  'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
543  'wl_notificationtimestamp IS NULL'
544  ], LIST_OR )
545  ], LIST_AND );
546  }
547 
548  $conds = [];
549  foreach ( $namespaceConds as $namespace => $pageConds ) {
550  $conds[] = $db->makeList( [
551  'wl_namespace = ' . $namespace,
552  '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
553  ], LIST_AND );
554  }
555 
556  if ( $missingTargets ) {
557  $lb = new LinkBatch( $missingTargets );
558  $conds[] = $lb->constructSet( 'wl', $db );
559  }
560 
561  return $db->makeList( $conds, LIST_OR );
562  }
563 
570  public function getWatchedItem( User $user, LinkTarget $target ) {
571  if ( $user->isAnon() ) {
572  return false;
573  }
574 
575  $cached = $this->getCached( $user, $target );
576  if ( $cached ) {
577  $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
578  return $cached;
579  }
580  $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
581  return $this->loadWatchedItem( $user, $target );
582  }
583 
590  public function loadWatchedItem( User $user, LinkTarget $target ) {
591  // Only loggedin user can have a watchlist
592  if ( $user->isAnon() ) {
593  return false;
594  }
595 
596  $dbr = $this->getConnectionRef( DB_REPLICA );
597 
598  $row = $dbr->selectRow(
599  'watchlist',
600  'wl_notificationtimestamp',
601  $this->dbCond( $user, $target ),
602  __METHOD__
603  );
604 
605  if ( !$row ) {
606  return false;
607  }
608 
609  $item = new WatchedItem(
610  $user,
611  $target,
612  $this->getLatestNotificationTimestamp( $row->wl_notificationtimestamp, $user, $target )
613  );
614  $this->cache( $item );
615 
616  return $item;
617  }
618 
625  public function getWatchedItemsForUser( User $user, array $options = [] ) {
626  $options += [ 'forWrite' => false ];
627 
628  $dbOptions = [];
629  if ( array_key_exists( 'sort', $options ) ) {
630  Assert::parameter(
631  ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
632  '$options[\'sort\']',
633  'must be SORT_ASC or SORT_DESC'
634  );
635  $dbOptions['ORDER BY'] = [
636  "wl_namespace {$options['sort']}",
637  "wl_title {$options['sort']}"
638  ];
639  }
640  $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
641 
642  $res = $db->select(
643  'watchlist',
644  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
645  [ 'wl_user' => $user->getId() ],
646  __METHOD__,
647  $dbOptions
648  );
649 
650  $watchedItems = [];
651  foreach ( $res as $row ) {
652  $target = new TitleValue( (int)$row->wl_namespace, $row->wl_title );
653  // @todo: Should we add these to the process cache?
654  $watchedItems[] = new WatchedItem(
655  $user,
656  new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
657  $this->getLatestNotificationTimestamp(
658  $row->wl_notificationtimestamp, $user, $target )
659  );
660  }
661 
662  return $watchedItems;
663  }
664 
671  public function isWatched( User $user, LinkTarget $target ) {
672  return (bool)$this->getWatchedItem( $user, $target );
673  }
674 
681  public function getNotificationTimestampsBatch( User $user, array $targets ) {
682  $timestamps = [];
683  foreach ( $targets as $target ) {
684  $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
685  }
686 
687  if ( $user->isAnon() ) {
688  return $timestamps;
689  }
690 
691  $targetsToLoad = [];
692  foreach ( $targets as $target ) {
693  $cachedItem = $this->getCached( $user, $target );
694  if ( $cachedItem ) {
695  $timestamps[$target->getNamespace()][$target->getDBkey()] =
696  $cachedItem->getNotificationTimestamp();
697  } else {
698  $targetsToLoad[] = $target;
699  }
700  }
701 
702  if ( !$targetsToLoad ) {
703  return $timestamps;
704  }
705 
706  $dbr = $this->getConnectionRef( DB_REPLICA );
707 
708  $lb = new LinkBatch( $targetsToLoad );
709  $res = $dbr->select(
710  'watchlist',
711  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
712  [
713  $lb->constructSet( 'wl', $dbr ),
714  'wl_user' => $user->getId(),
715  ],
716  __METHOD__
717  );
718 
719  foreach ( $res as $row ) {
720  $target = new TitleValue( (int)$row->wl_namespace, $row->wl_title );
721  $timestamps[$row->wl_namespace][$row->wl_title] =
723  $row->wl_notificationtimestamp, $user, $target );
724  }
725 
726  return $timestamps;
727  }
728 
735  public function addWatch( User $user, LinkTarget $target ) {
736  $this->addWatchBatchForUser( $user, [ $target ] );
737  }
738 
746  public function addWatchBatchForUser( User $user, array $targets ) {
747  if ( $this->readOnlyMode->isReadOnly() ) {
748  return false;
749  }
750  // Only logged-in user can have a watchlist
751  if ( $user->isAnon() ) {
752  return false;
753  }
754 
755  if ( !$targets ) {
756  return true;
757  }
758 
759  $rows = [];
760  $items = [];
761  foreach ( $targets as $target ) {
762  $rows[] = [
763  'wl_user' => $user->getId(),
764  'wl_namespace' => $target->getNamespace(),
765  'wl_title' => $target->getDBkey(),
766  'wl_notificationtimestamp' => null,
767  ];
768  $items[] = new WatchedItem(
769  $user,
770  $target,
771  null
772  );
773  $this->uncache( $user, $target );
774  }
775 
776  $dbw = $this->getConnectionRef( DB_MASTER );
777  $ticket = count( $targets ) > $this->updateRowsPerQuery ?
778  $this->lbFactory->getEmptyTransactionTicket( __METHOD__ ) : null;
779  $affectedRows = 0;
780  $rowBatches = array_chunk( $rows, $this->updateRowsPerQuery );
781  foreach ( $rowBatches as $toInsert ) {
782  // Use INSERT IGNORE to avoid overwriting the notification timestamp
783  // if there's already an entry for this page
784  $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
785  $affectedRows += $dbw->affectedRows();
786  if ( $ticket ) {
787  $this->lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
788  }
789  }
790  // Update process cache to ensure skin doesn't claim that the current
791  // page is unwatched in the response of action=watch itself (T28292).
792  // This would otherwise be re-queried from a replica by isWatched().
793  foreach ( $items as $item ) {
794  $this->cache( $item );
795  }
796 
797  return (bool)$affectedRows;
798  }
799 
807  public function removeWatch( User $user, LinkTarget $target ) {
808  return $this->removeWatchBatchForUser( $user, [ $target ] );
809  }
810 
828  public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
829  // Only loggedin user can have a watchlist
830  if ( $user->isAnon() || $this->readOnlyMode->isReadOnly() ) {
831  return false;
832  }
833 
834  if ( !$targets ) {
835  // Backwards compatibility
836  $this->resetAllNotificationTimestampsForUser( $user, $timestamp );
837  return true;
838  }
839 
840  $rows = $this->getTitleDbKeysGroupedByNamespace( $targets );
841 
842  $dbw = $this->getConnectionRef( DB_MASTER );
843  if ( $timestamp !== null ) {
844  $timestamp = $dbw->timestamp( $timestamp );
845  }
846  $ticket = $this->lbFactory->getEmptyTransactionTicket( __METHOD__ );
847  $affectedSinceWait = 0;
848 
849  // Batch update items per namespace
850  foreach ( $rows as $namespace => $namespaceTitles ) {
851  $rowBatches = array_chunk( $namespaceTitles, $this->updateRowsPerQuery );
852  foreach ( $rowBatches as $toUpdate ) {
853  $dbw->update(
854  'watchlist',
855  [ 'wl_notificationtimestamp' => $timestamp ],
856  [
857  'wl_user' => $user->getId(),
858  'wl_namespace' => $namespace,
859  'wl_title' => $toUpdate
860  ]
861  );
862  $affectedSinceWait += $dbw->affectedRows();
863  // Wait for replication every time we've touched updateRowsPerQuery rows
864  if ( $affectedSinceWait >= $this->updateRowsPerQuery ) {
865  $this->lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
866  $affectedSinceWait = 0;
867  }
868  }
869  }
870 
871  $this->uncacheUser( $user );
872 
873  return true;
874  }
875 
876  public function getLatestNotificationTimestamp( $timestamp, User $user, LinkTarget $target ) {
877  $timestamp = wfTimestampOrNull( TS_MW, $timestamp );
878  if ( $timestamp === null ) {
879  return null; // no notification
880  }
881 
882  $seenTimestamps = $this->getPageSeenTimestamps( $user );
883  if (
884  $seenTimestamps &&
885  $seenTimestamps->get( $this->getPageSeenKey( $target ) ) >= $timestamp
886  ) {
887  // If a reset job did not yet run, then the "seen" timestamp will be higher
888  return null;
889  }
890 
891  return $timestamp;
892  }
893 
900  public function resetAllNotificationTimestampsForUser( User $user, $timestamp = null ) {
901  // Only loggedin user can have a watchlist
902  if ( $user->isAnon() ) {
903  return;
904  }
905 
906  // If the page is watched by the user (or may be watched), update the timestamp
908  'userId' => $user->getId(), 'timestamp' => $timestamp, 'casTime' => time()
909  ] );
910 
911  // Try to run this post-send
912  // Calls DeferredUpdates::addCallableUpdate in normal operation
913  call_user_func(
914  $this->deferredUpdatesAddCallableUpdateCallback,
915  function () use ( $job ) {
916  $job->run();
917  }
918  );
919  }
920 
928  public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
929  $dbw = $this->getConnectionRef( DB_MASTER );
930  $uids = $dbw->selectFieldValues(
931  'watchlist',
932  'wl_user',
933  [
934  'wl_user != ' . intval( $editor->getId() ),
935  'wl_namespace' => $target->getNamespace(),
936  'wl_title' => $target->getDBkey(),
937  'wl_notificationtimestamp IS NULL',
938  ],
939  __METHOD__
940  );
941 
942  $watchers = array_map( 'intval', $uids );
943  if ( $watchers ) {
944  // Update wl_notificationtimestamp for all watching users except the editor
945  $fname = __METHOD__;
947  function () use ( $timestamp, $watchers, $target, $fname ) {
948  $dbw = $this->getConnectionRef( DB_MASTER );
949  $ticket = $this->lbFactory->getEmptyTransactionTicket( $fname );
950 
951  $watchersChunks = array_chunk( $watchers, $this->updateRowsPerQuery );
952  foreach ( $watchersChunks as $watchersChunk ) {
953  $dbw->update( 'watchlist',
954  [ /* SET */
955  'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
956  ], [ /* WHERE - TODO Use wl_id T130067 */
957  'wl_user' => $watchersChunk,
958  'wl_namespace' => $target->getNamespace(),
959  'wl_title' => $target->getDBkey(),
960  ], $fname
961  );
962  if ( count( $watchersChunks ) > 1 ) {
963  $this->lbFactory->commitAndWaitForReplication(
964  $fname, $ticket, [ 'domain' => $dbw->getDomainID() ]
965  );
966  }
967  }
968  $this->uncacheLinkTarget( $target );
969  },
971  $dbw
972  );
973  }
974 
975  return $watchers;
976  }
977 
986  public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
987  $time = time();
988 
989  // Only loggedin user can have a watchlist
990  if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
991  return false;
992  }
993 
994  if ( !Hooks::run( 'BeforeResetNotificationTimestamp', [ &$user, &$title, $force, &$oldid ] ) ) {
995  return false;
996  }
997 
998  $item = null;
999  if ( $force != 'force' ) {
1000  $item = $this->loadWatchedItem( $user, $title );
1001  if ( !$item || $item->getNotificationTimestamp() === null ) {
1002  return false;
1003  }
1004  }
1005 
1006  // Get the timestamp (TS_MW) of this revision to track the latest one seen
1007  $seenTime = call_user_func(
1008  $this->revisionGetTimestampFromIdCallback,
1009  $title,
1010  $oldid ?: $title->getLatestRevID()
1011  );
1012 
1013  // Mark the item as read immediately in lightweight storage
1014  $this->stash->merge(
1015  $this->getPageSeenTimestampsKey( $user ),
1016  function ( $cache, $key, $current ) use ( $title, $seenTime ) {
1017  $value = $current ?: new MapCacheLRU( 300 );
1018  $subKey = $this->getPageSeenKey( $title );
1019 
1020  if ( $seenTime > $value->get( $subKey ) ) {
1021  // Revision is newer than the last one seen
1022  $value->set( $subKey, $seenTime );
1023  $this->latestUpdateCache->set( $key, $value, IExpiringStore::TTL_PROC_LONG );
1024  } elseif ( $seenTime === false ) {
1025  // Revision does not exist
1026  $value->set( $subKey, wfTimestamp( TS_MW ) );
1027  $this->latestUpdateCache->set( $key, $value, IExpiringStore::TTL_PROC_LONG );
1028  } else {
1029  return false; // nothing to update
1030  }
1031 
1032  return $value;
1033  },
1035  );
1036 
1037  // If the page is watched by the user (or may be watched), update the timestamp
1038  $job = new ActivityUpdateJob(
1039  $title,
1040  [
1041  'type' => 'updateWatchlistNotification',
1042  'userid' => $user->getId(),
1043  'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
1044  'curTime' => $time
1045  ]
1046  );
1047  // Try to enqueue this post-send
1048  $this->queueGroup->lazyPush( $job );
1049 
1050  $this->uncache( $user, $title );
1051 
1052  return true;
1053  }
1054 
1059  private function getPageSeenTimestamps( User $user ) {
1060  $key = $this->getPageSeenTimestampsKey( $user );
1061 
1062  return $this->latestUpdateCache->getWithSetCallback(
1063  $key,
1065  function () use ( $key ) {
1066  return $this->stash->get( $key ) ?: null;
1067  }
1068  );
1069  }
1070 
1075  private function getPageSeenTimestampsKey( User $user ) {
1076  return $this->stash->makeGlobalKey(
1077  'watchlist-recent-updates',
1078  $this->lbFactory->getLocalDomainID(),
1079  $user->getId()
1080  );
1081  }
1082 
1087  private function getPageSeenKey( LinkTarget $target ) {
1088  return "{$target->getNamespace()}:{$target->getDBkey()}";
1089  }
1090 
1091  private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
1092  if ( !$oldid ) {
1093  // No oldid given, assuming latest revision; clear the timestamp.
1094  return null;
1095  }
1096 
1097  if ( !$title->getNextRevisionID( $oldid ) ) {
1098  // Oldid given and is the latest revision for this title; clear the timestamp.
1099  return null;
1100  }
1101 
1102  if ( $item === null ) {
1103  $item = $this->loadWatchedItem( $user, $title );
1104  }
1105 
1106  if ( !$item ) {
1107  // This can only happen if $force is enabled.
1108  return null;
1109  }
1110 
1111  // Oldid given and isn't the latest; update the timestamp.
1112  // This will result in no further notification emails being sent!
1113  // Calls Revision::getTimestampFromId in normal operation
1114  $notificationTimestamp = call_user_func(
1115  $this->revisionGetTimestampFromIdCallback,
1116  $title,
1117  $oldid
1118  );
1119 
1120  // We need to go one second to the future because of various strict comparisons
1121  // throughout the codebase
1122  $ts = new MWTimestamp( $notificationTimestamp );
1123  $ts->timestamp->add( new DateInterval( 'PT1S' ) );
1124  $notificationTimestamp = $ts->getTimestamp( TS_MW );
1125 
1126  if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
1127  if ( $force != 'force' ) {
1128  return false;
1129  } else {
1130  // This is a little silly‚Ķ
1131  return $item->getNotificationTimestamp();
1132  }
1133  }
1134 
1135  return $notificationTimestamp;
1136  }
1137 
1144  public function countUnreadNotifications( User $user, $unreadLimit = null ) {
1145  $dbr = $this->getConnectionRef( DB_REPLICA );
1146 
1147  $queryOptions = [];
1148  if ( $unreadLimit !== null ) {
1149  $unreadLimit = (int)$unreadLimit;
1150  $queryOptions['LIMIT'] = $unreadLimit;
1151  }
1152 
1153  $conds = [
1154  'wl_user' => $user->getId(),
1155  'wl_notificationtimestamp IS NOT NULL'
1156  ];
1157 
1158  $rowCount = $dbr->selectRowCount( 'watchlist', '1', $conds, __METHOD__, $queryOptions );
1159 
1160  if ( $unreadLimit === null ) {
1161  return $rowCount;
1162  }
1163 
1164  if ( $rowCount >= $unreadLimit ) {
1165  return true;
1166  }
1167 
1168  return $rowCount;
1169  }
1170 
1176  public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
1177  $oldTarget = Title::newFromLinkTarget( $oldTarget );
1178  $newTarget = Title::newFromLinkTarget( $newTarget );
1179 
1180  $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
1181  $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
1182  }
1183 
1189  public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
1190  $dbw = $this->getConnectionRef( DB_MASTER );
1191 
1192  $result = $dbw->select(
1193  'watchlist',
1194  [ 'wl_user', 'wl_notificationtimestamp' ],
1195  [
1196  'wl_namespace' => $oldTarget->getNamespace(),
1197  'wl_title' => $oldTarget->getDBkey(),
1198  ],
1199  __METHOD__,
1200  [ 'FOR UPDATE' ]
1201  );
1202 
1203  $newNamespace = $newTarget->getNamespace();
1204  $newDBkey = $newTarget->getDBkey();
1205 
1206  # Construct array to replace into the watchlist
1207  $values = [];
1208  foreach ( $result as $row ) {
1209  $values[] = [
1210  'wl_user' => $row->wl_user,
1211  'wl_namespace' => $newNamespace,
1212  'wl_title' => $newDBkey,
1213  'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
1214  ];
1215  }
1216 
1217  if ( !empty( $values ) ) {
1218  # Perform replace
1219  # Note that multi-row replace is very efficient for MySQL but may be inefficient for
1220  # some other DBMSes, mostly due to poor simulation by us
1221  $dbw->replace(
1222  'watchlist',
1223  [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
1224  $values,
1225  __METHOD__
1226  );
1227  }
1228  }
1229 
1235  $rows = [];
1236  foreach ( $titles as $title ) {
1237  // Group titles by namespace.
1238  $rows[ $title->getNamespace() ][] = $title->getDBkey();
1239  }
1240  return $rows;
1241  }
1242 
1248  foreach ( $titles as $title ) {
1249  $this->uncache( $user, $title );
1250  }
1251  }
1252 
1253 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
clearUserWatchedItemsUsingJobQueue(User $user)
Queues a job that will clear the users watchlist using the Job Queue.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2633
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
setNotificationTimestampsForUser(User $user, $timestamp, array $targets=[])
Set the "last viewed" timestamps for certain titles on a user&#39;s watchlist.
getTitleDbKeysGroupedByNamespace(array $titles)
getCacheKey(User $user, LinkTarget $target)
Job for clearing all of the "last viewed" timestamps for a user&#39;s watchlist, or setting them all to t...
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
countWatchedItems(User $user)
ReadOnlyMode $readOnlyMode
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getCached(User $user, LinkTarget $target)
uncacheTitlesForUser(User $user, array $titles)
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
$value
overrideDeferredUpdatesAddCallableUpdateCallback(callable $callback)
Overrides the DeferredUpdates::addCallableUpdate callback This is intended for use while testing and ...
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
addWatchBatchForUser(User $user, array $targets)
getNotificationTimestamp(User $user, Title $title, $item, $force, $oldid)
Describes a Statsd aware interface.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1799
const DB_MASTER
Definition: defines.php:26
getNamespace()
Get the namespace index.
getConnectionRef( $dbIndex)
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
Storage layer class for WatchedItems.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
A service class for fetching the wiki&#39;s current read-only mode.
callable null $revisionGetTimestampFromIdCallback
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
Job for updating user activity like "last viewed" timestamps.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
uncacheUser(User $user)
addWatch(User $user, LinkTarget $target)
duplicateAllAssociatedEntries(LinkTarget $oldTarget, LinkTarget $newTarget)
countWatchers(LinkTarget $target)
const LIST_AND
Definition: Defines.php:43
StatsdDataFactoryInterface $stats
isAnon()
Get whether the user is anonymous.
Definition: User.php:3806
array [] $cacheIndex
Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => &#39;key&#39; The index is needed so that on ...
$res
Definition: database.txt:21
countUnreadNotifications(User $user, $unreadLimit=null)
removeWatchBatchForUser(User $user, array $titles)
getLatestNotificationTimestamp( $timestamp, User $user, LinkTarget $target)
Convert $timestamp to TS_MW or return null if the page was visited since then by $user.
getDBkey()
Get the main part with underscores.
getWatchedItemsForUser(User $user, array $options=[])
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
loadWatchedItem(User $user, LinkTarget $target)
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:32
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
LoadBalancer $loadBalancer
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
resetAllNotificationTimestampsForUser(User $user, $timestamp=null)
Schedule a DeferredUpdate that sets all of the "last viewed" timestamps for a given user to the same ...
clearUserWatchedItems(User $user)
Deletes ALL watched items for the given user when under $updateRowsPerQuery entries exist...
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
getMainLB( $domain=false)
Get a cached (tracked) load balancer object.
resetNotificationTimestamp(User $user, Title $title, $force='', $oldid=0)
const LIST_OR
Definition: Defines.php:46
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:271
getPageSeenTimestampsKey(User $user)
setStatsdDataFactory(StatsdDataFactoryInterface $stats)
countVisitingWatchersMultiple(array $targetsWithVisitThresholds, $minimumWatchers=null)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
overrideRevisionGetTimestampFromIdCallback(callable $callback)
Overrides the Revision::getTimestampFromId callback This is intended for use while testing and will f...
JobQueueGroup $queueGroup
countWatchersMultiple(array $targets, array $options=[])
getPageSeenTimestamps(User $user)
updateNotificationTimestamp(User $editor, LinkTarget $target, $timestamp)
An interface for generating database load balancers.
Definition: ILBFactory.php:33
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
removeWatch(User $user, LinkTarget $target)
getPageSeenKey(LinkTarget $target)
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
callable null $deferredUpdatesAddCallableUpdateCallback
getId()
Get the user&#39;s ID.
Definition: User.php:2427
isWatched(User $user, LinkTarget $target)
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
cache(WatchedItem $item)
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
if(count( $args)< 1) $job
HashBagOStuff $cache
getLatestRevID( $flags=0)
What is the page_latest field for this page?
Definition: Title.php:3072
__construct(ILBFactory $lbFactory, JobQueueGroup $queueGroup, BagOStuff $stash, HashBagOStuff $cache, ReadOnlyMode $readOnlyMode, $updateRowsPerQuery)
uncacheLinkTarget(LinkTarget $target)
getWatchedItem(User $user, LinkTarget $target)
duplicateEntry(LinkTarget $oldTarget, LinkTarget $newTarget)
getNotificationTimestampsBatch(User $user, array $targets)
const DB_REPLICA
Definition: defines.php:25
dbCond(User $user, LinkTarget $target)
Return an array of conditions to select or update the appropriate database row.
HashBagOStuff $latestUpdateCache
getVisitingWatchersCondition(IDatabase $db, array $targetsWithVisitThresholds)
Generates condition for the query used in a batch count visiting watchers.
uncacheAllItemsForUser(User $user)
addQuotes( $s)
Adds quotes and backslashes.
uncache(User $user, LinkTarget $target)
countVisitingWatchers(LinkTarget $target, $threshold)
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error etc yourself modifying $error and returning true will cause the contents of $error to be echoed at the top of the edit form as wikitext Return true without altering $error to allow the edit to proceed & $editor
Definition: hooks.txt:1287
static newForUser(User $user, $maxWatchlistId)
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
getNextRevisionID( $revId, $flags=0)
Get the revision ID of the next revision.
Definition: Title.php:3799