MediaWiki  1.28.0
SqlBagOStuff.php
Go to the documentation of this file.
1 <?php
25 
31 class SqlBagOStuff extends BagOStuff {
33  protected $serverInfos;
35  protected $serverTags;
37  protected $numServers;
39  protected $lastExpireAll = 0;
41  protected $purgePeriod = 100;
43  protected $shards = 1;
45  protected $tableName = 'objectcache';
47  protected $replicaOnly = false;
49  protected $syncTimeout = 3;
50 
52  protected $separateMainLB;
54  protected $conns;
56  protected $connFailureTimes = [];
58  protected $connFailureErrors = [];
59 
96  public function __construct( $params ) {
97  parent::__construct( $params );
98 
99  $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
100  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
101 
102  if ( isset( $params['servers'] ) ) {
103  $this->serverInfos = [];
104  $this->serverTags = [];
105  $this->numServers = count( $params['servers'] );
106  $index = 0;
107  foreach ( $params['servers'] as $tag => $info ) {
108  $this->serverInfos[$index] = $info;
109  if ( is_string( $tag ) ) {
110  $this->serverTags[$index] = $tag;
111  } else {
112  $this->serverTags[$index] = isset( $info['host'] ) ? $info['host'] : "#$index";
113  }
114  ++$index;
115  }
116  } elseif ( isset( $params['server'] ) ) {
117  $this->serverInfos = [ $params['server'] ];
118  $this->numServers = count( $this->serverInfos );
119  } else {
120  // Default to using the main wiki's database servers
121  $this->serverInfos = false;
122  $this->numServers = 1;
123  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
124  }
125  if ( isset( $params['purgePeriod'] ) ) {
126  $this->purgePeriod = intval( $params['purgePeriod'] );
127  }
128  if ( isset( $params['tableName'] ) ) {
129  $this->tableName = $params['tableName'];
130  }
131  if ( isset( $params['shards'] ) ) {
132  $this->shards = intval( $params['shards'] );
133  }
134  if ( isset( $params['syncTimeout'] ) ) {
135  $this->syncTimeout = $params['syncTimeout'];
136  }
137  $this->replicaOnly = !empty( $params['slaveOnly'] );
138  }
139 
140  protected function getSeparateMainLB() {
142 
143  if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
144  if ( !$this->separateMainLB ) {
145  // We must keep a separate connection to MySQL in order to avoid deadlocks
146  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
147  $this->separateMainLB = $lbFactory->newMainLB();
148  }
149  return $this->separateMainLB;
150  } else {
151  // However, SQLite has an opposite behavior. And PostgreSQL needs to know
152  // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
153  return null;
154  }
155  }
156 
164  protected function getDB( $serverIndex ) {
165  if ( !isset( $this->conns[$serverIndex] ) ) {
166  if ( $serverIndex >= $this->numServers ) {
167  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
168  }
169 
170  # Don't keep timing out trying to connect for each call if the DB is down
171  if ( isset( $this->connFailureErrors[$serverIndex] )
172  && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
173  ) {
174  throw $this->connFailureErrors[$serverIndex];
175  }
176 
177  # If server connection info was given, use that
178  if ( $this->serverInfos ) {
179  $info = $this->serverInfos[$serverIndex];
180  $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
181  $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
182  $this->logger->debug( __CLASS__ . ": connecting to $host" );
183  // Use a blank trx profiler to ignore expections as this is a cache
184  $info['trxProfiler'] = new TransactionProfiler();
185  $db = Database::factory( $type, $info );
186  $db->clearFlag( DBO_TRX );
187  } else {
188  $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
189  if ( $this->getSeparateMainLB() ) {
190  $db = $this->getSeparateMainLB()->getConnection( $index );
191  $db->clearFlag( DBO_TRX ); // auto-commit mode
192  } else {
193  $db = wfGetDB( $index );
194  // Can't mess with transaction rounds (DBO_TRX) :(
195  }
196  }
197  $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
198  $this->conns[$serverIndex] = $db;
199  }
200 
201  return $this->conns[$serverIndex];
202  }
203 
209  protected function getTableByKey( $key ) {
210  if ( $this->shards > 1 ) {
211  $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
212  $tableIndex = $hash % $this->shards;
213  } else {
214  $tableIndex = 0;
215  }
216  if ( $this->numServers > 1 ) {
217  $sortedServers = $this->serverTags;
218  ArrayUtils::consistentHashSort( $sortedServers, $key );
219  reset( $sortedServers );
220  $serverIndex = key( $sortedServers );
221  } else {
222  $serverIndex = 0;
223  }
224  return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
225  }
226 
232  protected function getTableNameByShard( $index ) {
233  if ( $this->shards > 1 ) {
234  $decimals = strlen( $this->shards - 1 );
235  return $this->tableName .
236  sprintf( "%0{$decimals}d", $index );
237  } else {
238  return $this->tableName;
239  }
240  }
241 
242  protected function doGet( $key, $flags = 0 ) {
243  $casToken = null;
244 
245  return $this->getWithToken( $key, $casToken, $flags );
246  }
247 
248  protected function getWithToken( $key, &$casToken, $flags = 0 ) {
249  $values = $this->getMulti( [ $key ] );
250  if ( array_key_exists( $key, $values ) ) {
251  $casToken = $values[$key];
252  return $values[$key];
253  }
254  return false;
255  }
256 
257  public function getMulti( array $keys, $flags = 0 ) {
258  $values = []; // array of (key => value)
259 
260  $keysByTable = [];
261  foreach ( $keys as $key ) {
262  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
263  $keysByTable[$serverIndex][$tableName][] = $key;
264  }
265 
266  $this->garbageCollect(); // expire old entries if any
267 
268  $dataRows = [];
269  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
270  try {
271  $db = $this->getDB( $serverIndex );
272  foreach ( $serverKeys as $tableName => $tableKeys ) {
273  $res = $db->select( $tableName,
274  [ 'keyname', 'value', 'exptime' ],
275  [ 'keyname' => $tableKeys ],
276  __METHOD__,
277  // Approximate write-on-the-fly BagOStuff API via blocking.
278  // This approximation fails if a ROLLBACK happens (which is rare).
279  // We do not want to flush the TRX as that can break callers.
280  $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
281  );
282  if ( $res === false ) {
283  continue;
284  }
285  foreach ( $res as $row ) {
286  $row->serverIndex = $serverIndex;
287  $row->tableName = $tableName;
288  $dataRows[$row->keyname] = $row;
289  }
290  }
291  } catch ( DBError $e ) {
292  $this->handleReadError( $e, $serverIndex );
293  }
294  }
295 
296  foreach ( $keys as $key ) {
297  if ( isset( $dataRows[$key] ) ) { // HIT?
298  $row = $dataRows[$key];
299  $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
300  $db = null;
301  try {
302  $db = $this->getDB( $row->serverIndex );
303  if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
304  $this->debug( "get: key has expired" );
305  } else { // HIT
306  $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
307  }
308  } catch ( DBQueryError $e ) {
309  $this->handleWriteError( $e, $db, $row->serverIndex );
310  }
311  } else { // MISS
312  $this->debug( 'get: no matching rows' );
313  }
314  }
315 
316  return $values;
317  }
318 
319  public function setMulti( array $data, $expiry = 0 ) {
320  $keysByTable = [];
321  foreach ( $data as $key => $value ) {
322  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
323  $keysByTable[$serverIndex][$tableName][] = $key;
324  }
325 
326  $this->garbageCollect(); // expire old entries if any
327 
328  $result = true;
329  $exptime = (int)$expiry;
330  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
331  $db = null;
332  try {
333  $db = $this->getDB( $serverIndex );
334  } catch ( DBError $e ) {
335  $this->handleWriteError( $e, $db, $serverIndex );
336  $result = false;
337  continue;
338  }
339 
340  if ( $exptime < 0 ) {
341  $exptime = 0;
342  }
343 
344  if ( $exptime == 0 ) {
345  $encExpiry = $this->getMaxDateTime( $db );
346  } else {
347  $exptime = $this->convertExpiry( $exptime );
348  $encExpiry = $db->timestamp( $exptime );
349  }
350  foreach ( $serverKeys as $tableName => $tableKeys ) {
351  $rows = [];
352  foreach ( $tableKeys as $key ) {
353  $rows[] = [
354  'keyname' => $key,
355  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
356  'exptime' => $encExpiry,
357  ];
358  }
359 
360  try {
361  $db->replace(
362  $tableName,
363  [ 'keyname' ],
364  $rows,
365  __METHOD__
366  );
367  } catch ( DBError $e ) {
368  $this->handleWriteError( $e, $db, $serverIndex );
369  $result = false;
370  }
371 
372  }
373 
374  }
375 
376  return $result;
377  }
378 
379  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
380  $ok = $this->setMulti( [ $key => $value ], $exptime );
381  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
382  $ok = $this->waitForReplication() && $ok;
383  }
384 
385  return $ok;
386  }
387 
388  protected function cas( $casToken, $key, $value, $exptime = 0 ) {
389  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
390  $db = null;
391  try {
392  $db = $this->getDB( $serverIndex );
393  $exptime = intval( $exptime );
394 
395  if ( $exptime < 0 ) {
396  $exptime = 0;
397  }
398 
399  if ( $exptime == 0 ) {
400  $encExpiry = $this->getMaxDateTime( $db );
401  } else {
402  $exptime = $this->convertExpiry( $exptime );
403  $encExpiry = $db->timestamp( $exptime );
404  }
405  // (bug 24425) use a replace if the db supports it instead of
406  // delete/insert to avoid clashes with conflicting keynames
407  $db->update(
408  $tableName,
409  [
410  'keyname' => $key,
411  'value' => $db->encodeBlob( $this->serialize( $value ) ),
412  'exptime' => $encExpiry
413  ],
414  [
415  'keyname' => $key,
416  'value' => $db->encodeBlob( $this->serialize( $casToken ) )
417  ],
418  __METHOD__
419  );
420  } catch ( DBQueryError $e ) {
421  $this->handleWriteError( $e, $db, $serverIndex );
422 
423  return false;
424  }
425 
426  return (bool)$db->affectedRows();
427  }
428 
429  public function delete( $key ) {
430  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
431  $db = null;
432  try {
433  $db = $this->getDB( $serverIndex );
434  $db->delete(
435  $tableName,
436  [ 'keyname' => $key ],
437  __METHOD__ );
438  } catch ( DBError $e ) {
439  $this->handleWriteError( $e, $db, $serverIndex );
440  return false;
441  }
442 
443  return true;
444  }
445 
446  public function incr( $key, $step = 1 ) {
447  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
448  $db = null;
449  try {
450  $db = $this->getDB( $serverIndex );
451  $step = intval( $step );
452  $row = $db->selectRow(
453  $tableName,
454  [ 'value', 'exptime' ],
455  [ 'keyname' => $key ],
456  __METHOD__,
457  [ 'FOR UPDATE' ] );
458  if ( $row === false ) {
459  // Missing
460 
461  return null;
462  }
463  $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
464  if ( $this->isExpired( $db, $row->exptime ) ) {
465  // Expired, do not reinsert
466 
467  return null;
468  }
469 
470  $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
471  $newValue = $oldValue + $step;
472  $db->insert( $tableName,
473  [
474  'keyname' => $key,
475  'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
476  'exptime' => $row->exptime
477  ], __METHOD__, 'IGNORE' );
478 
479  if ( $db->affectedRows() == 0 ) {
480  // Race condition. See bug 28611
481  $newValue = null;
482  }
483  } catch ( DBError $e ) {
484  $this->handleWriteError( $e, $db, $serverIndex );
485  return null;
486  }
487 
488  return $newValue;
489  }
490 
491  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
492  $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
493  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
494  $ok = $this->waitForReplication() && $ok;
495  }
496 
497  return $ok;
498  }
499 
500  public function changeTTL( $key, $expiry = 0 ) {
501  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
502  $db = null;
503  try {
504  $db = $this->getDB( $serverIndex );
505  $db->update(
506  $tableName,
507  [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
508  [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
509  __METHOD__
510  );
511  if ( $db->affectedRows() == 0 ) {
512  return false;
513  }
514  } catch ( DBError $e ) {
515  $this->handleWriteError( $e, $db, $serverIndex );
516  return false;
517  }
518 
519  return true;
520  }
521 
527  protected function isExpired( $db, $exptime ) {
528  return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
529  }
530 
535  protected function getMaxDateTime( $db ) {
536  if ( time() > 0x7fffffff ) {
537  return $db->timestamp( 1 << 62 );
538  } else {
539  return $db->timestamp( 0x7fffffff );
540  }
541  }
542 
543  protected function garbageCollect() {
544  if ( !$this->purgePeriod || $this->replicaOnly ) {
545  // Disabled
546  return;
547  }
548  // Only purge on one in every $this->purgePeriod requests.
549  if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
550  return;
551  }
552  $now = time();
553  // Avoid repeating the delete within a few seconds
554  if ( $now > ( $this->lastExpireAll + 1 ) ) {
555  $this->lastExpireAll = $now;
556  $this->expireAll();
557  }
558  }
559 
560  public function expireAll() {
562  }
563 
570  public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
571  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
572  $db = null;
573  try {
574  $db = $this->getDB( $serverIndex );
575  $dbTimestamp = $db->timestamp( $timestamp );
576  $totalSeconds = false;
577  $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
578  for ( $i = 0; $i < $this->shards; $i++ ) {
579  $maxExpTime = false;
580  while ( true ) {
581  $conds = $baseConds;
582  if ( $maxExpTime !== false ) {
583  $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
584  }
585  $rows = $db->select(
586  $this->getTableNameByShard( $i ),
587  [ 'keyname', 'exptime' ],
588  $conds,
589  __METHOD__,
590  [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
591  if ( $rows === false || !$rows->numRows() ) {
592  break;
593  }
594  $keys = [];
595  $row = $rows->current();
596  $minExpTime = $row->exptime;
597  if ( $totalSeconds === false ) {
598  $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
599  - wfTimestamp( TS_UNIX, $minExpTime );
600  }
601  foreach ( $rows as $row ) {
602  $keys[] = $row->keyname;
603  $maxExpTime = $row->exptime;
604  }
605 
606  $db->delete(
607  $this->getTableNameByShard( $i ),
608  [
609  'exptime >= ' . $db->addQuotes( $minExpTime ),
610  'exptime < ' . $db->addQuotes( $dbTimestamp ),
611  'keyname' => $keys
612  ],
613  __METHOD__ );
614 
615  if ( $progressCallback ) {
616  if ( intval( $totalSeconds ) === 0 ) {
617  $percent = 0;
618  } else {
619  $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
620  - wfTimestamp( TS_UNIX, $maxExpTime );
621  if ( $remainingSeconds > $totalSeconds ) {
622  $totalSeconds = $remainingSeconds;
623  }
624  $processedSeconds = $totalSeconds - $remainingSeconds;
625  $percent = ( $i + $processedSeconds / $totalSeconds )
626  / $this->shards * 100;
627  }
628  $percent = ( $percent / $this->numServers )
629  + ( $serverIndex / $this->numServers * 100 );
630  call_user_func( $progressCallback, $percent );
631  }
632  }
633  }
634  } catch ( DBError $e ) {
635  $this->handleWriteError( $e, $db, $serverIndex );
636  return false;
637  }
638  }
639  return true;
640  }
641 
647  public function deleteAll() {
648  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
649  $db = null;
650  try {
651  $db = $this->getDB( $serverIndex );
652  for ( $i = 0; $i < $this->shards; $i++ ) {
653  $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
654  }
655  } catch ( DBError $e ) {
656  $this->handleWriteError( $e, $db, $serverIndex );
657  return false;
658  }
659  }
660  return true;
661  }
662 
671  protected function serialize( &$data ) {
672  $serial = serialize( $data );
673 
674  if ( function_exists( 'gzdeflate' ) ) {
675  return gzdeflate( $serial );
676  } else {
677  return $serial;
678  }
679  }
680 
686  protected function unserialize( $serial ) {
687  if ( function_exists( 'gzinflate' ) ) {
688  MediaWiki\suppressWarnings();
689  $decomp = gzinflate( $serial );
690  MediaWiki\restoreWarnings();
691 
692  if ( false !== $decomp ) {
693  $serial = $decomp;
694  }
695  }
696 
697  $ret = unserialize( $serial );
698 
699  return $ret;
700  }
701 
708  protected function handleReadError( DBError $exception, $serverIndex ) {
709  if ( $exception instanceof DBConnectionError ) {
710  $this->markServerDown( $exception, $serverIndex );
711  }
712  $this->logger->error( "DBError: {$exception->getMessage()}" );
713  if ( $exception instanceof DBConnectionError ) {
715  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
716  } else {
718  $this->logger->debug( __METHOD__ . ": ignoring query error" );
719  }
720  }
721 
730  protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
731  if ( !$db ) {
732  $this->markServerDown( $exception, $serverIndex );
733  } elseif ( $db->wasReadOnlyError() ) {
734  if ( $db->trxLevel() && $this->usesMainDB() ) {
735  // Errors like deadlocks and connection drops already cause rollback.
736  // For consistency, we have no choice but to throw an error and trigger
737  // complete rollback if the main DB is also being used as the cache DB.
738  throw $exception;
739  }
740  }
741 
742  $this->logger->error( "DBError: {$exception->getMessage()}" );
743  if ( $exception instanceof DBConnectionError ) {
745  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
746  } else {
748  $this->logger->debug( __METHOD__ . ": ignoring query error" );
749  }
750  }
751 
758  protected function markServerDown( DBError $exception, $serverIndex ) {
759  unset( $this->conns[$serverIndex] ); // bug T103435
760 
761  if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
762  if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
763  unset( $this->connFailureTimes[$serverIndex] );
764  unset( $this->connFailureErrors[$serverIndex] );
765  } else {
766  $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
767  return;
768  }
769  }
770  $now = time();
771  $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
772  $this->connFailureTimes[$serverIndex] = $now;
773  $this->connFailureErrors[$serverIndex] = $exception;
774  }
775 
779  public function createTables() {
780  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
781  $db = $this->getDB( $serverIndex );
782  if ( $db->getType() !== 'mysql' ) {
783  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
784  }
785 
786  for ( $i = 0; $i < $this->shards; $i++ ) {
787  $db->query(
788  'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
789  ' LIKE ' . $db->tableName( 'objectcache' ),
790  __METHOD__ );
791  }
792  }
793  }
794 
798  protected function usesMainDB() {
799  return !$this->serverInfos;
800  }
801 
802  protected function waitForReplication() {
803  if ( !$this->usesMainDB() ) {
804  // Custom DB server list; probably doesn't use replication
805  return true;
806  }
807 
808  $lb = $this->getSeparateMainLB()
809  ?: MediaWikiServices::getInstance()->getDBLoadBalancer();
810 
811  if ( $lb->getServerCount() <= 1 ) {
812  return true; // no replica DBs
813  }
814 
815  // Main LB is used; wait for any replica DBs to catch up
816  $masterPos = $lb->getMasterPos();
817 
818  $loop = new WaitConditionLoop(
819  function () use ( $lb, $masterPos ) {
820  return $lb->waitForAll( $masterPos, 1 );
821  },
824  );
825 
826  return ( $loop->invoke() === $loop::CONDITION_REACHED );
827  }
828 }
const ERR_UNEXPECTED
Definition: BagOStuff.php:80
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.
Database error base class.
Definition: DBError.php:26
the array() calling protocol came about after MediaWiki 1.4rc1.
incr($key, $step=1)
static factory($dbType, $p=[])
Construct a Database subclass instance given a database type and parameters.
Definition: Database.php:325
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:1936
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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:2102
__construct($params)
Constructor.
$wgDBtype
Database type.
$value
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
const ERR_UNREACHABLE
Definition: BagOStuff.php:79
unserialize($serial)
Unserialize and, if necessary, decompress an object.
cas($casToken, $key, $value, $exptime=0)
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
handleWriteError(DBError $exception, IDatabase $db=null, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
const DB_MASTER
Definition: defines.php:23
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':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:1934
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: defines.php:6
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:289
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
callable[] $busyCallbacks
Definition: BagOStuff.php:71
convertExpiry($exptime)
Convert an optionally relative time to an absolute time.
Definition: BagOStuff.php:692
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
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
$params
getTableByKey($key)
Get the server index and table name for a given key.
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:1007
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
const DBO_TRX
Definition: defines.php:9
LoadBalancer null $separateMainLB
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
changeTTL($key, $expiry=0)
$lbFactory
array $connFailureTimes
UNIX timestamps.
serialize(&$data)
Serialize an object and, if possible, compress the representation.
const DB_REPLICA
Definition: defines.php:22
Class to store objects in the database.
isExpired($db, $exptime)
debug($text)
Definition: BagOStuff.php:679
setLastError($err)
Set the "last error" registry.
Definition: BagOStuff.php:630
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:2491
merge($key, callable $callback, $exptime=0, $attempts=10, $flags=0)
array $connFailureErrors
Exceptions.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34
getDB($serverIndex)
Get a connection to the specified database.
deleteObjectsExpiringBefore($timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.