MediaWiki  1.29.1
WatchedItemStore.php
Go to the documentation of this file.
1 <?php
2 
4 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
7 use Wikimedia\Assert\Assert;
8 use Wikimedia\ScopedCallback;
11 
24 
25  const SORT_DESC = 'DESC';
26  const SORT_ASC = 'ASC';
27 
31  private $loadBalancer;
32 
36  private $readOnlyMode;
37 
41  private $cache;
42 
49  private $cacheIndex = [];
50 
55 
60 
64  private $stats;
65 
71  public function __construct(
75  ) {
76  $this->loadBalancer = $loadBalancer;
77  $this->cache = $cache;
78  $this->readOnlyMode = $readOnlyMode;
79  $this->stats = new NullStatsdDataFactory();
80  $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
81  $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
82  }
83 
84  public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
85  $this->stats = $stats;
86  }
87 
99  public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
100  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
101  throw new MWException(
102  'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
103  );
104  }
106  $this->deferredUpdatesAddCallableUpdateCallback = $callback;
107  return new ScopedCallback( function() use ( $previousValue ) {
108  $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
109  } );
110  }
111 
122  public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
123  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
124  throw new MWException(
125  'Cannot override Revision::getTimestampFromId callback in operation.'
126  );
127  }
129  $this->revisionGetTimestampFromIdCallback = $callback;
130  return new ScopedCallback( function() use ( $previousValue ) {
131  $this->revisionGetTimestampFromIdCallback = $previousValue;
132  } );
133  }
134 
135  private function getCacheKey( User $user, LinkTarget $target ) {
136  return $this->cache->makeKey(
137  (string)$target->getNamespace(),
138  $target->getDBkey(),
139  (string)$user->getId()
140  );
141  }
142 
143  private function cache( WatchedItem $item ) {
144  $user = $item->getUser();
145  $target = $item->getLinkTarget();
146  $key = $this->getCacheKey( $user, $target );
147  $this->cache->set( $key, $item );
148  $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
149  $this->stats->increment( 'WatchedItemStore.cache' );
150  }
151 
152  private function uncache( User $user, LinkTarget $target ) {
153  $this->cache->delete( $this->getCacheKey( $user, $target ) );
154  unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
155  $this->stats->increment( 'WatchedItemStore.uncache' );
156  }
157 
158  private function uncacheLinkTarget( LinkTarget $target ) {
159  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
160  if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
161  return;
162  }
163  foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
164  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
165  $this->cache->delete( $key );
166  }
167  }
168 
169  private function uncacheUser( User $user ) {
170  $this->stats->increment( 'WatchedItemStore.uncacheUser' );
171  foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
172  foreach ( $dbKeyArray as $dbKey => $userArray ) {
173  if ( isset( $userArray[$user->getId()] ) ) {
174  $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
175  $this->cache->delete( $userArray[$user->getId()] );
176  }
177  }
178  }
179  }
180 
187  private function getCached( User $user, LinkTarget $target ) {
188  return $this->cache->get( $this->getCacheKey( $user, $target ) );
189  }
190 
200  private function dbCond( User $user, LinkTarget $target ) {
201  return [
202  'wl_user' => $user->getId(),
203  'wl_namespace' => $target->getNamespace(),
204  'wl_title' => $target->getDBkey(),
205  ];
206  }
207 
214  private function getConnectionRef( $dbIndex ) {
215  return $this->loadBalancer->getConnectionRef( $dbIndex, [ 'watchlist' ] );
216  }
217 
226  public function countWatchedItems( User $user ) {
227  $dbr = $this->getConnectionRef( DB_REPLICA );
228  $return = (int)$dbr->selectField(
229  'watchlist',
230  'COUNT(*)',
231  [
232  'wl_user' => $user->getId()
233  ],
234  __METHOD__
235  );
236 
237  return $return;
238  }
239 
245  public function countWatchers( LinkTarget $target ) {
246  $dbr = $this->getConnectionRef( DB_REPLICA );
247  $return = (int)$dbr->selectField(
248  'watchlist',
249  'COUNT(*)',
250  [
251  'wl_namespace' => $target->getNamespace(),
252  'wl_title' => $target->getDBkey(),
253  ],
254  __METHOD__
255  );
256 
257  return $return;
258  }
259 
270  public function countVisitingWatchers( LinkTarget $target, $threshold ) {
271  $dbr = $this->getConnectionRef( DB_REPLICA );
272  $visitingWatchers = (int)$dbr->selectField(
273  'watchlist',
274  'COUNT(*)',
275  [
276  'wl_namespace' => $target->getNamespace(),
277  'wl_title' => $target->getDBkey(),
278  'wl_notificationtimestamp >= ' .
279  $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
280  ' OR wl_notificationtimestamp IS NULL'
281  ],
282  __METHOD__
283  );
284 
285  return $visitingWatchers;
286  }
287 
297  public function countWatchersMultiple( array $targets, array $options = [] ) {
298  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
299 
300  $dbr = $this->getConnectionRef( DB_REPLICA );
301 
302  if ( array_key_exists( 'minimumWatchers', $options ) ) {
303  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
304  }
305 
306  $lb = new LinkBatch( $targets );
307  $res = $dbr->select(
308  'watchlist',
309  [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
310  [ $lb->constructSet( 'wl', $dbr ) ],
311  __METHOD__,
312  $dbOptions
313  );
314 
315  $watchCounts = [];
316  foreach ( $targets as $linkTarget ) {
317  $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
318  }
319 
320  foreach ( $res as $row ) {
321  $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
322  }
323 
324  return $watchCounts;
325  }
326 
343  array $targetsWithVisitThresholds,
344  $minimumWatchers = null
345  ) {
346  $dbr = $this->getConnectionRef( DB_REPLICA );
347 
348  $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
349 
350  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
351  if ( $minimumWatchers !== null ) {
352  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
353  }
354  $res = $dbr->select(
355  'watchlist',
356  [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
357  $conds,
358  __METHOD__,
359  $dbOptions
360  );
361 
362  $watcherCounts = [];
363  foreach ( $targetsWithVisitThresholds as list( $target ) ) {
364  /* @var LinkTarget $target */
365  $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
366  }
367 
368  foreach ( $res as $row ) {
369  $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
370  }
371 
372  return $watcherCounts;
373  }
374 
383  IDatabase $db,
384  array $targetsWithVisitThresholds
385  ) {
386  $missingTargets = [];
387  $namespaceConds = [];
388  foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
389  if ( $threshold === null ) {
390  $missingTargets[] = $target;
391  continue;
392  }
393  /* @var LinkTarget $target */
394  $namespaceConds[$target->getNamespace()][] = $db->makeList( [
395  'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
396  $db->makeList( [
397  'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
398  'wl_notificationtimestamp IS NULL'
399  ], LIST_OR )
400  ], LIST_AND );
401  }
402 
403  $conds = [];
404  foreach ( $namespaceConds as $namespace => $pageConds ) {
405  $conds[] = $db->makeList( [
406  'wl_namespace = ' . $namespace,
407  '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
408  ], LIST_AND );
409  }
410 
411  if ( $missingTargets ) {
412  $lb = new LinkBatch( $missingTargets );
413  $conds[] = $lb->constructSet( 'wl', $db );
414  }
415 
416  return $db->makeList( $conds, LIST_OR );
417  }
418 
427  public function getWatchedItem( User $user, LinkTarget $target ) {
428  if ( $user->isAnon() ) {
429  return false;
430  }
431 
432  $cached = $this->getCached( $user, $target );
433  if ( $cached ) {
434  $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
435  return $cached;
436  }
437  $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
438  return $this->loadWatchedItem( $user, $target );
439  }
440 
449  public function loadWatchedItem( User $user, LinkTarget $target ) {
450  // Only loggedin user can have a watchlist
451  if ( $user->isAnon() ) {
452  return false;
453  }
454 
455  $dbr = $this->getConnectionRef( DB_REPLICA );
456  $row = $dbr->selectRow(
457  'watchlist',
458  'wl_notificationtimestamp',
459  $this->dbCond( $user, $target ),
460  __METHOD__
461  );
462 
463  if ( !$row ) {
464  return false;
465  }
466 
467  $item = new WatchedItem(
468  $user,
469  $target,
470  $row->wl_notificationtimestamp
471  );
472  $this->cache( $item );
473 
474  return $item;
475  }
476 
486  public function getWatchedItemsForUser( User $user, array $options = [] ) {
487  $options += [ 'forWrite' => false ];
488 
489  $dbOptions = [];
490  if ( array_key_exists( 'sort', $options ) ) {
491  Assert::parameter(
492  ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
493  '$options[\'sort\']',
494  'must be SORT_ASC or SORT_DESC'
495  );
496  $dbOptions['ORDER BY'] = [
497  "wl_namespace {$options['sort']}",
498  "wl_title {$options['sort']}"
499  ];
500  }
501  $db = $this->getConnectionRef( $options['forWrite'] ? DB_MASTER : DB_REPLICA );
502 
503  $res = $db->select(
504  'watchlist',
505  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
506  [ 'wl_user' => $user->getId() ],
507  __METHOD__,
508  $dbOptions
509  );
510 
511  $watchedItems = [];
512  foreach ( $res as $row ) {
513  // @todo: Should we add these to the process cache?
514  $watchedItems[] = new WatchedItem(
515  $user,
516  new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
517  $row->wl_notificationtimestamp
518  );
519  }
520 
521  return $watchedItems;
522  }
523 
532  public function isWatched( User $user, LinkTarget $target ) {
533  return (bool)$this->getWatchedItem( $user, $target );
534  }
535 
545  public function getNotificationTimestampsBatch( User $user, array $targets ) {
546  $timestamps = [];
547  foreach ( $targets as $target ) {
548  $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
549  }
550 
551  if ( $user->isAnon() ) {
552  return $timestamps;
553  }
554 
555  $targetsToLoad = [];
556  foreach ( $targets as $target ) {
557  $cachedItem = $this->getCached( $user, $target );
558  if ( $cachedItem ) {
559  $timestamps[$target->getNamespace()][$target->getDBkey()] =
560  $cachedItem->getNotificationTimestamp();
561  } else {
562  $targetsToLoad[] = $target;
563  }
564  }
565 
566  if ( !$targetsToLoad ) {
567  return $timestamps;
568  }
569 
570  $dbr = $this->getConnectionRef( DB_REPLICA );
571 
572  $lb = new LinkBatch( $targetsToLoad );
573  $res = $dbr->select(
574  'watchlist',
575  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
576  [
577  $lb->constructSet( 'wl', $dbr ),
578  'wl_user' => $user->getId(),
579  ],
580  __METHOD__
581  );
582 
583  foreach ( $res as $row ) {
584  $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
585  }
586 
587  return $timestamps;
588  }
589 
596  public function addWatch( User $user, LinkTarget $target ) {
597  $this->addWatchBatchForUser( $user, [ $target ] );
598  }
599 
606  public function addWatchBatchForUser( User $user, array $targets ) {
607  if ( $this->readOnlyMode->isReadOnly() ) {
608  return false;
609  }
610  // Only loggedin user can have a watchlist
611  if ( $user->isAnon() ) {
612  return false;
613  }
614 
615  if ( !$targets ) {
616  return true;
617  }
618 
619  $rows = [];
620  $items = [];
621  foreach ( $targets as $target ) {
622  $rows[] = [
623  'wl_user' => $user->getId(),
624  'wl_namespace' => $target->getNamespace(),
625  'wl_title' => $target->getDBkey(),
626  'wl_notificationtimestamp' => null,
627  ];
628  $items[] = new WatchedItem(
629  $user,
630  $target,
631  null
632  );
633  $this->uncache( $user, $target );
634  }
635 
636  $dbw = $this->getConnectionRef( DB_MASTER );
637  foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
638  // Use INSERT IGNORE to avoid overwriting the notification timestamp
639  // if there's already an entry for this page
640  $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
641  }
642  // Update process cache to ensure skin doesn't claim that the current
643  // page is unwatched in the response of action=watch itself (T28292).
644  // This would otherwise be re-queried from a slave by isWatched().
645  foreach ( $items as $item ) {
646  $this->cache( $item );
647  }
648 
649  return true;
650  }
651 
663  public function removeWatch( User $user, LinkTarget $target ) {
664  // Only logged in user can have a watchlist
665  if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
666  return false;
667  }
668 
669  $this->uncache( $user, $target );
670 
671  $dbw = $this->getConnectionRef( DB_MASTER );
672  $dbw->delete( 'watchlist',
673  [
674  'wl_user' => $user->getId(),
675  'wl_namespace' => $target->getNamespace(),
676  'wl_title' => $target->getDBkey(),
677  ], __METHOD__
678  );
679  $success = (bool)$dbw->affectedRows();
680 
681  return $success;
682  }
683 
691  public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
692  // Only loggedin user can have a watchlist
693  if ( $user->isAnon() ) {
694  return false;
695  }
696 
697  $dbw = $this->getConnectionRef( DB_MASTER );
698 
699  $conds = [ 'wl_user' => $user->getId() ];
700  if ( $targets ) {
701  $batch = new LinkBatch( $targets );
702  $conds[] = $batch->constructSet( 'wl', $dbw );
703  }
704 
705  if ( $timestamp !== null ) {
706  $timestamp = $dbw->timestamp( $timestamp );
707  }
708 
709  $success = $dbw->update(
710  'watchlist',
711  [ 'wl_notificationtimestamp' => $timestamp ],
712  $conds,
713  __METHOD__
714  );
715 
716  $this->uncacheUser( $user );
717 
718  return $success;
719  }
720 
729  public function updateNotificationTimestamp( User $editor, LinkTarget $target, $timestamp ) {
730  $dbw = $this->getConnectionRef( DB_MASTER );
731  $uids = $dbw->selectFieldValues(
732  'watchlist',
733  'wl_user',
734  [
735  'wl_user != ' . intval( $editor->getId() ),
736  'wl_namespace' => $target->getNamespace(),
737  'wl_title' => $target->getDBkey(),
738  'wl_notificationtimestamp IS NULL',
739  ],
740  __METHOD__
741  );
742 
743  $watchers = array_map( 'intval', $uids );
744  if ( $watchers ) {
745  // Update wl_notificationtimestamp for all watching users except the editor
746  $fname = __METHOD__;
748  function () use ( $timestamp, $watchers, $target, $fname ) {
749  global $wgUpdateRowsPerQuery;
750 
751  $dbw = $this->getConnectionRef( DB_MASTER );
752  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
753  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
754 
755  $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
756  foreach ( $watchersChunks as $watchersChunk ) {
757  $dbw->update( 'watchlist',
758  [ /* SET */
759  'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
760  ], [ /* WHERE - TODO Use wl_id T130067 */
761  'wl_user' => $watchersChunk,
762  'wl_namespace' => $target->getNamespace(),
763  'wl_title' => $target->getDBkey(),
764  ], $fname
765  );
766  if ( count( $watchersChunks ) > 1 ) {
767  $factory->commitAndWaitForReplication(
768  __METHOD__, $ticket, [ 'wiki' => $dbw->getWikiID() ]
769  );
770  }
771  }
772  $this->uncacheLinkTarget( $target );
773  },
775  $dbw
776  );
777  }
778 
779  return $watchers;
780  }
781 
794  public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
795  // Only loggedin user can have a watchlist
796  if ( $this->readOnlyMode->isReadOnly() || $user->isAnon() ) {
797  return false;
798  }
799 
800  $item = null;
801  if ( $force != 'force' ) {
802  $item = $this->loadWatchedItem( $user, $title );
803  if ( !$item || $item->getNotificationTimestamp() === null ) {
804  return false;
805  }
806  }
807 
808  // If the page is watched by the user (or may be watched), update the timestamp
809  $job = new ActivityUpdateJob(
810  $title,
811  [
812  'type' => 'updateWatchlistNotification',
813  'userid' => $user->getId(),
814  'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
815  'curTime' => time()
816  ]
817  );
818 
819  // Try to run this post-send
820  // Calls DeferredUpdates::addCallableUpdate in normal operation
821  call_user_func(
822  $this->deferredUpdatesAddCallableUpdateCallback,
823  function() use ( $job ) {
824  $job->run();
825  }
826  );
827 
828  $this->uncache( $user, $title );
829 
830  return true;
831  }
832 
833  private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
834  if ( !$oldid ) {
835  // No oldid given, assuming latest revision; clear the timestamp.
836  return null;
837  }
838 
839  if ( !$title->getNextRevisionID( $oldid ) ) {
840  // Oldid given and is the latest revision for this title; clear the timestamp.
841  return null;
842  }
843 
844  if ( $item === null ) {
845  $item = $this->loadWatchedItem( $user, $title );
846  }
847 
848  if ( !$item ) {
849  // This can only happen if $force is enabled.
850  return null;
851  }
852 
853  // Oldid given and isn't the latest; update the timestamp.
854  // This will result in no further notification emails being sent!
855  // Calls Revision::getTimestampFromId in normal operation
856  $notificationTimestamp = call_user_func(
857  $this->revisionGetTimestampFromIdCallback,
858  $title,
859  $oldid
860  );
861 
862  // We need to go one second to the future because of various strict comparisons
863  // throughout the codebase
864  $ts = new MWTimestamp( $notificationTimestamp );
865  $ts->timestamp->add( new DateInterval( 'PT1S' ) );
866  $notificationTimestamp = $ts->getTimestamp( TS_MW );
867 
868  if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
869  if ( $force != 'force' ) {
870  return false;
871  } else {
872  // This is a little silly…
873  return $item->getNotificationTimestamp();
874  }
875  }
876 
877  return $notificationTimestamp;
878  }
879 
887  public function countUnreadNotifications( User $user, $unreadLimit = null ) {
888  $queryOptions = [];
889  if ( $unreadLimit !== null ) {
890  $unreadLimit = (int)$unreadLimit;
891  $queryOptions['LIMIT'] = $unreadLimit;
892  }
893 
894  $dbr = $this->getConnectionRef( DB_REPLICA );
895  $rowCount = $dbr->selectRowCount(
896  'watchlist',
897  '1',
898  [
899  'wl_user' => $user->getId(),
900  'wl_notificationtimestamp IS NOT NULL',
901  ],
902  __METHOD__,
903  $queryOptions
904  );
905 
906  if ( !isset( $unreadLimit ) ) {
907  return $rowCount;
908  }
909 
910  if ( $rowCount >= $unreadLimit ) {
911  return true;
912  }
913 
914  return $rowCount;
915  }
916 
926  public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
927  $oldTarget = Title::newFromLinkTarget( $oldTarget );
928  $newTarget = Title::newFromLinkTarget( $newTarget );
929 
930  $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
931  $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
932  }
933 
944  public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
945  $dbw = $this->getConnectionRef( DB_MASTER );
946 
947  $result = $dbw->select(
948  'watchlist',
949  [ 'wl_user', 'wl_notificationtimestamp' ],
950  [
951  'wl_namespace' => $oldTarget->getNamespace(),
952  'wl_title' => $oldTarget->getDBkey(),
953  ],
954  __METHOD__,
955  [ 'FOR UPDATE' ]
956  );
957 
958  $newNamespace = $newTarget->getNamespace();
959  $newDBkey = $newTarget->getDBkey();
960 
961  # Construct array to replace into the watchlist
962  $values = [];
963  foreach ( $result as $row ) {
964  $values[] = [
965  'wl_user' => $row->wl_user,
966  'wl_namespace' => $newNamespace,
967  'wl_title' => $newDBkey,
968  'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
969  ];
970  }
971 
972  if ( !empty( $values ) ) {
973  # Perform replace
974  # Note that multi-row replace is very efficient for MySQL but may be inefficient for
975  # some other DBMSes, mostly due to poor simulation by us
976  $dbw->replace(
977  'watchlist',
978  [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
979  $values,
980  __METHOD__
981  );
982  }
983  }
984 
985 }
WatchedItemStore\getNotificationTimestampsBatch
getNotificationTimestampsBatch(User $user, array $targets)
Definition: WatchedItemStore.php:545
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:32
WatchedItemStore\countUnreadNotifications
countUnreadNotifications(User $user, $unreadLimit=null)
Definition: WatchedItemStore.php:887
WatchedItemStore\overrideRevisionGetTimestampFromIdCallback
overrideRevisionGetTimestampFromIdCallback(callable $callback)
Overrides the Revision::getTimestampFromId callback This is intended for use while testing and will f...
Definition: WatchedItemStore.php:122
ActivityUpdateJob
Job for updating user activity like "last viewed" timestamps.
Definition: ActivityUpdateJob.php:29
WatchedItemStore\addWatch
addWatch(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
Definition: WatchedItemStore.php:596
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
Wikimedia\Rdbms\IDatabase\makeList
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
captcha-old.count
count
Definition: captcha-old.py:225
WatchedItemStore\getVisitingWatchersCondition
getVisitingWatchersCondition(IDatabase $db, array $targetsWithVisitThresholds)
Generates condition for the query used in a batch count visiting watchers.
Definition: WatchedItemStore.php:382
WatchedItemStore\removeWatch
removeWatch(User $user, LinkTarget $target)
Removes the an entry for the User watching the LinkTarget Must be called separately for Subject & Tal...
Definition: WatchedItemStore.php:663
WatchedItemStore\getWatchedItem
getWatchedItem(User $user, LinkTarget $target)
Get an item (may be cached)
Definition: WatchedItemStore.php:427
$result
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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1954
ReadOnlyMode
A service class for fetching the wiki's current read-only mode.
Definition: ReadOnlyMode.php:11
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
WatchedItemStore\countVisitingWatchers
countVisitingWatchers(LinkTarget $target, $threshold)
Number of page watchers who also visited a "recent" edit.
Definition: WatchedItemStore.php:270
$fname
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition: Setup.php:36
NullStatsdDataFactory
Definition: NullStatsdDataFactory.php:11
WatchedItemStore\duplicateAllAssociatedEntries
duplicateAllAssociatedEntries(LinkTarget $oldTarget, LinkTarget $newTarget)
Check if the given title already is watched by the user, and if so add a watch for the new title.
Definition: WatchedItemStore.php:926
WatchedItemStore\uncacheUser
uncacheUser(User $user)
Definition: WatchedItemStore.php:169
$res
$res
Definition: database.txt:21
WatchedItemStore\$loadBalancer
LoadBalancer $loadBalancer
Definition: WatchedItemStore.php:31
$success
$success
Definition: NoLocalSettings.php:44
WatchedItemStore\$cache
HashBagOStuff $cache
Definition: WatchedItemStore.php:41
php
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
LIST_AND
const LIST_AND
Definition: Defines.php:41
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
WatchedItemStore\updateNotificationTimestamp
updateNotificationTimestamp(User $editor, LinkTarget $target, $timestamp)
Definition: WatchedItemStore.php:729
WatchedItemStore\resetNotificationTimestamp
resetNotificationTimestamp(User $user, Title $title, $force='', $oldid=0)
Reset the notification timestamp of this entry.
Definition: WatchedItemStore.php:794
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:111
WatchedItemStore\$readOnlyMode
ReadOnlyMode $readOnlyMode
Definition: WatchedItemStore.php:36
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
LIST_OR
const LIST_OR
Definition: Defines.php:44
WatchedItemStore\overrideDeferredUpdatesAddCallableUpdateCallback
overrideDeferredUpdatesAddCallableUpdateCallback(callable $callback)
Overrides the DeferredUpdates::addCallableUpdate callback This is intended for use while testing and ...
Definition: WatchedItemStore.php:99
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
WatchedItemStore\__construct
__construct(LoadBalancer $loadBalancer, HashBagOStuff $cache, ReadOnlyMode $readOnlyMode)
Definition: WatchedItemStore.php:71
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition: Title.php:239
WatchedItemStore\duplicateEntry
duplicateEntry(LinkTarget $oldTarget, LinkTarget $newTarget)
Check if the given title already is watched by the user, and if so add a watch for the new title.
Definition: WatchedItemStore.php:944
DeferredUpdates\POSTSEND
const POSTSEND
Definition: DeferredUpdates.php:61
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
WatchedItemStore\addWatchBatchForUser
addWatchBatchForUser(User $user, array $targets)
Definition: WatchedItemStore.php:606
DB_MASTER
const DB_MASTER
Definition: defines.php:26
$editor
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:1252
WatchedItemStore\uncacheLinkTarget
uncacheLinkTarget(LinkTarget $target)
Definition: WatchedItemStore.php:158
string
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:177
list
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
WatchedItem\getUser
getUser()
Definition: WatchedItem.php:99
WatchedItemStore\getConnectionRef
getConnectionRef( $dbIndex)
Definition: WatchedItemStore.php:214
WatchedItemStore\$deferredUpdatesAddCallableUpdateCallback
callable null $deferredUpdatesAddCallableUpdateCallback
Definition: WatchedItemStore.php:54
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
WatchedItemStore\uncache
uncache(User $user, LinkTarget $target)
Definition: WatchedItemStore.php:152
WatchedItemStore\dbCond
dbCond(User $user, LinkTarget $target)
Return an array of conditions to select or update the appropriate database row.
Definition: WatchedItemStore.php:200
StatsdAwareInterface
Describes a Statsd aware interface.
Definition: StatsdAwareInterface.php:11
WatchedItemStore\$cacheIndex
array[] $cacheIndex
Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key' The index is needed so that on ...
Definition: WatchedItemStore.php:49
WatchedItem
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:32
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
WatchedItemStore\setNotificationTimestampsForUser
setNotificationTimestampsForUser(User $user, $timestamp, array $targets=[])
Definition: WatchedItemStore.php:691
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
WatchedItemStore
Storage layer class for WatchedItems.
Definition: WatchedItemStore.php:23
WatchedItemStore\countWatchedItems
countWatchedItems(User $user)
Count the number of individual items that are watched by the user.
Definition: WatchedItemStore.php:226
Title
Represents a title within MediaWiki.
Definition: Title.php:39
WatchedItemStore\getWatchedItemsForUser
getWatchedItemsForUser(User $user, array $options=[])
Definition: WatchedItemStore.php:486
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
Wikimedia\Rdbms\IDatabase\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
WatchedItemStore\$stats
StatsdDataFactoryInterface $stats
Definition: WatchedItemStore.php:64
WatchedItemStore\countWatchers
countWatchers(LinkTarget $target)
Definition: WatchedItemStore.php:245
WatchedItemStore\loadWatchedItem
loadWatchedItem(User $user, LinkTarget $target)
Loads an item from the db.
Definition: WatchedItemStore.php:449
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:47
WatchedItemStore\SORT_DESC
const SORT_DESC
Definition: WatchedItemStore.php:25
as
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
WatchedItemStore\getCached
getCached(User $user, LinkTarget $target)
Definition: WatchedItemStore.php:187
WatchedItem\getLinkTarget
getLinkTarget()
Definition: WatchedItem.php:106
WatchedItemStore\countVisitingWatchersMultiple
countVisitingWatchersMultiple(array $targetsWithVisitThresholds, $minimumWatchers=null)
Number of watchers of each page who have visited recent edits to that page.
Definition: WatchedItemStore.php:342
WatchedItemStore\setStatsdDataFactory
setStatsdDataFactory(StatsdDataFactoryInterface $stats)
Sets a StatsdDataFactory instance on the object.
Definition: WatchedItemStore.php:84
$batch
$batch
Definition: linkcache.txt:23
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:27
WatchedItemStore\isWatched
isWatched(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
Definition: WatchedItemStore.php:532
WatchedItemStore\$revisionGetTimestampFromIdCallback
callable null $revisionGetTimestampFromIdCallback
Definition: WatchedItemStore.php:59
WatchedItemStore\getNotificationTimestamp
getNotificationTimestamp(User $user, Title $title, $item, $force, $oldid)
Definition: WatchedItemStore.php:833
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
WatchedItemStore\getCacheKey
getCacheKey(User $user, LinkTarget $target)
Definition: WatchedItemStore.php:135
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
WatchedItemStore\countWatchersMultiple
countWatchersMultiple(array $targets, array $options=[])
Definition: WatchedItemStore.php:297
array
the array() calling protocol came about after MediaWiki 1.4rc1.
WatchedItemStore\cache
cache(WatchedItem $item)
Definition: WatchedItemStore.php:143
TitleValue
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:36
WatchedItemStore\SORT_ASC
const SORT_ASC
Definition: WatchedItemStore.php:26