Go to the documentation of this file.
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Wikimedia\ScopedCallback;
31 use Wikimedia\Timestamp\ConvertibleTimestamp;
35 use InvalidArgumentException;
246 $password =
$params[
'password'];
249 $this->mSchema =
$params[
'schema'];
250 $this->mTablePrefix =
$params[
'tablePrefix'];
252 $this->cliMode =
$params[
'cliMode'];
254 $this->agent = str_replace(
'/',
'-',
$params[
'agent'] );
256 $this->mFlags =
$params[
'flags'];
258 if ( $this->cliMode ) {
265 $this->mSessionVars =
$params[
'variables'];
267 $this->srvCache = isset(
$params[
'srvCache'] )
271 $this->profiler =
$params[
'profiler'];
272 $this->trxProfiler =
$params[
'trxProfiler'];
273 $this->connLogger =
$params[
'connLogger'];
274 $this->queryLogger =
$params[
'queryLogger'];
275 $this->errorLogger =
$params[
'errorLogger'];
281 $this->
open( $server,
$user, $password, $dbName );
283 throw new InvalidArgumentException(
"No database user provided." );
287 if ( $this->mDBname !=
'' ) {
289 $this->currentDomain =
new DatabaseDomain( $this->mDBname,
null, $this->mTablePrefix );
334 final public static function factory( $dbType, $p = [] ) {
335 static $canonicalDBTypes = [
336 'mysql' => [
'mysqli',
'mysql' ],
342 static $classAliases = [
351 $dbType = strtolower( $dbType );
352 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
353 $possibleDrivers = $canonicalDBTypes[$dbType];
354 if ( !empty( $p[
'driver'] ) ) {
355 if ( in_array( $p[
'driver'], $possibleDrivers ) ) {
356 $driver = $p[
'driver'];
358 throw new InvalidArgumentException( __METHOD__ .
359 " type '$dbType' does not support driver '{$p['driver']}'" );
362 foreach ( $possibleDrivers
as $posDriver ) {
363 if ( extension_loaded( $posDriver ) ) {
364 $driver = $posDriver;
373 if ( $driver ===
false || $driver ===
'' ) {
374 throw new InvalidArgumentException( __METHOD__ .
375 " no viable database extension found for type '$dbType'" );
378 $class =
'Database' . ucfirst( $driver );
379 if ( isset( $classAliases[$class] ) ) {
380 $class = $classAliases[$class];
383 if ( class_exists( $class ) && is_subclass_of( $class,
IDatabase::class ) ) {
385 $p[
'host'] = isset( $p[
'host'] ) ? $p[
'host'] :
false;
386 $p[
'user'] = isset( $p[
'user'] ) ? $p[
'user'] :
false;
387 $p[
'password'] = isset( $p[
'password'] ) ? $p[
'password'] :
false;
388 $p[
'dbname'] = isset( $p[
'dbname'] ) ? $p[
'dbname'] :
false;
389 $p[
'flags'] = isset( $p[
'flags'] ) ? $p[
'flags'] : 0;
390 $p[
'variables'] = isset( $p[
'variables'] ) ? $p[
'variables'] : [];
391 $p[
'tablePrefix'] = isset( $p[
'tablePrefix'] ) ? $p[
'tablePrefix'] :
'';
392 $p[
'schema'] = isset( $p[
'schema'] ) ? $p[
'schema'] :
'';
393 $p[
'cliMode'] = isset( $p[
'cliMode'] ) ? $p[
'cliMode'] : ( PHP_SAPI ===
'cli' );
394 $p[
'agent'] = isset( $p[
'agent'] ) ? $p[
'agent'] :
'';
395 if ( !isset( $p[
'connLogger'] ) ) {
396 $p[
'connLogger'] = new \Psr\Log\NullLogger();
398 if ( !isset( $p[
'queryLogger'] ) ) {
399 $p[
'queryLogger'] = new \Psr\Log\NullLogger();
401 $p[
'profiler'] = isset( $p[
'profiler'] ) ? $p[
'profiler'] :
null;
402 if ( !isset( $p[
'trxProfiler'] ) ) {
405 if ( !isset( $p[
'errorLogger'] ) ) {
406 $p[
'errorLogger'] =
function ( Exception
$e ) {
407 trigger_error( get_class(
$e ) .
': ' .
$e->getMessage(), E_USER_WARNING );
411 $conn =
new $class( $p );
420 $this->queryLogger = $logger;
452 if ( $ignoreErrors !==
null ) {
466 return $this->mTrxLevel ? $this->mTrxTimestamp :
null;
471 if ( $prefix !==
null ) {
472 $this->mTablePrefix = $prefix;
473 $this->currentDomain = ( $this->mDBname !=
'' )
483 if ( $schema !==
null ) {
484 $this->mSchema = $schema;
491 if ( is_null(
$name ) ) {
494 if ( array_key_exists(
$name, $this->mLBInfo ) ) {
495 return $this->mLBInfo[
$name];
503 if ( is_null(
$value ) ) {
504 $this->mLBInfo =
$name;
511 $this->lazyMasterHandle = $conn;
540 return $this->mLastWriteTime ?:
false;
548 return $this->mTrxLevel && (
554 if ( !$this->mTrxLevel ) {
556 } elseif ( !$this->mTrxDoneWrites ) {
561 case self::ESTIMATE_DB_APPLY:
563 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
564 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
567 $applyTime += self::TINY_WRITE_SEC * $omitted;
576 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
580 if ( !$this->mTrxLevel ) {
586 $this->mTrxIdleCallbacks,
587 $this->mTrxPreCommitCallbacks,
588 $this->mTrxEndCallbacks
590 foreach ( $callbacks
as $callback ) {
591 $fnames[] = $callback[1];
602 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
603 if ( $remember === self::REMEMBER_PRIOR ) {
604 array_push( $this->priorFlags, $this->mFlags );
606 $this->mFlags |= $flag;
609 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
610 if ( $remember === self::REMEMBER_PRIOR ) {
611 array_push( $this->priorFlags, $this->mFlags );
613 $this->mFlags &= ~$flag;
617 if ( !$this->priorFlags ) {
621 if ( $state === self::RESTORE_INITIAL ) {
622 $this->mFlags = reset( $this->priorFlags );
623 $this->priorFlags = [];
625 $this->mFlags = array_pop( $this->priorFlags );
630 return !!( $this->mFlags & $flag );
643 return $this->currentDomain->getId();
668 $this->mPHPError =
false;
669 $this->htmlErrors = ini_set(
'html_errors',
'0' );
670 set_error_handler( [ $this,
'connectionErrorLogger' ] );
677 restore_error_handler();
678 if ( $this->htmlErrors !==
false ) {
679 ini_set(
'html_errors', $this->htmlErrors );
689 if ( $this->mPHPError ) {
690 $error = preg_replace(
'!\[<a.*</a>\]!',
'', $this->mPHPError );
691 $error = preg_replace(
'!^.*?:\s?(.*)$!',
'$1', $error );
706 $this->mPHPError = $errstr;
718 'db_server' => $this->mServer,
719 'db_name' => $this->mDBname,
720 'db_user' => $this->mUser,
727 if ( $this->mConn ) {
729 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
733 $this->mConn =
false;
734 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) {
735 throw new RuntimeException(
"Transaction callbacks still pending." );
739 $this->mOpened =
false;
779 abstract protected function doQuery( $sql );
790 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
798 return preg_match(
'/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) :
null;
813 [
'BEGIN',
'COMMIT',
'ROLLBACK',
'SHOW',
'SET',
'CREATE',
'ALTER' ],
824 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
828 $this->mSessionTempTables[
$matches[1]] = 1;
831 } elseif ( preg_match(
832 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
836 unset( $this->mSessionTempTables[
$matches[1]] );
839 } elseif ( preg_match(
840 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
844 return isset( $this->mSessionTempTables[
$matches[1]] );
850 public function query( $sql,
$fname = __METHOD__, $tempIgnore =
false ) {
852 $this->mLastQuery = $sql;
857 if ( $reason !==
false ) {
860 # Set a flag indicating that writes have been done
861 $this->mLastWriteTime = microtime(
true );
866 $commentedSql = preg_replace(
'/\s|$/',
" /* $fname {$this->agent} */ ", $sql, 1 );
868 # Start implicit transactions that wrap the request if DBO_TRX is enabled
872 $this->
begin( __METHOD__ .
" ($fname)", self::TRANSACTION_INTERNAL );
873 $this->mTrxAutomatic =
true;
876 # Keep track of whether the transaction has write queries pending
877 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
878 $this->mTrxDoneWrites =
true;
879 $this->trxProfiler->transactionWritingIn(
880 $this->mServer, $this->mDBname, $this->mTrxShortId );
884 $this->queryLogger->debug(
"{$this->mDBname} {$commentedSql}" );
887 # Avoid fatals if close() was called
890 # Send the query to the server
893 # Try reconnecting if the connection was lost
896 # Stash the last error values before anything might clear them
899 # Update state tracking to reflect transaction loss due to disconnection
902 $msg = __METHOD__ .
": lost connection to {$this->getServer()}; reconnected";
903 $this->connLogger->warning( $msg );
904 $this->queryLogger->warning(
905 "$msg:\n" . (
new RuntimeException() )->getTraceAsString() );
907 if ( !$recoverable ) {
908 # Callers may catch the exception and continue to use the DB
911 # Should be safe to silently retry the query
915 $msg = __METHOD__ .
": lost connection to {$this->getServer()} permanently";
916 $this->connLogger->error( $msg );
920 if (
false ===
$ret ) {
921 # Deadlocks cause the entire transaction to abort, not just the statement.
922 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
923 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
928 # Update state tracking to reflect transaction loss
942 $isMaster = !is_null( $this->
getLBInfo(
'master' ) );
943 # generalizeSQL() will probably cut down the query to reasonable
944 # logging size most of the time. The substr is really just a sanity check.
946 $queryProf =
'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
948 $queryProf =
'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
951 # Include query transaction state
952 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" :
"";
954 $startTime = microtime(
true );
955 if ( $this->profiler ) {
956 call_user_func( [ $this->profiler,
'profileIn' ], $queryProf );
959 if ( $this->profiler ) {
960 call_user_func( [ $this->profiler,
'profileOut' ], $queryProf );
962 $queryRuntime = max( microtime(
true ) - $startTime, 0.0 );
964 unset( $queryProfSection );
966 if (
$ret !==
false ) {
967 $this->lastPing = $startTime;
968 if ( $isWrite && $this->mTrxLevel ) {
970 $this->mTrxWriteCallers[] =
$fname;
974 if ( $sql === self::PING_QUERY ) {
975 $this->mRTTEstimate = $queryRuntime;
978 $this->trxProfiler->recordQueryCompletion(
981 $this->queryLogger->debug( $sql, [
983 'master' => $isMaster,
984 'runtime' => $queryRuntime,
1003 $indicativeOfReplicaRuntime =
true;
1004 if ( $runtime > self::SLOW_WRITE_SEC ) {
1007 if ( $verb ===
'INSERT' ) {
1009 } elseif ( $verb ===
'REPLACE' ) {
1010 $indicativeOfReplicaRuntime = $this->
affectedRows() > self::SMALL_WRITE_ROWS / 2;
1014 $this->mTrxWriteDuration += $runtime;
1015 $this->mTrxWriteQueryCount += 1;
1016 if ( $indicativeOfReplicaRuntime ) {
1017 $this->mTrxWriteAdjDuration += $runtime;
1018 $this->mTrxWriteAdjQueryCount += 1;
1023 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1024 # Dropped connections also mean that named locks are automatically released.
1025 # Only allow error suppression in autocommit mode or when the lost transaction
1026 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1027 if ( $this->mNamedLocksHeld ) {
1029 } elseif ( $sql ===
'COMMIT' ) {
1030 return !$priorWritesPending;
1031 } elseif ( $sql ===
'ROLLBACK' ) {
1035 } elseif ( $priorWritesPending ) {
1043 $this->mTrxLevel = 0;
1044 $this->mTrxIdleCallbacks = [];
1045 $this->mTrxPreCommitCallbacks = [];
1046 $this->mSessionTempTables = [];
1047 $this->mNamedLocksHeld = [];
1053 }
catch ( Exception
$e ) {
1061 $this->queryLogger->debug(
"SQL ERROR (ignored): $error\n" );
1063 $sql1line = mb_substr( str_replace(
"\n",
"\\n", $sql ), 0, 5 * 1024 );
1064 $this->queryLogger->error(
1065 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1067 'method' => __METHOD__,
1070 'sql1line' => $sql1line,
1074 $this->queryLogger->debug(
"SQL ERROR: " . $error .
"\n" );
1085 if ( $var ===
'*' ) {
1102 if ( $row !==
false ) {
1103 return reset( $row );
1110 $table, $var, $cond =
'',
$fname = __METHOD__,
$options = [], $join_conds = []
1112 if ( $var ===
'*' ) {
1114 } elseif ( !is_string( $var ) ) {
1123 if (
$res ===
false ) {
1128 foreach (
$res as $row ) {
1129 $values[] = $row->$var;
1145 $preLimitTail = $postLimitTail =
'';
1151 if ( is_numeric( $key ) ) {
1152 $noKeyOptions[$option] =
true;
1160 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1161 $postLimitTail .=
' FOR UPDATE';
1164 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1165 $postLimitTail .=
' LOCK IN SHARE MODE';
1168 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1169 $startOpts .=
'DISTINCT';
1172 # Various MySQL extensions
1173 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1174 $startOpts .=
' /*! STRAIGHT_JOIN */';
1177 if ( isset( $noKeyOptions[
'HIGH_PRIORITY'] ) ) {
1178 $startOpts .=
' HIGH_PRIORITY';
1181 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1182 $startOpts .=
' SQL_BIG_RESULT';
1185 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1186 $startOpts .=
' SQL_BUFFER_RESULT';
1189 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1190 $startOpts .=
' SQL_SMALL_RESULT';
1193 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1194 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1197 if ( isset( $noKeyOptions[
'SQL_CACHE'] ) ) {
1198 $startOpts .=
' SQL_CACHE';
1201 if ( isset( $noKeyOptions[
'SQL_NO_CACHE'] ) ) {
1202 $startOpts .=
' SQL_NO_CACHE';
1205 if ( isset(
$options[
'USE INDEX'] ) && is_string(
$options[
'USE INDEX'] ) ) {
1210 if ( isset(
$options[
'IGNORE INDEX'] ) && is_string(
$options[
'IGNORE INDEX'] ) ) {
1216 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1229 if ( isset(
$options[
'GROUP BY'] ) ) {
1230 $gb = is_array(
$options[
'GROUP BY'] )
1231 ? implode(
',',
$options[
'GROUP BY'] )
1233 $sql .=
' GROUP BY ' . $gb;
1235 if ( isset(
$options[
'HAVING'] ) ) {
1236 $having = is_array(
$options[
'HAVING'] )
1239 $sql .=
' HAVING ' . $having;
1254 if ( isset(
$options[
'ORDER BY'] ) ) {
1255 $ob = is_array(
$options[
'ORDER BY'] )
1256 ? implode(
',',
$options[
'ORDER BY'] )
1259 return ' ORDER BY ' . $ob;
1266 $options = [], $join_conds = [] ) {
1275 if ( is_array(
$vars ) ) {
1280 $useIndexes = ( isset(
$options[
'USE INDEX'] ) && is_array(
$options[
'USE INDEX'] ) )
1284 isset(
$options[
'IGNORE INDEX'] ) &&
1285 is_array(
$options[
'IGNORE INDEX'] )
1290 if ( is_array( $table ) ) {
1293 $table, $useIndexes, $ignoreIndexes, $join_conds );
1294 } elseif ( $table !=
'' ) {
1295 if ( $table[0] ==
' ' ) {
1296 $from =
' FROM ' . $table;
1300 [ $table ], $useIndexes, $ignoreIndexes, [] );
1306 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1309 if ( !empty( $conds ) ) {
1310 if ( is_array( $conds ) ) {
1313 $sql =
"SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1314 "WHERE $conds $preLimitTail";
1316 $sql =
"SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1319 if ( isset(
$options[
'LIMIT'] ) ) {
1323 $sql =
"$sql $postLimitTail";
1325 if ( isset(
$options[
'EXPLAIN'] ) ) {
1326 $sql =
'EXPLAIN ' . $sql;
1339 if (
$res ===
false ) {
1360 $rows = ( isset( $row[
'rowcount'] ) ) ? (
int)$row[
'rowcount'] : 0;
1374 $res = $this->
query(
"SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName",
$fname );
1378 $rows = ( isset( $row[
'rowcount'] ) ) ? (
int)$row[
'rowcount'] : 0;
1393 # This does the same as the regexp below would do, but in such a way
1394 # as to avoid crashing php on some large strings.
1395 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1397 $sql = str_replace(
"\\\\",
'', $sql );
1398 $sql = str_replace(
"\\'",
'', $sql );
1399 $sql = str_replace(
"\\\"",
'', $sql );
1400 $sql = preg_replace(
"/'.*'/s",
"'X'", $sql );
1401 $sql = preg_replace(
'/".*"/s',
"'X'", $sql );
1403 # All newlines, tabs, etc replaced by single space
1404 $sql = preg_replace(
'/\s+/',
' ', $sql );
1407 # except the ones surrounded by characters, e.g. l10n
1408 $sql = preg_replace(
'/-?\d+(,-?\d+)+/s',
'N,...,N', $sql );
1409 $sql = preg_replace(
'/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s',
'N', $sql );
1415 $info = $this->
fieldInfo( $table, $field );
1426 if ( is_null( $info ) ) {
1429 return $info !==
false;
1434 $tableRaw = $this->
tableName( $table,
'raw' );
1435 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1440 $ignoreErrors =
true;
1441 $res = $this->
query(
"SELECT 1 FROM $table LIMIT 1",
$fname, $ignoreErrors );
1447 $indexInfo = $this->
indexInfo( $table, $index );
1449 if ( !$indexInfo ) {
1453 return !$indexInfo[0]->Non_unique;
1467 # No rows to insert, easy just return now
1468 if ( !
count( $a ) ) {
1479 if ( isset(
$options[
'fileHandle'] ) ) {
1484 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1486 $keys = array_keys( $a[0] );
1489 $keys = array_keys( $a );
1493 " INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
1497 foreach ( $a
as $row ) {
1503 $sql .=
'(' . $this->
makeList( $row ) .
')';
1506 $sql .=
'(' . $this->
makeList( $a ) .
')';
1509 if ( $fh !==
null &&
false === fwrite( $fh, $sql ) ) {
1511 } elseif ( $fh !==
null ) {
1531 if ( in_array(
'IGNORE',
$options ) ) {
1547 return implode(
' ', $opts );
1555 if ( $conds !== [] && $conds !==
'*' ) {
1563 if ( !is_array( $a ) ) {
1564 throw new DBUnexpectedError( $this, __METHOD__ .
' called with incorrect parameters' );
1570 foreach ( $a
as $field =>
$value ) {
1584 $list .=
"($value)";
1591 $includeNull =
false;
1592 foreach ( array_keys(
$value,
null,
true )
as $nullKey ) {
1593 $includeNull =
true;
1594 unset(
$value[$nullKey] );
1597 throw new InvalidArgumentException(
1598 __METHOD__ .
": empty input for field $field" );
1601 $list .=
"$field IS NULL";
1604 if ( $includeNull ) {
1618 if ( $includeNull ) {
1619 $list .=
" OR $field IS NULL)";
1622 } elseif (
$value ===
null ) {
1624 $list .=
"$field IS ";
1626 $list .=
"$field = ";
1633 $list .=
"$field = ";
1645 foreach ( $data
as $base => $sub ) {
1646 if (
count( $sub ) ) {
1648 [ $baseKey =>
$base, $subKey => array_keys( $sub ) ],
1669 public function bitAnd( $fieldLeft, $fieldRight ) {
1670 return "($fieldLeft & $fieldRight)";
1673 public function bitOr( $fieldLeft, $fieldRight ) {
1674 return "($fieldLeft | $fieldRight)";
1678 return 'CONCAT(' . implode(
',', $stringList ) .
')';
1682 $delim, $table, $field, $conds =
'', $join_conds = []
1684 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->
addQuotes( $delim ) .
')';
1686 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1694 # Stub. Shouldn't cause serious problems if it's not overridden, but
1695 # if your database engine supports a concept similar to MySQL's
1696 # databases you may as well.
1697 $this->mDBname = $db;
1711 # Skip the entire process when we have a string quoted on both ends.
1712 # Note that we check the end so that we will still quote any use of
1713 # use of `database`.table. But won't break things if someone wants
1714 # to query a database table with a dot in the name.
1719 # Lets test for any bits of text that should never show up in a table
1720 # name. Basically anything like JOIN or ON which are actually part of
1721 # SQL queries, but may end up inside of the table value to combine
1722 # sql. Such as how the API is doing.
1723 # Note that we use a whitespace test rather than a \b test to avoid
1724 # any remote case where a word like on may be inside of a table name
1725 # surrounded by symbols which may be considered word breaks.
1726 if ( preg_match(
'/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i',
$name ) !== 0 ) {
1730 # Split database and table into proper variables.
1731 # We reverse the explode so that database.table and table both output
1732 # the correct table.
1733 $dbDetails = explode(
'.',
$name, 3 );
1734 if (
count( $dbDetails ) == 3 ) {
1735 list( $database, $schema, $table ) = $dbDetails;
1736 # We don't want any prefix added in this case
1738 } elseif (
count( $dbDetails ) == 2 ) {
1739 list( $database, $table ) = $dbDetails;
1740 # We don't want any prefix added in this case
1742 # In dbs that support it, $database may actually be the schema
1743 # but that doesn't affect any of the functionality here
1746 list( $table ) = $dbDetails;
1747 if ( isset( $this->tableAliases[$table] ) ) {
1748 $database = $this->tableAliases[$table][
'dbname'];
1749 $schema = is_string( $this->tableAliases[$table][
'schema'] )
1750 ? $this->tableAliases[$table][
'schema']
1752 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
1753 ? $this->tableAliases[$table][
'prefix']
1762 # Quote $table and apply the prefix if not quoted.
1763 # $tableName might be empty if this is called from Database::replaceVars()
1764 $tableName =
"{$prefix}{$table}";
1765 if ( $format ===
'quoted'
1767 && $tableName !==
''
1772 # Quote $schema and $database and merge them with the table name if needed
1786 if ( strlen( $namespace ) ) {
1790 $relation = $namespace .
'.' . $relation;
1797 $inArray = func_get_args();
1800 foreach ( $inArray
as $name ) {
1808 $inArray = func_get_args();
1811 foreach ( $inArray
as $name ) {
1827 if ( !$alias || $alias ==
$name ) {
1842 foreach (
$tables as $alias => $table ) {
1843 if ( is_numeric( $alias ) ) {
1861 if ( !$alias || (
string)$alias === (
string)
$name ) {
1876 foreach ( $fields
as $alias => $field ) {
1877 if ( is_numeric( $alias ) ) {
1897 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1901 $use_index = (
array)$use_index;
1902 $ignore_index = (
array)$ignore_index;
1903 $join_conds = (
array)$join_conds;
1905 foreach (
$tables as $alias => $table ) {
1906 if ( !is_string( $alias ) ) {
1911 if ( isset( $join_conds[$alias] ) ) {
1912 list( $joinType, $conds ) = $join_conds[$alias];
1913 $tableClause = $joinType;
1915 if ( isset( $use_index[$alias] ) ) {
1918 $tableClause .=
' ' . $use;
1921 if ( isset( $ignore_index[$alias] ) ) {
1923 implode(
',', (
array)$ignore_index[$alias] ) );
1924 if ( $ignore !=
'' ) {
1925 $tableClause .=
' ' . $ignore;
1930 $tableClause .=
' ON (' . $on .
')';
1933 $retJOIN[] = $tableClause;
1934 } elseif ( isset( $use_index[$alias] ) ) {
1938 implode(
',', (
array)$use_index[$alias] )
1941 $ret[] = $tableClause;
1942 } elseif ( isset( $ignore_index[$alias] ) ) {
1946 implode(
',', (
array)$ignore_index[$alias] )
1949 $ret[] = $tableClause;
1953 $ret[] = $tableClause;
1958 $implicitJoins = !empty(
$ret ) ? implode(
',',
$ret ) :
"";
1959 $explicitJoins = !empty( $retJOIN ) ? implode(
' ', $retJOIN ) :
"";
1962 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
1976 if (
$s instanceof
Blob ) {
1979 if (
$s ===
null ) {
1981 } elseif ( is_bool(
$s ) ) {
1984 # This will also quote numeric values. This should be harmless,
1985 # and protects against weird problems that occur when they really
1986 # _are_ strings such as article titles and string->number->string
1987 # conversion is not 1:1.
2002 return '"' . str_replace(
'"',
'""',
$s ) .
'"';
2015 return $name[0] ==
'"' && substr(
$name, -1, 1 ) ==
'"';
2023 return str_replace( [ $escapeChar,
'%',
'_' ],
2024 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
2095 $quotedTable = $this->
tableName( $table );
2097 if (
count( $rows ) == 0 ) {
2102 if ( !is_array( reset( $rows ) ) ) {
2107 foreach ( $rows
as $row ) {
2108 # Delete rows which collide
2109 if ( $uniqueIndexes ) {
2110 $sql =
"DELETE FROM $quotedTable WHERE ";
2112 foreach ( $uniqueIndexes
as $index ) {
2119 if ( is_array( $index ) ) {
2121 foreach ( $index
as $col ) {
2127 $sql .= $col .
'=' . $this->
addQuotes( $row[$col] );
2130 $sql .= $index .
'=' . $this->
addQuotes( $row[$index] );
2137 # Now insert the row
2156 if ( !is_array( reset( $rows ) ) ) {
2160 $sql =
"REPLACE INTO $table (" . implode(
',', array_keys( $rows[0] ) ) .
') VALUES ';
2163 foreach ( $rows
as $row ) {
2170 $sql .=
'(' . $this->
makeList( $row ) .
')';
2179 if ( !
count( $rows ) ) {
2183 if ( !is_array( reset( $rows ) ) ) {
2187 if (
count( $uniqueIndexes ) ) {
2189 foreach ( $rows
as $row ) {
2190 foreach ( $uniqueIndexes
as $index ) {
2191 $index = is_array( $index ) ? $index : [ $index ];
2193 foreach ( $index
as $column ) {
2194 $rowKey[$column] = $row[$column];
2206 $this->
begin(
$fname, self::TRANSACTION_INTERNAL );
2209 # Update any existing conflicting row(s)
2210 if ( $where !==
false ) {
2215 # Now insert any non-conflicting row(s)
2216 $ok = $this->
insert( $table, $rows,
$fname, [
'IGNORE' ] ) && $ok;
2217 }
catch ( Exception
$e ) {
2230 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2237 $delTable = $this->
tableName( $delTable );
2238 $joinTable = $this->
tableName( $joinTable );
2239 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2240 if ( $conds !=
'*' ) {
2250 $sql =
"SHOW COLUMNS FROM $table LIKE \"$field\";";
2251 $res = $this->
query( $sql, __METHOD__ );
2256 if ( preg_match(
'/\((.*)\)/', $row->Type, $m ) ) {
2265 public function delete( $table, $conds,
$fname = __METHOD__ ) {
2267 throw new DBUnexpectedError( $this, __METHOD__ .
' called with no conditions' );
2271 $sql =
"DELETE FROM $table";
2273 if ( $conds !=
'*' ) {
2274 if ( is_array( $conds ) ) {
2277 $sql .=
' WHERE ' . $conds;
2284 $destTable, $srcTable, $varMap, $conds,
2285 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2287 if ( $this->cliMode ) {
2305 foreach ( $varMap
as $dstColumn => $sourceColumnOrSql ) {
2308 $selectOptions[] =
'FOR UPDATE';
2309 $res = $this->
select( $srcTable, implode(
',', $fields ), $conds,
$fname, $selectOptions );
2315 foreach (
$res as $row ) {
2316 $rows[] = (
array)$row;
2319 return $this->
insert( $destTable, $rows,
$fname, $insertOptions );
2324 $insertOptions = [], $selectOptions = []
2326 $destTable = $this->
tableName( $destTable );
2328 if ( !is_array( $insertOptions ) ) {
2329 $insertOptions = [ $insertOptions ];
2334 if ( !is_array( $selectOptions ) ) {
2335 $selectOptions = [ $selectOptions ];
2341 if ( is_array( $srcTable ) ) {
2342 $srcTable = implode(
',', array_map( [ $this,
'tableName' ], $srcTable ) );
2344 $srcTable = $this->
tableName( $srcTable );
2347 $sql =
"INSERT $insertOptions" .
2348 " INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
2349 " SELECT $startOpts " . implode(
',', $varMap ) .
2350 " FROM $srcTable $useIndex $ignoreIndex ";
2352 if ( $conds !=
'*' ) {
2353 if ( is_array( $conds ) ) {
2356 $sql .=
" WHERE $conds";
2359 $sql .=
" $tailOpts";
2384 if ( !is_numeric(
$limit ) ) {
2386 "Invalid non-numeric limit passed to limitResult()\n" );
2389 return "$sql LIMIT "
2390 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
2399 $glue = $all ?
') UNION ALL (' :
') UNION (';
2401 return '(' . implode( $glue, $sqls ) .
')';
2405 if ( is_array( $cond ) ) {
2409 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2413 return "REPLACE({$orig}, {$old}, {$new})";
2447 $args = func_get_args();
2448 $function = array_shift(
$args );
2451 $this->
begin( __METHOD__ );
2458 $retVal = call_user_func_array( $function,
$args );
2463 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2469 }
while ( --$tries > 0 );
2471 if ( $tries <= 0 ) {
2476 $this->
commit( __METHOD__ );
2483 # Real waits are implemented in the subclass.
2502 if ( !$this->mTrxLevel ) {
2505 $this->mTrxEndCallbacks[] = [ $callback,
$fname ];
2509 $this->mTrxIdleCallbacks[] = [ $callback,
$fname ];
2510 if ( !$this->mTrxLevel ) {
2516 if ( $this->mTrxLevel ) {
2517 $this->mTrxPreCommitCallbacks[] = [ $callback,
$fname ];
2522 call_user_func( $callback );
2524 }
catch ( Exception
$e ) {
2525 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
2533 $this->mTrxRecurringCallbacks[
$name] = $callback;
2535 unset( $this->mTrxRecurringCallbacks[
$name] );
2548 $this->mTrxEndCallbacksSuppressed = $suppress;
2561 if ( $this->mTrxEndCallbacksSuppressed ) {
2569 $callbacks = array_merge(
2570 $this->mTrxIdleCallbacks,
2571 $this->mTrxEndCallbacks
2573 $this->mTrxIdleCallbacks = [];
2574 $this->mTrxEndCallbacks = [];
2575 foreach ( $callbacks
as $callback ) {
2577 list( $phpCallback ) = $callback;
2579 call_user_func_array( $phpCallback, [ $trigger ] );
2585 }
catch ( Exception $ex ) {
2586 call_user_func( $this->errorLogger, $ex );
2591 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
2595 }
while (
count( $this->mTrxIdleCallbacks ) );
2597 if (
$e instanceof Exception ) {
2614 $this->mTrxPreCommitCallbacks = [];
2615 foreach ( $callbacks
as $callback ) {
2617 list( $phpCallback ) = $callback;
2618 call_user_func( $phpCallback );
2619 }
catch ( Exception $ex ) {
2620 call_user_func( $this->errorLogger, $ex );
2624 }
while (
count( $this->mTrxPreCommitCallbacks ) );
2626 if (
$e instanceof Exception ) {
2641 if ( $this->mTrxEndCallbacksSuppressed ) {
2648 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2650 $phpCallback( $trigger, $this );
2651 }
catch ( Exception $ex ) {
2652 call_user_func( $this->errorLogger, $ex );
2657 if (
$e instanceof Exception ) {
2663 if ( !$this->mTrxLevel ) {
2664 $this->
begin( $fname, self::TRANSACTION_INTERNAL );
2668 $this->mTrxAutomaticAtomic =
true;
2672 $this->mTrxAtomicLevels[] =
$fname;
2676 if ( !$this->mTrxLevel ) {
2677 throw new DBUnexpectedError( $this,
"No atomic transaction is open (got $fname)." );
2679 if ( !$this->mTrxAtomicLevels ||
2680 array_pop( $this->mTrxAtomicLevels ) !==
$fname
2682 throw new DBUnexpectedError( $this,
"Invalid atomic section ended (got $fname)." );
2685 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2686 $this->
commit( $fname, self::FLUSHING_INTERNAL );
2693 $res = call_user_func_array( $callback, [ $this,
$fname ] );
2694 }
catch ( Exception
$e ) {
2695 $this->
rollback( $fname, self::FLUSHING_INTERNAL );
2703 final public function begin(
$fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2705 if ( $this->mTrxLevel ) {
2706 if ( $this->mTrxAtomicLevels ) {
2707 $levels = implode(
', ', $this->mTrxAtomicLevels );
2708 $msg =
"$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2710 } elseif ( !$this->mTrxAutomatic ) {
2711 $msg =
"$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2715 $msg =
"$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2716 $this->queryLogger->error( $msg );
2721 $msg =
"$fname: Implicit transaction expected (DBO_TRX set).";
2722 $this->queryLogger->error( $msg );
2730 $this->mTrxTimestamp = microtime(
true );
2731 $this->mTrxFname =
$fname;
2732 $this->mTrxDoneWrites =
false;
2733 $this->mTrxAutomaticAtomic =
false;
2734 $this->mTrxAtomicLevels = [];
2735 $this->mTrxShortId = sprintf(
'%06x', mt_rand( 0, 0xffffff ) );
2736 $this->mTrxWriteDuration = 0.0;
2737 $this->mTrxWriteQueryCount = 0;
2738 $this->mTrxWriteAdjDuration = 0.0;
2739 $this->mTrxWriteAdjQueryCount = 0;
2740 $this->mTrxWriteCallers = [];
2745 $this->mTrxReplicaLag =
$status[
'lag'] + ( microtime(
true ) -
$status[
'since'] );
2749 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2759 $this->
query(
'BEGIN', $fname );
2760 $this->mTrxLevel = 1;
2764 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2766 $levels = implode(
', ', $this->mTrxAtomicLevels );
2769 "$fname: Got COMMIT while atomic sections $levels are still open."
2773 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2774 if ( !$this->mTrxLevel ) {
2776 } elseif ( !$this->mTrxAutomatic ) {
2779 "$fname: Flushing an explicit transaction, getting out of sync."
2783 if ( !$this->mTrxLevel ) {
2784 $this->queryLogger->error(
2785 "$fname: No transaction to commit, something got out of sync." );
2787 } elseif ( $this->mTrxAutomatic ) {
2789 $msg =
"$fname: Explicit commit of implicit transaction.";
2790 $this->queryLogger->error( $msg );
2801 if ( $this->mTrxDoneWrites ) {
2802 $this->mLastWriteTime = microtime(
true );
2803 $this->trxProfiler->transactionWritingOut(
2804 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2818 if ( $this->mTrxLevel ) {
2819 $this->
query(
'COMMIT', $fname );
2820 $this->mTrxLevel = 0;
2825 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2826 if ( !$this->mTrxLevel ) {
2830 if ( !$this->mTrxLevel ) {
2831 $this->queryLogger->error(
2832 "$fname: No transaction to rollback, something got out of sync." );
2837 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2846 $this->mTrxAtomicLevels = [];
2847 if ( $this->mTrxDoneWrites ) {
2848 $this->trxProfiler->transactionWritingOut(
2849 $this->mServer, $this->mDBname, $this->mTrxShortId );
2852 $this->mTrxIdleCallbacks = [];
2853 $this->mTrxPreCommitCallbacks = [];
2865 if ( $this->mTrxLevel ) {
2866 # Disconnects cause rollback anyway, so ignore those errors
2867 $ignoreErrors =
true;
2868 $this->
query(
'ROLLBACK', $fname, $ignoreErrors );
2869 $this->mTrxLevel = 0;
2879 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2883 $this->
commit( $fname, self::FLUSHING_INTERNAL );
2891 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
2893 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
2897 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
2901 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
2905 $t =
new ConvertibleTimestamp( $ts );
2907 return $t->getTimestamp( TS_MW );
2911 if ( is_null( $ts ) ) {
2936 } elseif (
$result ===
true ) {
2944 public function ping( &$rtt =
null ) {
2946 if ( $this->
isOpen() && ( microtime(
true ) - $this->lastPing ) < self::PING_TTL ) {
2947 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2955 $ok = ( $this->
query( self::PING_QUERY, __METHOD__,
true ) !==
false );
2970 $this->mOpened =
false;
2971 $this->mConn =
false;
2973 $this->
open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2974 $this->lastPing = microtime(
true );
2999 return $this->mTrxLevel
3013 'since' => microtime(
true )
3036 $res = [
'lag' => 0,
'since' => INF,
'pending' =>
false ];
3037 foreach ( func_get_args()
as $db ) {
3039 $status = $db->getSessionLagStatus();
3040 if (
$status[
'lag'] ===
false ) {
3041 $res[
'lag'] =
false;
3042 } elseif (
$res[
'lag'] !==
false ) {
3046 $res[
'pending'] =
$res[
'pending'] ?: $db->writesPending();
3065 if ( $b instanceof
Blob ) {
3076 callable $lineCallback =
null,
3077 callable $resultCallback =
null,
3079 callable $inputCallback =
null
3081 MediaWiki\suppressWarnings();
3082 $fp = fopen( $filename,
'r' );
3083 MediaWiki\restoreWarnings();
3085 if (
false === $fp ) {
3086 throw new RuntimeException(
"Could not open \"{$filename}\".\n" );
3090 $fname = __METHOD__ .
"( $filename )";
3095 $fp, $lineCallback, $resultCallback,
$fname, $inputCallback );
3096 }
catch ( Exception
$e ) {
3107 $this->mSchemaVars =
$vars;
3112 callable $lineCallback =
null,
3113 callable $resultCallback =
null,
3115 callable $inputCallback =
null
3119 while ( !feof( $fp ) ) {
3120 if ( $lineCallback ) {
3121 call_user_func( $lineCallback );
3124 $line = trim( fgets( $fp ) );
3126 if (
$line ==
'' ) {
3142 if ( $done || feof( $fp ) ) {
3145 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3148 if ( $resultCallback ) {
3149 call_user_func( $resultCallback,
$res, $this );
3152 if (
false ===
$res ) {
3155 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3173 if ( $this->delimiter ) {
3175 $newLine = preg_replace(
3176 '/' . preg_quote( $this->delimiter,
'/' ) .
'$/',
'', $newLine );
3177 if ( $newLine != $prev ) {
3207 return preg_replace_callback(
3209 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3210 \'\{\$ (\w+) }\' | # 3. addQuotes
3211 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3212 /\*\$ (\w+) \*/ # 5. leave unencoded
3217 if ( isset( $m[1] ) && $m[1] !==
'' ) {
3218 if ( $m[1] ===
'i' ) {
3223 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3],
$vars ) ) {
3225 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4],
$vars ) ) {
3227 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5],
$vars ) ) {
3228 return $vars[$m[5]];
3244 if ( $this->mSchemaVars ) {
3267 public function lock( $lockName, $method, $timeout = 5 ) {
3268 $this->mNamedLocksHeld[$lockName] = 1;
3273 public function unlock( $lockName, $method ) {
3274 unset( $this->mNamedLocksHeld[$lockName] );
3285 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3289 if ( !$this->
lock( $lockKey,
$fname, $timeout ) ) {
3293 $unlocker =
new ScopedCallback(
function ()
use ( $lockKey,
$fname ) {
3309 $this->
commit( $fname, self::FLUSHING_INTERNAL );
3324 throw new DBUnexpectedError( $this,
"Transaction writes or callbacks still pending." );
3359 public function dropTable( $tableName, $fName = __METHOD__ ) {
3360 if ( !$this->
tableExists( $tableName, $fName ) ) {
3363 $sql =
"DROP TABLE " . $this->
tableName( $tableName ) .
" CASCADE";
3365 return $this->
query( $sql, $fName );
3373 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() )
3379 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() ) {
3383 return ConvertibleTimestamp::convert( $format, $expiry );
3398 $reason = $this->
getLBInfo(
'readOnlyReason' );
3400 return is_string( $reason ) ? $reason :
false;
3404 $this->tableAliases = $aliases;
3427 if ( !$this->mConn ) {
3430 'DB connection was already closed or the connection dropped.'
3450 $this->connLogger->warning(
3451 "Cloning " .
static::class .
" is not recomended; forking connection:\n" .
3452 (
new RuntimeException() )->getTraceAsString()
3457 $this->mOpened =
false;
3458 $this->mConn =
false;
3459 $this->mTrxEndCallbacks = [];
3461 $this->
open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3462 $this->lastPing = microtime(
true );
3472 throw new RuntimeException(
'Database serialization may cause problems, since ' .
3473 'the connection is not restored on wakeup.' );
3480 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3481 trigger_error(
"Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3485 if ( $danglingWriters ) {
3486 $fnames = implode(
', ', $danglingWriters );
3487 trigger_error(
"DB transaction writes or callbacks still pending ($fnames)." );
3490 if ( $this->mConn ) {
3493 \MediaWiki\suppressWarnings();
3495 \MediaWiki\restoreWarnings();
3496 $this->mConn =
false;
3497 $this->mOpened =
false;
processing should stop and the error should be shown to the user * false
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Simple store for keeping values in an associative array for the current process.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
interface is intended to be more or less compatible with the PHP memcached client.
Allows to change the fields on the form that will be generated $name
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 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
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
This document describes the state of Postgres support in MediaWiki
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
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
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
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
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
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Class to handle database/prefix specification for IDatabase domains.
Advanced database interface for IDatabase handles that include maintenance methods.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
the array() calling protocol came about after MediaWiki 1.4rc1.