MediaWiki  1.27.2
WANObjectCache.php
Go to the documentation of this file.
1 <?php
26 
67 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
69  protected $cache;
71  protected $procCache;
73  protected $purgeChannel;
75  protected $purgeRelayer;
77  protected $logger;
78 
80  protected $lastRelayError = self::ERR_NONE;
81 
83  const MAX_COMMIT_DELAY = 3;
85  const MAX_READ_LAG = 7;
87  const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
88 
90  const CHECK_KEY_TTL = self::TTL_YEAR;
92  const LOCK_TTL = 10;
94  const LOW_TTL = 30;
96  const LOCK_TSE = 1;
97 
99  const TTL_UNCACHEABLE = -1;
101  const TSE_NONE = -1;
103  const TTL_LAGGED = 30;
105  const HOLDOFF_NONE = 0;
106 
108  const TINY_NEGATIVE = -0.000001;
109 
111  const VERSION = 1;
112 
113  const FLD_VERSION = 0;
114  const FLD_VALUE = 1;
115  const FLD_TTL = 2;
116  const FLD_TIME = 3;
117  const FLD_FLAGS = 4;
118  const FLD_HOLDOFF = 5;
119 
121  const FLG_STALE = 1;
122 
123  const ERR_NONE = 0; // no error
124  const ERR_NO_RESPONSE = 1; // no response
125  const ERR_UNREACHABLE = 2; // can't connect
126  const ERR_UNEXPECTED = 3; // response gave some error
127  const ERR_RELAY = 4; // relay broadcast failed
128 
129  const VALUE_KEY_PREFIX = 'WANCache:v:';
130  const STASH_KEY_PREFIX = 'WANCache:s:';
131  const TIME_KEY_PREFIX = 'WANCache:t:';
132 
133  const PURGE_VAL_PREFIX = 'PURGED:';
134 
135  const MAX_PC_KEYS = 1000; // max keys to keep in process cache
136 
137  const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
138 
146  public function __construct( array $params ) {
147  $this->cache = $params['cache'];
148  $this->procCache = new HashBagOStuff( [ 'maxKeys' => self::MAX_PC_KEYS ] );
149  $this->purgeChannel = isset( $params['channels']['purge'] )
150  ? $params['channels']['purge']
151  : self::DEFAULT_PURGE_CHANNEL;
152  $this->purgeRelayer = isset( $params['relayers']['purge'] )
153  ? $params['relayers']['purge']
154  : new EventRelayerNull( [] );
155  $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
156  }
157 
158  public function setLogger( LoggerInterface $logger ) {
159  $this->logger = $logger;
160  }
161 
167  public static function newEmpty() {
168  return new self( [
169  'cache' => new EmptyBagOStuff(),
170  'pool' => 'empty',
171  'relayer' => new EventRelayerNull( [] )
172  ] );
173  }
174 
214  final public function get( $key, &$curTTL = null, array $checkKeys = [] ) {
215  $curTTLs = [];
216  $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys );
217  $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
218 
219  return isset( $values[$key] ) ? $values[$key] : false;
220  }
221 
233  final public function getMulti(
234  array $keys, &$curTTLs = [], array $checkKeys = []
235  ) {
236  $result = [];
237  $curTTLs = [];
238 
239  $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
240  $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
241 
242  $checkKeysForAll = [];
243  $checkKeysByKey = [];
244  $checkKeysFlat = [];
245  foreach ( $checkKeys as $i => $keys ) {
246  $prefixed = self::prefixCacheKeys( (array)$keys, self::TIME_KEY_PREFIX );
247  $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
248  // Is this check keys for a specific cache key, or for all keys being fetched?
249  if ( is_int( $i ) ) {
250  $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
251  } else {
252  $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
253  ? array_merge( $checkKeysByKey[$i], $prefixed )
254  : $prefixed;
255  }
256  }
257 
258  // Fetch all of the raw values
259  $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
260  // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
261  $now = microtime( true );
262 
263  // Collect timestamps from all "check" keys
264  $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
265  $purgeValuesByKey = [];
266  foreach ( $checkKeysByKey as $cacheKey => $checks ) {
267  $purgeValuesByKey[$cacheKey] =
268  $this->processCheckKeys( $checks, $wrappedValues, $now );
269  }
270 
271  // Get the main cache value for each key and validate them
272  foreach ( $valueKeys as $vKey ) {
273  if ( !isset( $wrappedValues[$vKey] ) ) {
274  continue; // not found
275  }
276 
277  $key = substr( $vKey, $vPrefixLen ); // unprefix
278 
279  list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
280  if ( $value !== false ) {
281  $result[$key] = $value;
282 
283  // Force dependant keys to be invalid for a while after purging
284  // to reduce race conditions involving stale data getting cached
285  $purgeValues = $purgeValuesForAll;
286  if ( isset( $purgeValuesByKey[$key] ) ) {
287  $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
288  }
289  foreach ( $purgeValues as $purge ) {
290  $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
291  if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
292  // How long ago this value was expired by *this* check key
293  $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
294  // How long ago this value was expired by *any* known check key
295  $curTTL = min( $curTTL, $ago );
296  }
297  }
298  }
299  $curTTLs[$key] = $curTTL;
300  }
301 
302  return $result;
303  }
304 
312  private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
313  $purgeValues = [];
314  foreach ( $timeKeys as $timeKey ) {
315  $purge = isset( $wrappedValues[$timeKey] )
316  ? self::parsePurgeValue( $wrappedValues[$timeKey] )
317  : false;
318  if ( $purge === false ) {
319  // Key is not set or invalid; regenerate
320  $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
321  $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
322  $purge = self::parsePurgeValue( $newVal );
323  }
324  $purgeValues[] = $purge;
325  }
326  return $purgeValues;
327  }
328 
379  final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
380  $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
381  $age = isset( $opts['since'] ) ? max( 0, microtime( true ) - $opts['since'] ) : 0;
382  $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
383 
384  // Do not cache potentially uncommitted data as it might get rolled back
385  if ( !empty( $opts['pending'] ) ) {
386  $this->logger->info( "Rejected set() for $key due to pending writes." );
387 
388  return true; // no-op the write for being unsafe
389  }
390 
391  $wrapExtra = []; // additional wrapped value fields
392  // Check if there's a risk of writing stale data after the purge tombstone expired
393  if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
394  // Case A: read lag with "lockTSE"; save but record value as stale
395  if ( $lockTSE >= 0 ) {
396  $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
397  $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
398  // Case B: any long-running transaction; ignore this set()
399  } elseif ( $age > self::MAX_READ_LAG ) {
400  $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
401 
402  return true; // no-op the write for being unsafe
403  // Case C: high replication lag; lower TTL instead of ignoring all set()s
404  } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
405  $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
406  $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
407  // Case D: medium length request with medium replication lag; ignore this set()
408  } else {
409  $this->logger->warning( "Rejected set() for $key due to high read lag." );
410 
411  return true; // no-op the write for being unsafe
412  }
413  }
414 
415  // Wrap that value with time/TTL/version metadata
416  $wrapped = $this->wrap( $value, $ttl ) + $wrapExtra;
417 
418  $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
419  return ( is_string( $cWrapped ) )
420  ? false // key is tombstoned; do nothing
421  : $wrapped;
422  };
423 
424  return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
425  }
426 
484  final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
485  $key = self::VALUE_KEY_PREFIX . $key;
486 
487  if ( $ttl <= 0 ) {
488  // Update the local datacenter immediately
489  $ok = $this->cache->delete( $key );
490  // Publish the purge to all datacenters
491  $ok = $this->relayDelete( $key ) && $ok;
492  } else {
493  // Update the local datacenter immediately
494  $ok = $this->cache->set( $key,
495  $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
496  $ttl
497  );
498  // Publish the purge to all datacenters
499  $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE ) && $ok;
500  }
501 
502  return $ok;
503  }
504 
524  final public function getCheckKeyTime( $key ) {
525  $key = self::TIME_KEY_PREFIX . $key;
526 
527  $purge = self::parsePurgeValue( $this->cache->get( $key ) );
528  if ( $purge !== false ) {
529  $time = $purge[self::FLD_TIME];
530  } else {
531  // Casting assures identical floats for the next getCheckKeyTime() calls
532  $now = (string)microtime( true );
533  $this->cache->add( $key,
534  $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
535  self::CHECK_KEY_TTL
536  );
537  $time = (float)$now;
538  }
539 
540  return $time;
541  }
542 
574  final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
575  $key = self::TIME_KEY_PREFIX . $key;
576  // Update the local datacenter immediately
577  $ok = $this->cache->set( $key,
578  $this->makePurgeValue( microtime( true ), $holdoff ),
579  self::CHECK_KEY_TTL
580  );
581  // Publish the purge to all datacenters
582  return $this->relayPurge( $key, self::CHECK_KEY_TTL, $holdoff ) && $ok;
583  }
584 
612  final public function resetCheckKey( $key ) {
613  $key = self::TIME_KEY_PREFIX . $key;
614  // Update the local datacenter immediately
615  $ok = $this->cache->delete( $key );
616  // Publish the purge to all datacenters
617  return $this->relayDelete( $key ) && $ok;
618  }
619 
771  final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
772  $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
773 
774  // Try the process cache if enabled
775  $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
776 
777  if ( $value === false ) {
778  // Fetch the value over the network
779  $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
780  // Update the process cache if enabled
781  if ( $pcTTL >= 0 && $value !== false ) {
782  $this->procCache->set( $key, $value, $pcTTL );
783  }
784  }
785 
786  return $value;
787  }
788 
800  protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
801  $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
802  $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
803  $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
804 
805  // Get the current key value
806  $curTTL = null;
807  $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
808  $value = $cValue; // return value
809 
810  // Determine if a regeneration is desired
811  if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
812  return $value;
813  }
814 
815  // A deleted key with a negative TTL left must be tombstoned
816  $isTombstone = ( $curTTL !== null && $value === false );
817  // Assume a key is hot if requested soon after invalidation
818  $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
819  // Decide whether a single thread should handle regenerations.
820  // This avoids stampedes when $checkKeys are bumped and when preemptive
821  // renegerations take too long. It also reduces regenerations while $key
822  // is tombstoned. This balances cache freshness with avoiding DB load.
823  $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) );
824 
825  $lockAcquired = false;
826  if ( $useMutex ) {
827  // Acquire a datacenter-local non-blocking lock
828  if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
829  // Lock acquired; this thread should update the key
830  $lockAcquired = true;
831  } elseif ( $value !== false ) {
832  // If it cannot be acquired; then the stale value can be used
833  return $value;
834  } else {
835  // Use the stash value for tombstoned keys to reduce regeneration load.
836  // For hot keys, either another thread has the lock or the lock failed;
837  // use the stash value from the last thread that regenerated it.
838  $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
839  if ( $value !== false ) {
840  return $value;
841  }
842  }
843  }
844 
845  if ( !is_callable( $callback ) ) {
846  throw new InvalidArgumentException( "Invalid cache miss callback provided." );
847  }
848 
849  // Generate the new value from the callback...
850  $setOpts = [];
851  $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
852  // When delete() is called, writes are write-holed by the tombstone,
853  // so use a special stash key to pass the new value around threads.
854  if ( $useMutex && $value !== false && $ttl >= 0 ) {
855  $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
856  $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
857  }
858 
859  if ( $lockAcquired ) {
860  $this->cache->unlock( $key );
861  }
862 
863  if ( $value !== false && $ttl >= 0 ) {
864  // Update the cache; this will fail if the key is tombstoned
865  $setOpts['lockTSE'] = $lockTSE;
866  $this->set( $key, $value, $ttl, $setOpts );
867  }
868 
869  return $value;
870  }
871 
878  public function makeKey() {
879  return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
880  }
881 
888  public function makeGlobalKey() {
889  return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
890  }
891 
896  final public function getLastError() {
897  if ( $this->lastRelayError ) {
898  // If the cache and the relayer failed, focus on the later.
899  // An update not making it to the relayer means it won't show up
900  // in other DCs (nor will consistent re-hashing see up-to-date values).
901  // On the other hand, if just the cache update failed, then it should
902  // eventually be applied by the relayer.
903  return $this->lastRelayError;
904  }
905 
906  $code = $this->cache->getLastError();
907  switch ( $code ) {
908  case BagOStuff::ERR_NONE:
909  return self::ERR_NONE;
911  return self::ERR_NO_RESPONSE;
913  return self::ERR_UNREACHABLE;
914  default:
915  return self::ERR_UNEXPECTED;
916  }
917  }
918 
922  final public function clearLastError() {
923  $this->cache->clearLastError();
924  $this->lastRelayError = self::ERR_NONE;
925  }
926 
932  public function clearProcessCache() {
933  $this->procCache->clear();
934  }
935 
946  protected function relayPurge( $key, $ttl, $holdoff ) {
947  $event = $this->cache->modifySimpleRelayEvent( [
948  'cmd' => 'set',
949  'key' => $key,
950  'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
951  'ttl' => max( $ttl, 1 ),
952  'sbt' => true, // substitute $UNIXTIME$ with actual microtime
953  ] );
954 
955  $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
956  if ( !$ok ) {
957  $this->lastRelayError = self::ERR_RELAY;
958  }
959 
960  return $ok;
961  }
962 
969  protected function relayDelete( $key ) {
970  $event = $this->cache->modifySimpleRelayEvent( [
971  'cmd' => 'delete',
972  'key' => $key,
973  ] );
974 
975  $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
976  if ( !$ok ) {
977  $this->lastRelayError = self::ERR_RELAY;
978  }
979 
980  return $ok;
981  }
982 
995  protected function worthRefresh( $curTTL, $lowTTL ) {
996  if ( $curTTL >= $lowTTL ) {
997  return false;
998  } elseif ( $curTTL <= 0 ) {
999  return true;
1000  }
1001 
1002  $chance = ( 1 - $curTTL / $lowTTL );
1003 
1004  return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1005  }
1006 
1014  protected function wrap( $value, $ttl ) {
1015  return [
1016  self::FLD_VERSION => self::VERSION,
1017  self::FLD_VALUE => $value,
1018  self::FLD_TTL => $ttl,
1019  self::FLD_TIME => microtime( true )
1020  ];
1021  }
1022 
1030  protected function unwrap( $wrapped, $now ) {
1031  // Check if the value is a tombstone
1032  $purge = self::parsePurgeValue( $wrapped );
1033  if ( $purge !== false ) {
1034  // Purged values should always have a negative current $ttl
1035  $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1036  return [ false, $curTTL ];
1037  }
1038 
1039  if ( !is_array( $wrapped ) // not found
1040  || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1041  || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1042  ) {
1043  return [ false, null ];
1044  }
1045 
1046  $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1047  if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1048  // Treat as expired, with the cache time as the expiration
1049  $age = $now - $wrapped[self::FLD_TIME];
1050  $curTTL = min( -$age, self::TINY_NEGATIVE );
1051  } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1052  // Get the approximate time left on the key
1053  $age = $now - $wrapped[self::FLD_TIME];
1054  $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1055  } else {
1056  // Key had no TTL, so the time left is unbounded
1057  $curTTL = INF;
1058  }
1059 
1060  return [ $wrapped[self::FLD_VALUE], $curTTL ];
1061  }
1062 
1068  protected static function prefixCacheKeys( array $keys, $prefix ) {
1069  $res = [];
1070  foreach ( $keys as $key ) {
1071  $res[] = $prefix . $key;
1072  }
1073 
1074  return $res;
1075  }
1076 
1082  protected static function parsePurgeValue( $value ) {
1083  if ( !is_string( $value ) ) {
1084  return false;
1085  }
1086  $segments = explode( ':', $value, 3 );
1087  if ( !isset( $segments[0] ) || !isset( $segments[1] )
1088  || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1089  ) {
1090  return false;
1091  }
1092  if ( !isset( $segments[2] ) ) {
1093  // Back-compat with old purge values without holdoff
1094  $segments[2] = self::HOLDOFF_TTL;
1095  }
1096  return [
1097  self::FLD_TIME => (float)$segments[1],
1098  self::FLD_HOLDOFF => (int)$segments[2],
1099  ];
1100  }
1101 
1107  protected function makePurgeValue( $timestamp, $holdoff ) {
1108  return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1109  }
1110 }
processCheckKeys(array $timeKeys, array $wrappedValues, $now)
set($key, $value, $ttl=0, array $opts=[])
Set the value of a key in cache.
string $purgeChannel
Purge channel name.
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
const TTL_LAGGED
Max TTL to store keys when a data sourced is lagged.
const TINY_NEGATIVE
Tiny negative float to use when CTL comes up >= 0 due to clock skew.
the array() calling protocol came about after MediaWiki 1.4rc1.
const CHECK_KEY_TTL
Seconds to keep dependency purge keys around.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
clearProcessCache()
Clear the in-process caches; useful for testing.
static prefixCacheKeys(array $keys, $prefix)
unwrap($wrapped, $now)
Do not use this method outside WANObjectCache.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
const MAX_COMMIT_DELAY
Max time expected to pass between delete() and DB commit finishing.
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
LoggerInterface $logger
EventRelayer $purgeRelayer
Bus that handles purge broadcasts.
const ERR_NO_RESPONSE
Definition: BagOStuff.php:75
touchCheckKey($key, $holdoff=self::HOLDOFF_TTL)
Purge a "check" key from all datacenters, invalidating keys that use it.
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
$value
const DEFAULT_PURGE_CHANNEL
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
const ERR_UNREACHABLE
Definition: BagOStuff.php:76
Multi-datacenter aware caching interface.
wrap($value, $ttl)
Do not use this method outside WANObjectCache.
No-op class for publishing messages into a PubSub system.
getWithSetCallback($key, $ttl, $callback, array $opts=[])
Method to fetch/regenerate cache keys.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1612
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':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:1796
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
const LOW_TTL
Default remaining TTL at which to consider pre-emptive regeneration.
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
if($limit) $timestamp
$res
Definition: database.txt:21
__construct(array $params)
$params
const ERR_NONE
Possible values for getLastError()
Definition: BagOStuff.php:74
getCheckKeyTime($key)
Fetch the value of a timestamp "check" key.
getMulti(array $keys, &$curTTLs=[], array $checkKeys=[])
Fetch the value of several keys from cache.
const LOCK_TSE
Default time-since-expiry on a miss that makes a key "hot".
A BagOStuff object with no objects in it.
const HOLDOFF_NONE
Idiom for delete() for "no hold-off".
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:762
const VERSION
Cache format version number.
clearLastError()
Clear the "last error" registry.
resetCheckKey($key)
Delete a "check" key from all datacenters, invalidating keys that use it.
worthRefresh($curTTL, $lowTTL)
Check if a key should be regenerated (using random probability)
const HOLDOFF_TTL
Seconds to tombstone keys on delete()
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
relayPurge($key, $ttl, $holdoff)
Do the actual async bus purge of a key.
int $lastRelayError
ERR_* constant for the "last error" registry.
static parsePurgeValue($value)
const LOCK_TTL
Seconds to keep lock keys around.
makePurgeValue($timestamp, $holdoff)
relayDelete($key)
Do the actual async bus delete of a key.
Generic base class for storage interfaces.
const MAX_READ_LAG
Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()
doGetWithSetCallback($key, $ttl, $callback, array $opts)
Do the actual I/O for getWithSetCallback() when needed.
setLogger(LoggerInterface $logger)
const TSE_NONE
Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.
HashBagOStuff $procCache
Script instance PHP cache.
BagOStuff $cache
The local datacenter cache.