MediaWiki  1.27.2
SqlBagOStuff.php
Go to the documentation of this file.
1 <?php
29 class SqlBagOStuff extends BagOStuff {
31  protected $serverInfos;
33  protected $serverTags;
35  protected $numServers;
37  protected $lastExpireAll = 0;
39  protected $purgePeriod = 100;
41  protected $shards = 1;
43  protected $tableName = 'objectcache';
45  protected $slaveOnly = false;
47  protected $syncTimeout = 3;
48 
50  protected $conns;
52  protected $connFailureTimes = [];
54  protected $connFailureErrors = [];
55 
92  public function __construct( $params ) {
93  parent::__construct( $params );
94  if ( isset( $params['servers'] ) ) {
95  $this->serverInfos = [];
96  $this->serverTags = [];
97  $this->numServers = count( $params['servers'] );
98  $index = 0;
99  foreach ( $params['servers'] as $tag => $info ) {
100  $this->serverInfos[$index] = $info;
101  if ( is_string( $tag ) ) {
102  $this->serverTags[$index] = $tag;
103  } else {
104  $this->serverTags[$index] = isset( $info['host'] ) ? $info['host'] : "#$index";
105  }
106  ++$index;
107  }
108  } elseif ( isset( $params['server'] ) ) {
109  $this->serverInfos = [ $params['server'] ];
110  $this->numServers = count( $this->serverInfos );
111  } else {
112  $this->serverInfos = false;
113  $this->numServers = 1;
114  }
115  if ( isset( $params['purgePeriod'] ) ) {
116  $this->purgePeriod = intval( $params['purgePeriod'] );
117  }
118  if ( isset( $params['tableName'] ) ) {
119  $this->tableName = $params['tableName'];
120  }
121  if ( isset( $params['shards'] ) ) {
122  $this->shards = intval( $params['shards'] );
123  }
124  if ( isset( $params['syncTimeout'] ) ) {
125  $this->syncTimeout = $params['syncTimeout'];
126  }
127  $this->slaveOnly = !empty( $params['slaveOnly'] );
128  }
129 
137  protected function getDB( $serverIndex ) {
138  if ( !isset( $this->conns[$serverIndex] ) ) {
139  if ( $serverIndex >= $this->numServers ) {
140  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
141  }
142 
143  # Don't keep timing out trying to connect for each call if the DB is down
144  if ( isset( $this->connFailureErrors[$serverIndex] )
145  && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
146  ) {
147  throw $this->connFailureErrors[$serverIndex];
148  }
149 
150  # If server connection info was given, use that
151  if ( $this->serverInfos ) {
152  $info = $this->serverInfos[$serverIndex];
153  $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
154  $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
155  $this->logger->debug( __CLASS__ . ": connecting to $host" );
156  // Use a blank trx profiler to ignore expections as this is a cache
157  $info['trxProfiler'] = new TransactionProfiler();
158  $db = DatabaseBase::factory( $type, $info );
159  $db->clearFlag( DBO_TRX );
160  } else {
161  // We must keep a separate connection to MySQL in order to avoid deadlocks
162  // However, SQLite has an opposite behavior. And PostgreSQL needs to know
163  // if we are in transaction or not (@TODO: find some work-around).
164  $index = $this->slaveOnly ? DB_SLAVE : DB_MASTER;
165  if ( wfGetDB( $index )->getType() == 'mysql' ) {
166  $lb = wfGetLBFactory()->newMainLB();
167  $db = $lb->getConnection( $index );
168  $db->clearFlag( DBO_TRX ); // auto-commit mode
169  } else {
170  $db = wfGetDB( $index );
171  }
172  }
173  $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
174  $this->conns[$serverIndex] = $db;
175  }
176 
177  return $this->conns[$serverIndex];
178  }
179 
185  protected function getTableByKey( $key ) {
186  if ( $this->shards > 1 ) {
187  $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
188  $tableIndex = $hash % $this->shards;
189  } else {
190  $tableIndex = 0;
191  }
192  if ( $this->numServers > 1 ) {
193  $sortedServers = $this->serverTags;
194  ArrayUtils::consistentHashSort( $sortedServers, $key );
195  reset( $sortedServers );
196  $serverIndex = key( $sortedServers );
197  } else {
198  $serverIndex = 0;
199  }
200  return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
201  }
202 
208  protected function getTableNameByShard( $index ) {
209  if ( $this->shards > 1 ) {
210  $decimals = strlen( $this->shards - 1 );
211  return $this->tableName .
212  sprintf( "%0{$decimals}d", $index );
213  } else {
214  return $this->tableName;
215  }
216  }
217 
218  protected function doGet( $key, $flags = 0 ) {
219  $casToken = null;
220 
221  return $this->getWithToken( $key, $casToken, $flags );
222  }
223 
224  protected function getWithToken( $key, &$casToken, $flags = 0 ) {
225  $values = $this->getMulti( [ $key ] );
226  if ( array_key_exists( $key, $values ) ) {
227  $casToken = $values[$key];
228  return $values[$key];
229  }
230  return false;
231  }
232 
233  public function getMulti( array $keys, $flags = 0 ) {
234  $values = []; // array of (key => value)
235 
236  $keysByTable = [];
237  foreach ( $keys as $key ) {
238  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
239  $keysByTable[$serverIndex][$tableName][] = $key;
240  }
241 
242  $this->garbageCollect(); // expire old entries if any
243 
244  $dataRows = [];
245  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
246  try {
247  $db = $this->getDB( $serverIndex );
248  foreach ( $serverKeys as $tableName => $tableKeys ) {
249  $res = $db->select( $tableName,
250  [ 'keyname', 'value', 'exptime' ],
251  [ 'keyname' => $tableKeys ],
252  __METHOD__,
253  // Approximate write-on-the-fly BagOStuff API via blocking.
254  // This approximation fails if a ROLLBACK happens (which is rare).
255  // We do not want to flush the TRX as that can break callers.
256  $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
257  );
258  if ( $res === false ) {
259  continue;
260  }
261  foreach ( $res as $row ) {
262  $row->serverIndex = $serverIndex;
263  $row->tableName = $tableName;
264  $dataRows[$row->keyname] = $row;
265  }
266  }
267  } catch ( DBError $e ) {
268  $this->handleReadError( $e, $serverIndex );
269  }
270  }
271 
272  foreach ( $keys as $key ) {
273  if ( isset( $dataRows[$key] ) ) { // HIT?
274  $row = $dataRows[$key];
275  $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
276  try {
277  $db = $this->getDB( $row->serverIndex );
278  if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
279  $this->debug( "get: key has expired" );
280  } else { // HIT
281  $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
282  }
283  } catch ( DBQueryError $e ) {
284  $this->handleWriteError( $e, $row->serverIndex );
285  }
286  } else { // MISS
287  $this->debug( 'get: no matching rows' );
288  }
289  }
290 
291  return $values;
292  }
293 
294  public function setMulti( array $data, $expiry = 0 ) {
295  $keysByTable = [];
296  foreach ( $data as $key => $value ) {
297  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
298  $keysByTable[$serverIndex][$tableName][] = $key;
299  }
300 
301  $this->garbageCollect(); // expire old entries if any
302 
303  $result = true;
304  $exptime = (int)$expiry;
305  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
306  try {
307  $db = $this->getDB( $serverIndex );
308  } catch ( DBError $e ) {
309  $this->handleWriteError( $e, $serverIndex );
310  $result = false;
311  continue;
312  }
313 
314  if ( $exptime < 0 ) {
315  $exptime = 0;
316  }
317 
318  if ( $exptime == 0 ) {
319  $encExpiry = $this->getMaxDateTime( $db );
320  } else {
321  $exptime = $this->convertExpiry( $exptime );
322  $encExpiry = $db->timestamp( $exptime );
323  }
324  foreach ( $serverKeys as $tableName => $tableKeys ) {
325  $rows = [];
326  foreach ( $tableKeys as $key ) {
327  $rows[] = [
328  'keyname' => $key,
329  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
330  'exptime' => $encExpiry,
331  ];
332  }
333 
334  try {
335  $db->replace(
336  $tableName,
337  [ 'keyname' ],
338  $rows,
339  __METHOD__
340  );
341  } catch ( DBError $e ) {
342  $this->handleWriteError( $e, $serverIndex );
343  $result = false;
344  }
345 
346  }
347 
348  }
349 
350  return $result;
351  }
352 
353  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
354  $ok = $this->setMulti( [ $key => $value ], $exptime );
355  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
356  $ok = $ok && $this->waitForSlaves();
357  }
358 
359  return $ok;
360  }
361 
362  protected function cas( $casToken, $key, $value, $exptime = 0 ) {
363  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
364  try {
365  $db = $this->getDB( $serverIndex );
366  $exptime = intval( $exptime );
367 
368  if ( $exptime < 0 ) {
369  $exptime = 0;
370  }
371 
372  if ( $exptime == 0 ) {
373  $encExpiry = $this->getMaxDateTime( $db );
374  } else {
375  $exptime = $this->convertExpiry( $exptime );
376  $encExpiry = $db->timestamp( $exptime );
377  }
378  // (bug 24425) use a replace if the db supports it instead of
379  // delete/insert to avoid clashes with conflicting keynames
380  $db->update(
381  $tableName,
382  [
383  'keyname' => $key,
384  'value' => $db->encodeBlob( $this->serialize( $value ) ),
385  'exptime' => $encExpiry
386  ],
387  [
388  'keyname' => $key,
389  'value' => $db->encodeBlob( $this->serialize( $casToken ) )
390  ],
391  __METHOD__
392  );
393  } catch ( DBQueryError $e ) {
394  $this->handleWriteError( $e, $serverIndex );
395 
396  return false;
397  }
398 
399  return (bool)$db->affectedRows();
400  }
401 
402  public function delete( $key ) {
403  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
404  try {
405  $db = $this->getDB( $serverIndex );
406  $db->delete(
407  $tableName,
408  [ 'keyname' => $key ],
409  __METHOD__ );
410  } catch ( DBError $e ) {
411  $this->handleWriteError( $e, $serverIndex );
412  return false;
413  }
414 
415  return true;
416  }
417 
418  public function incr( $key, $step = 1 ) {
419  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
420  try {
421  $db = $this->getDB( $serverIndex );
422  $step = intval( $step );
423  $row = $db->selectRow(
424  $tableName,
425  [ 'value', 'exptime' ],
426  [ 'keyname' => $key ],
427  __METHOD__,
428  [ 'FOR UPDATE' ] );
429  if ( $row === false ) {
430  // Missing
431 
432  return null;
433  }
434  $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
435  if ( $this->isExpired( $db, $row->exptime ) ) {
436  // Expired, do not reinsert
437 
438  return null;
439  }
440 
441  $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
442  $newValue = $oldValue + $step;
443  $db->insert( $tableName,
444  [
445  'keyname' => $key,
446  'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
447  'exptime' => $row->exptime
448  ], __METHOD__, 'IGNORE' );
449 
450  if ( $db->affectedRows() == 0 ) {
451  // Race condition. See bug 28611
452  $newValue = null;
453  }
454  } catch ( DBError $e ) {
455  $this->handleWriteError( $e, $serverIndex );
456  return null;
457  }
458 
459  return $newValue;
460  }
461 
462  public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
463  if ( !is_callable( $callback ) ) {
464  throw new Exception( "Got invalid callback." );
465  }
466 
467  $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
468  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
469  $ok = $ok && $this->waitForSlaves();
470  }
471 
472  return $ok;
473  }
474 
480  protected function isExpired( $db, $exptime ) {
481  return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
482  }
483 
488  protected function getMaxDateTime( $db ) {
489  if ( time() > 0x7fffffff ) {
490  return $db->timestamp( 1 << 62 );
491  } else {
492  return $db->timestamp( 0x7fffffff );
493  }
494  }
495 
496  protected function garbageCollect() {
497  if ( !$this->purgePeriod || $this->slaveOnly ) {
498  // Disabled
499  return;
500  }
501  // Only purge on one in every $this->purgePeriod requests.
502  if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
503  return;
504  }
505  $now = time();
506  // Avoid repeating the delete within a few seconds
507  if ( $now > ( $this->lastExpireAll + 1 ) ) {
508  $this->lastExpireAll = $now;
509  $this->expireAll();
510  }
511  }
512 
513  public function expireAll() {
515  }
516 
523  public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
524  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
525  try {
526  $db = $this->getDB( $serverIndex );
527  $dbTimestamp = $db->timestamp( $timestamp );
528  $totalSeconds = false;
529  $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
530  for ( $i = 0; $i < $this->shards; $i++ ) {
531  $maxExpTime = false;
532  while ( true ) {
533  $conds = $baseConds;
534  if ( $maxExpTime !== false ) {
535  $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
536  }
537  $rows = $db->select(
538  $this->getTableNameByShard( $i ),
539  [ 'keyname', 'exptime' ],
540  $conds,
541  __METHOD__,
542  [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
543  if ( $rows === false || !$rows->numRows() ) {
544  break;
545  }
546  $keys = [];
547  $row = $rows->current();
548  $minExpTime = $row->exptime;
549  if ( $totalSeconds === false ) {
550  $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
551  - wfTimestamp( TS_UNIX, $minExpTime );
552  }
553  foreach ( $rows as $row ) {
554  $keys[] = $row->keyname;
555  $maxExpTime = $row->exptime;
556  }
557 
558  $db->delete(
559  $this->getTableNameByShard( $i ),
560  [
561  'exptime >= ' . $db->addQuotes( $minExpTime ),
562  'exptime < ' . $db->addQuotes( $dbTimestamp ),
563  'keyname' => $keys
564  ],
565  __METHOD__ );
566 
567  if ( $progressCallback ) {
568  if ( intval( $totalSeconds ) === 0 ) {
569  $percent = 0;
570  } else {
571  $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
572  - wfTimestamp( TS_UNIX, $maxExpTime );
573  if ( $remainingSeconds > $totalSeconds ) {
574  $totalSeconds = $remainingSeconds;
575  }
576  $processedSeconds = $totalSeconds - $remainingSeconds;
577  $percent = ( $i + $processedSeconds / $totalSeconds )
578  / $this->shards * 100;
579  }
580  $percent = ( $percent / $this->numServers )
581  + ( $serverIndex / $this->numServers * 100 );
582  call_user_func( $progressCallback, $percent );
583  }
584  }
585  }
586  } catch ( DBError $e ) {
587  $this->handleWriteError( $e, $serverIndex );
588  return false;
589  }
590  }
591  return true;
592  }
593 
599  public function deleteAll() {
600  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
601  try {
602  $db = $this->getDB( $serverIndex );
603  for ( $i = 0; $i < $this->shards; $i++ ) {
604  $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
605  }
606  } catch ( DBError $e ) {
607  $this->handleWriteError( $e, $serverIndex );
608  return false;
609  }
610  }
611  return true;
612  }
613 
622  protected function serialize( &$data ) {
623  $serial = serialize( $data );
624 
625  if ( function_exists( 'gzdeflate' ) ) {
626  return gzdeflate( $serial );
627  } else {
628  return $serial;
629  }
630  }
631 
637  protected function unserialize( $serial ) {
638  if ( function_exists( 'gzinflate' ) ) {
639  MediaWiki\suppressWarnings();
640  $decomp = gzinflate( $serial );
641  MediaWiki\restoreWarnings();
642 
643  if ( false !== $decomp ) {
644  $serial = $decomp;
645  }
646  }
647 
648  $ret = unserialize( $serial );
649 
650  return $ret;
651  }
652 
659  protected function handleReadError( DBError $exception, $serverIndex ) {
660  if ( $exception instanceof DBConnectionError ) {
661  $this->markServerDown( $exception, $serverIndex );
662  }
663  $this->logger->error( "DBError: {$exception->getMessage()}" );
664  if ( $exception instanceof DBConnectionError ) {
666  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
667  } else {
669  $this->logger->debug( __METHOD__ . ": ignoring query error" );
670  }
671  }
672 
679  protected function handleWriteError( DBError $exception, $serverIndex ) {
680  if ( $exception instanceof DBConnectionError ) {
681  $this->markServerDown( $exception, $serverIndex );
682  }
683  if ( $exception->db && $exception->db->wasReadOnlyError() ) {
684  if ( $exception->db->trxLevel() ) {
685  try {
686  $exception->db->rollback( __METHOD__ );
687  } catch ( DBError $e ) {
688  }
689  }
690  }
691 
692  $this->logger->error( "DBError: {$exception->getMessage()}" );
693  if ( $exception instanceof DBConnectionError ) {
695  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
696  } else {
698  $this->logger->debug( __METHOD__ . ": ignoring query error" );
699  }
700  }
701 
708  protected function markServerDown( $exception, $serverIndex ) {
709  unset( $this->conns[$serverIndex] ); // bug T103435
710 
711  if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
712  if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
713  unset( $this->connFailureTimes[$serverIndex] );
714  unset( $this->connFailureErrors[$serverIndex] );
715  } else {
716  $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
717  return;
718  }
719  }
720  $now = time();
721  $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
722  $this->connFailureTimes[$serverIndex] = $now;
723  $this->connFailureErrors[$serverIndex] = $exception;
724  }
725 
729  public function createTables() {
730  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
731  $db = $this->getDB( $serverIndex );
732  if ( $db->getType() !== 'mysql' ) {
733  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
734  }
735 
736  for ( $i = 0; $i < $this->shards; $i++ ) {
737  $db->query(
738  'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
739  ' LIKE ' . $db->tableName( 'objectcache' ),
740  __METHOD__ );
741  }
742  }
743  }
744 
745  protected function waitForSlaves() {
746  if ( !$this->serverInfos ) {
747  // Main LB is used; wait for any slaves to catch up
748  try {
749  wfGetLBFactory()->waitForReplication( [ 'wiki' => wfWikiID() ] );
750  return true;
751  } catch ( DBReplicationWaitError $e ) {
752  return false;
753  }
754  } else {
755  // Custom DB server list; probably doesn't use replication
756  return true;
757  }
758  }
759 }
const ERR_UNEXPECTED
Definition: BagOStuff.php:77
static consistentHashSort(&$array, $key, $separator="\000")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
Definition: ArrayUtils.php:49
getWithToken($key, &$casToken, $flags=0)
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
merge($key, $callback, $exptime=0, $attempts=10, $flags=0)
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
incr($key, $step=1)
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
array[] $serverInfos
(server index => server config)
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
__construct($params)
Constructor.
handleWriteError(DBError $exception, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
$value
const DBO_TRX
Definition: Defines.php:33
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
unserialize($serial)
Unserialize and, if necessary, decompress an object.
cas($casToken, $key, $value, $exptime=0)
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes().You will need both of them.------------------------------------------------------------------------Basic query optimisation------------------------------------------------------------------------MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them.Patches containing unacceptably slow features will not be accepted.Unindexed queries are generally not welcome in MediaWiki
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
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
mergeViaCas($key, $callback, $exptime=0, $attempts=10)
Definition: BagOStuff.php:285
markServerDown($exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
Exception class for replica DB wait timeouts.
Definition: LBFactory.php:480
convertExpiry($exptime)
Convert an optionally relative time to an absolute time.
Definition: BagOStuff.php:656
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition: design.txt:25
string[] $serverTags
(server index => tag/host name)
getMulti(array $keys, $flags=0)
Helper class that detects high-contention DB queries via profiling calls.
if($limit) $timestamp
string $tableName
$res
Definition: database.txt:21
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
$params
getTableByKey($key)
Get the server index and table name for a given key.
static factory($dbType, $p=[])
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
Definition: Database.php:580
const DB_SLAVE
Definition: Defines.php:46
createTables()
Create shard tables.
setMulti(array $data, $expiry=0)
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 $tag
Definition: hooks.txt:965
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
set($key, $value, $exptime=0, $flags=0)
deleteAll()
Delete content of shard tables in every server.
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
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
wfGetLBFactory()
Get the load balancer factory object.
array $connFailureTimes
UNIX timestamps.
serialize(&$data)
Serialize an object and, if possible, compress the representation.
const DB_MASTER
Definition: Defines.php:47
Class to store objects in the database.
isExpired($db, $exptime)
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
debug($text)
Definition: BagOStuff.php:643
setLastError($err)
Set the "last error" registry.
Definition: BagOStuff.php:618
doGet($key, $flags=0)
getTableNameByShard($index)
Get the table name for a given shard index.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
array $connFailureErrors
Exceptions.
getDB($serverIndex)
Get a connection to the specified database.
deleteObjectsExpiringBefore($timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.