MediaWiki  master
WatchedItemStore.php
Go to the documentation of this file.
1 <?php
2 
3 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
5 use Wikimedia\Assert\Assert;
6 
16 
17  const SORT_DESC = 'DESC';
18  const SORT_ASC = 'ASC';
19 
23  private $loadBalancer;
24 
28  private $cache;
29 
36  private $cacheIndex = [];
37 
42 
47 
51  private $stats;
52 
57  public function __construct(
60  ) {
61  $this->loadBalancer = $loadBalancer;
62  $this->cache = $cache;
63  $this->stats = new NullStatsdDataFactory();
64  $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
65  $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
66  }
67 
68  public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
69  $this->stats = $stats;
70  }
71 
83  public function overrideDeferredUpdatesAddCallableUpdateCallback( callable $callback ) {
84  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
85  throw new MWException(
86  'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
87  );
88  }
90  $this->deferredUpdatesAddCallableUpdateCallback = $callback;
91  return new ScopedCallback( function() use ( $previousValue ) {
92  $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
93  } );
94  }
95 
106  public function overrideRevisionGetTimestampFromIdCallback( callable $callback ) {
107  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
108  throw new MWException(
109  'Cannot override Revision::getTimestampFromId callback in operation.'
110  );
111  }
113  $this->revisionGetTimestampFromIdCallback = $callback;
114  return new ScopedCallback( function() use ( $previousValue ) {
115  $this->revisionGetTimestampFromIdCallback = $previousValue;
116  } );
117  }
118 
119  private function getCacheKey( User $user, LinkTarget $target ) {
120  return $this->cache->makeKey(
121  (string)$target->getNamespace(),
122  $target->getDBkey(),
123  (string)$user->getId()
124  );
125  }
126 
127  private function cache( WatchedItem $item ) {
128  $user = $item->getUser();
129  $target = $item->getLinkTarget();
130  $key = $this->getCacheKey( $user, $target );
131  $this->cache->set( $key, $item );
132  $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
133  $this->stats->increment( 'WatchedItemStore.cache' );
134  }
135 
136  private function uncache( User $user, LinkTarget $target ) {
137  $this->cache->delete( $this->getCacheKey( $user, $target ) );
138  unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
139  $this->stats->increment( 'WatchedItemStore.uncache' );
140  }
141 
142  private function uncacheLinkTarget( LinkTarget $target ) {
143  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
144  if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
145  return;
146  }
147  foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
148  $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
149  $this->cache->delete( $key );
150  }
151  }
152 
153  private function uncacheUser( User $user ) {
154  $this->stats->increment( 'WatchedItemStore.uncacheUser' );
155  foreach ( $this->cacheIndex as $ns => $dbKeyArray ) {
156  foreach ( $dbKeyArray as $dbKey => $userArray ) {
157  if ( isset( $userArray[$user->getId()] ) ) {
158  $this->stats->increment( 'WatchedItemStore.uncacheUser.items' );
159  $this->cache->delete( $userArray[$user->getId()] );
160  }
161  }
162  }
163  }
164 
171  private function getCached( User $user, LinkTarget $target ) {
172  return $this->cache->get( $this->getCacheKey( $user, $target ) );
173  }
174 
184  private function dbCond( User $user, LinkTarget $target ) {
185  return [
186  'wl_user' => $user->getId(),
187  'wl_namespace' => $target->getNamespace(),
188  'wl_title' => $target->getDBkey(),
189  ];
190  }
191 
198  private function getConnection( $slaveOrMaster ) {
199  return $this->loadBalancer->getConnection( $slaveOrMaster, [ 'watchlist' ] );
200  }
201 
207  private function reuseConnection( $connection ) {
208  $this->loadBalancer->reuseConnection( $connection );
209  }
210 
219  public function countWatchedItems( User $user ) {
220  $dbr = $this->getConnection( DB_SLAVE );
221  $return = (int)$dbr->selectField(
222  'watchlist',
223  'COUNT(*)',
224  [
225  'wl_user' => $user->getId()
226  ],
227  __METHOD__
228  );
229  $this->reuseConnection( $dbr );
230 
231  return $return;
232  }
233 
239  public function countWatchers( LinkTarget $target ) {
240  $dbr = $this->getConnection( DB_SLAVE );
241  $return = (int)$dbr->selectField(
242  'watchlist',
243  'COUNT(*)',
244  [
245  'wl_namespace' => $target->getNamespace(),
246  'wl_title' => $target->getDBkey(),
247  ],
248  __METHOD__
249  );
250  $this->reuseConnection( $dbr );
251 
252  return $return;
253  }
254 
265  public function countVisitingWatchers( LinkTarget $target, $threshold ) {
266  $dbr = $this->getConnection( DB_SLAVE );
267  $visitingWatchers = (int)$dbr->selectField(
268  'watchlist',
269  'COUNT(*)',
270  [
271  'wl_namespace' => $target->getNamespace(),
272  'wl_title' => $target->getDBkey(),
273  'wl_notificationtimestamp >= ' .
274  $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
275  ' OR wl_notificationtimestamp IS NULL'
276  ],
277  __METHOD__
278  );
279  $this->reuseConnection( $dbr );
280 
281  return $visitingWatchers;
282  }
283 
293  public function countWatchersMultiple( array $targets, array $options = [] ) {
294  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
295 
296  $dbr = $this->getConnection( DB_SLAVE );
297 
298  if ( array_key_exists( 'minimumWatchers', $options ) ) {
299  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
300  }
301 
302  $lb = new LinkBatch( $targets );
303  $res = $dbr->select(
304  'watchlist',
305  [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
306  [ $lb->constructSet( 'wl', $dbr ) ],
307  __METHOD__,
308  $dbOptions
309  );
310 
311  $this->reuseConnection( $dbr );
312 
313  $watchCounts = [];
314  foreach ( $targets as $linkTarget ) {
315  $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
316  }
317 
318  foreach ( $res as $row ) {
319  $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
320  }
321 
322  return $watchCounts;
323  }
324 
341  array $targetsWithVisitThresholds,
342  $minimumWatchers = null
343  ) {
344  $dbr = $this->getConnection( DB_SLAVE );
345 
346  $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
347 
348  $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
349  if ( $minimumWatchers !== null ) {
350  $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
351  }
352  $res = $dbr->select(
353  'watchlist',
354  [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
355  $conds,
356  __METHOD__,
357  $dbOptions
358  );
359 
360  $this->reuseConnection( $dbr );
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->getConnection( DB_SLAVE );
456  $row = $dbr->selectRow(
457  'watchlist',
458  'wl_notificationtimestamp',
459  $this->dbCond( $user, $target ),
460  __METHOD__
461  );
462  $this->reuseConnection( $dbr );
463 
464  if ( !$row ) {
465  return false;
466  }
467 
468  $item = new WatchedItem(
469  $user,
470  $target,
471  $row->wl_notificationtimestamp
472  );
473  $this->cache( $item );
474 
475  return $item;
476  }
477 
487  public function getWatchedItemsForUser( User $user, array $options = [] ) {
488  $options += [ 'forWrite' => false ];
489 
490  $dbOptions = [];
491  if ( array_key_exists( 'sort', $options ) ) {
492  Assert::parameter(
493  ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
494  '$options[\'sort\']',
495  'must be SORT_ASC or SORT_DESC'
496  );
497  $dbOptions['ORDER BY'] = [
498  "wl_namespace {$options['sort']}",
499  "wl_title {$options['sort']}"
500  ];
501  }
502  $db = $this->getConnection( $options['forWrite'] ? DB_MASTER : DB_SLAVE );
503 
504  $res = $db->select(
505  'watchlist',
506  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
507  [ 'wl_user' => $user->getId() ],
508  __METHOD__,
509  $dbOptions
510  );
511  $this->reuseConnection( $db );
512 
513  $watchedItems = [];
514  foreach ( $res as $row ) {
515  // todo these could all be cached at some point?
516  $watchedItems[] = new WatchedItem(
517  $user,
518  new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
519  $row->wl_notificationtimestamp
520  );
521  }
522 
523  return $watchedItems;
524  }
525 
534  public function isWatched( User $user, LinkTarget $target ) {
535  return (bool)$this->getWatchedItem( $user, $target );
536  }
537 
547  public function getNotificationTimestampsBatch( User $user, array $targets ) {
548  $timestamps = [];
549  foreach ( $targets as $target ) {
550  $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
551  }
552 
553  if ( $user->isAnon() ) {
554  return $timestamps;
555  }
556 
557  $targetsToLoad = [];
558  foreach ( $targets as $target ) {
559  $cachedItem = $this->getCached( $user, $target );
560  if ( $cachedItem ) {
561  $timestamps[$target->getNamespace()][$target->getDBkey()] =
562  $cachedItem->getNotificationTimestamp();
563  } else {
564  $targetsToLoad[] = $target;
565  }
566  }
567 
568  if ( !$targetsToLoad ) {
569  return $timestamps;
570  }
571 
572  $dbr = $this->getConnection( DB_SLAVE );
573 
574  $lb = new LinkBatch( $targetsToLoad );
575  $res = $dbr->select(
576  'watchlist',
577  [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
578  [
579  $lb->constructSet( 'wl', $dbr ),
580  'wl_user' => $user->getId(),
581  ],
582  __METHOD__
583  );
584  $this->reuseConnection( $dbr );
585 
586  foreach ( $res as $row ) {
587  $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
588  }
589 
590  return $timestamps;
591  }
592 
599  public function addWatch( User $user, LinkTarget $target ) {
600  $this->addWatchBatchForUser( $user, [ $target ] );
601  }
602 
609  public function addWatchBatchForUser( User $user, array $targets ) {
610  if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
611  return false;
612  }
613  // Only loggedin user can have a watchlist
614  if ( $user->isAnon() ) {
615  return false;
616  }
617 
618  if ( !$targets ) {
619  return true;
620  }
621 
622  $rows = [];
623  foreach ( $targets as $target ) {
624  $rows[] = [
625  'wl_user' => $user->getId(),
626  'wl_namespace' => $target->getNamespace(),
627  'wl_title' => $target->getDBkey(),
628  'wl_notificationtimestamp' => null,
629  ];
630  $this->uncache( $user, $target );
631  }
632 
633  $dbw = $this->getConnection( DB_MASTER );
634  foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
635  // Use INSERT IGNORE to avoid overwriting the notification timestamp
636  // if there's already an entry for this page
637  $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
638  }
639  $this->reuseConnection( $dbw );
640 
641  return true;
642  }
643 
655  public function removeWatch( User $user, LinkTarget $target ) {
656  // Only logged in user can have a watchlist
657  if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
658  return false;
659  }
660 
661  $this->uncache( $user, $target );
662 
663  $dbw = $this->getConnection( DB_MASTER );
664  $dbw->delete( 'watchlist',
665  [
666  'wl_user' => $user->getId(),
667  'wl_namespace' => $target->getNamespace(),
668  'wl_title' => $target->getDBkey(),
669  ], __METHOD__
670  );
671  $success = (bool)$dbw->affectedRows();
672  $this->reuseConnection( $dbw );
673 
674  return $success;
675  }
676 
684  public function setNotificationTimestampsForUser( User $user, $timestamp, array $targets = [] ) {
685  // Only loggedin user can have a watchlist
686  if ( $user->isAnon() ) {
687  return false;
688  }
689 
690  $dbw = $this->getConnection( DB_MASTER );
691 
692  $conds = [ 'wl_user' => $user->getId() ];
693  if ( $targets ) {
694  $batch = new LinkBatch( $targets );
695  $conds[] = $batch->constructSet( 'wl', $dbw );
696  }
697 
698  $success = $dbw->update(
699  'watchlist',
700  [ 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp ) ],
701  $conds,
702  __METHOD__
703  );
704 
705  $this->reuseConnection( $dbw );
706 
707  $this->uncacheUser( $user );
708 
709  return $success;
710  }
711 
721  $dbw = $this->getConnection( DB_MASTER );
722  $uids = $dbw->selectFieldValues(
723  'watchlist',
724  'wl_user',
725  [
726  'wl_user != ' . intval( $editor->getId() ),
727  'wl_namespace' => $target->getNamespace(),
728  'wl_title' => $target->getDBkey(),
729  'wl_notificationtimestamp IS NULL',
730  ],
731  __METHOD__
732  );
733  $this->reuseConnection( $dbw );
734 
735  $watchers = array_map( 'intval', $uids );
736  if ( $watchers ) {
737  // Update wl_notificationtimestamp for all watching users except the editor
738  $fname = __METHOD__;
740  function () use ( $timestamp, $watchers, $target, $fname ) {
742 
743  $dbw = $this->getConnection( DB_MASTER );
744 
745  $watchersChunks = array_chunk( $watchers, $wgUpdateRowsPerQuery );
746  foreach ( $watchersChunks as $watchersChunk ) {
747  $dbw->update( 'watchlist',
748  [ /* SET */
749  'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
750  ], [ /* WHERE - TODO Use wl_id T130067 */
751  'wl_user' => $watchersChunk,
752  'wl_namespace' => $target->getNamespace(),
753  'wl_title' => $target->getDBkey(),
754  ], $fname
755  );
756  if ( count( $watchersChunks ) > 1 ) {
757  $dbw->commit( __METHOD__, 'flush' );
758  wfGetLBFactory()->waitForReplication( [ 'wiki' => $dbw->getWikiID() ] );
759  }
760  }
761  $this->uncacheLinkTarget( $target );
762 
763  $this->reuseConnection( $dbw );
764  }
765  );
766  }
767 
768  return $watchers;
769  }
770 
783  public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
784  // Only loggedin user can have a watchlist
785  if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
786  return false;
787  }
788 
789  $item = null;
790  if ( $force != 'force' ) {
791  $item = $this->loadWatchedItem( $user, $title );
792  if ( !$item || $item->getNotificationTimestamp() === null ) {
793  return false;
794  }
795  }
796 
797  // If the page is watched by the user (or may be watched), update the timestamp
798  $job = new ActivityUpdateJob(
799  $title,
800  [
801  'type' => 'updateWatchlistNotification',
802  'userid' => $user->getId(),
803  'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
804  'curTime' => time()
805  ]
806  );
807 
808  // Try to run this post-send
809  // Calls DeferredUpdates::addCallableUpdate in normal operation
810  call_user_func(
811  $this->deferredUpdatesAddCallableUpdateCallback,
812  function() use ( $job ) {
813  $job->run();
814  }
815  );
816 
817  $this->uncache( $user, $title );
818 
819  return true;
820  }
821 
822  private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
823  if ( !$oldid ) {
824  // No oldid given, assuming latest revision; clear the timestamp.
825  return null;
826  }
827 
828  if ( !$title->getNextRevisionID( $oldid ) ) {
829  // Oldid given and is the latest revision for this title; clear the timestamp.
830  return null;
831  }
832 
833  if ( $item === null ) {
834  $item = $this->loadWatchedItem( $user, $title );
835  }
836 
837  if ( !$item ) {
838  // This can only happen if $force is enabled.
839  return null;
840  }
841 
842  // Oldid given and isn't the latest; update the timestamp.
843  // This will result in no further notification emails being sent!
844  // Calls Revision::getTimestampFromId in normal operation
845  $notificationTimestamp = call_user_func(
846  $this->revisionGetTimestampFromIdCallback,
847  $title,
848  $oldid
849  );
850 
851  // We need to go one second to the future because of various strict comparisons
852  // throughout the codebase
853  $ts = new MWTimestamp( $notificationTimestamp );
854  $ts->timestamp->add( new DateInterval( 'PT1S' ) );
855  $notificationTimestamp = $ts->getTimestamp( TS_MW );
856 
857  if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
858  if ( $force != 'force' ) {
859  return false;
860  } else {
861  // This is a little silly…
862  return $item->getNotificationTimestamp();
863  }
864  }
865 
866  return $notificationTimestamp;
867  }
868 
876  public function countUnreadNotifications( User $user, $unreadLimit = null ) {
877  $queryOptions = [];
878  if ( $unreadLimit !== null ) {
879  $unreadLimit = (int)$unreadLimit;
880  $queryOptions['LIMIT'] = $unreadLimit;
881  }
882 
883  $dbr = $this->getConnection( DB_SLAVE );
884  $rowCount = $dbr->selectRowCount(
885  'watchlist',
886  '1',
887  [
888  'wl_user' => $user->getId(),
889  'wl_notificationtimestamp IS NOT NULL',
890  ],
891  __METHOD__,
892  $queryOptions
893  );
894  $this->reuseConnection( $dbr );
895 
896  if ( !isset( $unreadLimit ) ) {
897  return $rowCount;
898  }
899 
900  if ( $rowCount >= $unreadLimit ) {
901  return true;
902  }
903 
904  return $rowCount;
905  }
906 
916  public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
917  $oldTarget = Title::newFromLinkTarget( $oldTarget );
918  $newTarget = Title::newFromLinkTarget( $newTarget );
919 
920  $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
921  $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
922  }
923 
934  public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
935  $dbw = $this->getConnection( DB_MASTER );
936 
937  $result = $dbw->select(
938  'watchlist',
939  [ 'wl_user', 'wl_notificationtimestamp' ],
940  [
941  'wl_namespace' => $oldTarget->getNamespace(),
942  'wl_title' => $oldTarget->getDBkey(),
943  ],
944  __METHOD__,
945  [ 'FOR UPDATE' ]
946  );
947 
948  $newNamespace = $newTarget->getNamespace();
949  $newDBkey = $newTarget->getDBkey();
950 
951  # Construct array to replace into the watchlist
952  $values = [];
953  foreach ( $result as $row ) {
954  $values[] = [
955  'wl_user' => $row->wl_user,
956  'wl_namespace' => $newNamespace,
957  'wl_title' => $newDBkey,
958  'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
959  ];
960  }
961 
962  if ( !empty( $values ) ) {
963  # Perform replace
964  # Note that multi-row replace is very efficient for MySQL but may be inefficient for
965  # some other DBMSes, mostly due to poor simulation by us
966  $dbw->replace(
967  'watchlist',
968  [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
969  $values,
970  __METHOD__
971  );
972  }
973 
974  $this->reuseConnection( $dbw );
975  }
976 
977 }
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=[])
the array() calling protocol came about after MediaWiki 1.4rc1.
$success
getCacheKey(User $user, LinkTarget $target)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
countWatchedItems(User $user)
Count the number of individual items that are watched by the user.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
makeList($a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
getCached(User $user, LinkTarget $target)
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:36
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
reuseConnection($connection)
overrideDeferredUpdatesAddCallableUpdateCallback(callable $callback)
Overrides the DeferredUpdates::addCallableUpdate callback This is intended for use while testing and ...
addWatchBatchForUser(User $user, array $targets)
Represents a title within MediaWiki.
Definition: Title.php:36
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getNotificationTimestamp(User $user, Title $title, $item, $force, $oldid)
Describes a Statsd aware interface.
timestamp($ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition: Title.php:230
__construct(LoadBalancer $loadBalancer, HashBagOStuff $cache)
getNamespace()
Get the namespace index.
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 '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1814
$batch
Definition: linkcache.txt:23
static addCallableUpdate($callable, $type=self::POSTSEND)
Add a callable update.
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:47
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:32
Class for asserting that a callback happens when an dummy object leaves scope.
Job for updating user activity like "last viewed" timestamps.
Database load balancing object.
getNextRevisionID($revId, $flags=0)
Get the revision ID of the next revision.
Definition: Title.php:3950
uncacheUser(User $user)
addWatch(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
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...
countWatchers(LinkTarget $target)
resetNotificationTimestamp(User $user, Title $title, $force= '', $oldid=0)
Reset the notification timestamp of this entry.
const LIST_AND
Definition: Defines.php:194
StatsdDataFactoryInterface $stats
isAnon()
Get whether the user is anonymous.
Definition: User.php:3521
if($limit) $timestamp
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1020
array[] $cacheIndex
Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key' The index is needed so that on m...
$res
Definition: database.txt:21
countUnreadNotifications(User $user, $unreadLimit=null)
MediaWiki exception.
Definition: MWException.php:26
getDBkey()
Get the main part with underscores.
getWatchedItemsForUser(User $user, array $options=[])
loadWatchedItem(User $user, LinkTarget $target)
Loads an item from the db.
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:32
const DB_SLAVE
Definition: Defines.php:46
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
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
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 local account $user
Definition: hooks.txt:242
const LIST_OR
Definition: Defines.php:197
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
setStatsdDataFactory(StatsdDataFactoryInterface $stats)
Sets a StatsdDataFactory instance on the object.
getConnection($slaveOrMaster)
Simple store for keeping values in an associative array for the current process.
countVisitingWatchersMultiple(array $targetsWithVisitThresholds, $minimumWatchers=null)
Number of watchers of each page who have visited recent edits to that page.
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...
wfGetLBFactory()
Get the load balancer factory object.
countWatchersMultiple(array $targets, array $options=[])
updateNotificationTimestamp(User $editor, LinkTarget $target, $timestamp)
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
removeWatch(User $user, LinkTarget $target)
Removes the an entry for the User watching the LinkTarget Must be called separately for Subject & Tal...
callable null $deferredUpdatesAddCallableUpdateCallback
getId()
Get the user's ID.
Definition: User.php:2114
isWatched(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
cache(WatchedItem $item)
if(count($args)< 1) $job
HashBagOStuff $cache
$wgUpdateRowsPerQuery
Number of rows to update per query.
uncacheLinkTarget(LinkTarget $target)
getWatchedItem(User $user, LinkTarget $target)
Get an item (may be cached)
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...
getNotificationTimestampsBatch(User $user, array $targets)
const DB_MASTER
Definition: Defines.php:47
addQuotes($s)
Adds quotes and backslashes.
dbCond(User $user, LinkTarget $target)
Return an array of conditions to select or update the appropriate database row.
getVisitingWatchersCondition(IDatabase $db, array $targetsWithVisitThresholds)
Generates condition for the query used in a batch count visiting watchers.
uncache(User $user, LinkTarget $target)
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:31
countVisitingWatchers(LinkTarget $target, $threshold)
Number of page watchers who also visited a "recent" edit.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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 the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor'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:1115
Basic database interface for live and lazy-loaded DB handles.
Definition: IDatabase.php:35