Go to the documentation of this file.
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Timestamp\ConvertibleTimestamp;
37 use InvalidArgumentException;
38 use UnexpectedValueException;
65 const ATTR_DB_LEVEL_LOCKING =
'db-level-locking';
67 const ATTR_SCHEMAS_AS_TABLE_GROUPS =
'supports-schemas';
70 const NEW_UNCONNECTED = 0;
72 const NEW_CONNECTED = 1;
279 const STATUS_TRX_ERROR = 1;
281 const STATUS_TRX_OK = 2;
283 const STATUS_TRX_NONE = 3;
286 const TEMP_NORMAL = 1;
288 const TEMP_PSEUDO_PERMANENT = 2;
295 foreach ( [
'host',
'user',
'password',
'dbname',
'schema',
'tablePrefix' ]
as $name ) {
299 $this->cliMode =
$params[
'cliMode'];
301 $this->agent = str_replace(
'/',
'-',
$params[
'agent'] );
303 $this->flags =
$params[
'flags'];
305 if ( $this->cliMode ) {
314 $this->sessionVars =
$params[
'variables'];
318 $this->profiler = is_callable(
$params[
'profiler'] ) ?
$params[
'profiler'] :
null;
319 $this->trxProfiler =
$params[
'trxProfiler'];
320 $this->connLogger =
$params[
'connLogger'];
321 $this->queryLogger =
$params[
'queryLogger'];
322 $this->errorLogger =
$params[
'errorLogger'];
323 $this->deprecationLogger =
$params[
'deprecationLogger'];
325 if ( isset(
$params[
'nonNativeInsertSelectBatchSize'] ) ) {
326 $this->nonNativeInsertSelectBatchSize =
$params[
'nonNativeInsertSelectBatchSize'];
347 throw new LogicException( __METHOD__ .
': already connected.' );
361 if ( strlen( $this->connectionParams[
'user'] ) ) {
363 $this->connectionParams[
'host'],
364 $this->connectionParams[
'user'],
365 $this->connectionParams[
'password'],
366 $this->connectionParams[
'dbname'],
367 $this->connectionParams[
'schema'],
368 $this->connectionParams[
'tablePrefix']
371 throw new InvalidArgumentException(
"No database user provided." );
434 final public static function factory( $dbType, $p = [], $connect = self::NEW_CONNECTED ) {
437 if ( class_exists( $class ) && is_subclass_of( $class,
IDatabase::class ) ) {
439 $p[
'host'] = $p[
'host'] ??
false;
440 $p[
'user'] = $p[
'user'] ??
false;
441 $p[
'password'] = $p[
'password'] ??
false;
442 $p[
'dbname'] = $p[
'dbname'] ??
false;
443 $p[
'flags'] = $p[
'flags'] ?? 0;
444 $p[
'variables'] = $p[
'variables'] ?? [];
445 $p[
'tablePrefix'] = $p[
'tablePrefix'] ??
'';
446 $p[
'schema'] = $p[
'schema'] ??
null;
447 $p[
'cliMode'] = $p[
'cliMode'] ?? ( PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg' );
448 $p[
'agent'] = $p[
'agent'] ??
'';
449 if ( !isset( $p[
'connLogger'] ) ) {
450 $p[
'connLogger'] =
new NullLogger();
452 if ( !isset( $p[
'queryLogger'] ) ) {
453 $p[
'queryLogger'] =
new NullLogger();
455 $p[
'profiler'] = $p[
'profiler'] ??
null;
456 if ( !isset( $p[
'trxProfiler'] ) ) {
459 if ( !isset( $p[
'errorLogger'] ) ) {
460 $p[
'errorLogger'] =
function ( Exception
$e ) {
461 trigger_error( get_class(
$e ) .
': ' .
$e->getMessage(), E_USER_WARNING );
464 if ( !isset( $p[
'deprecationLogger'] ) ) {
465 $p[
'deprecationLogger'] =
function ( $msg ) {
466 trigger_error( $msg, E_USER_DEPRECATED );
471 $conn =
new $class( $p );
472 if ( $connect == self::NEW_CONNECTED ) {
473 $conn->initConnection();
491 self::ATTR_DB_LEVEL_LOCKING =>
false,
492 self::ATTR_SCHEMAS_AS_TABLE_GROUPS =>
false
497 return call_user_func( [ $class,
'getAttributes' ] ) + $defaults;
506 private static function getClass( $dbType, $driver =
null ) {
513 static $builtinTypes = [
520 $dbType = strtolower( $dbType );
523 if ( isset( $builtinTypes[$dbType] ) ) {
524 $possibleDrivers = $builtinTypes[$dbType];
525 if ( is_string( $possibleDrivers ) ) {
526 $class = $possibleDrivers;
527 } elseif ( (
string)$driver !==
'' ) {
528 if ( !isset( $possibleDrivers[$driver] ) ) {
529 throw new InvalidArgumentException( __METHOD__ .
530 " type '$dbType' does not support driver '{$driver}'" );
533 $class = $possibleDrivers[$driver];
535 foreach ( $possibleDrivers
as $posDriver => $possibleClass ) {
536 if ( extension_loaded( $posDriver ) ) {
537 $class = $possibleClass;
543 $class =
'Database' . ucfirst( $dbType );
546 if ( $class ===
false ) {
547 throw new InvalidArgumentException( __METHOD__ .
548 " no viable database extension found for type '$dbType'" );
570 $this->queryLogger = $logger;
605 $old = $this->currentDomain->getTablePrefix();
606 if ( $prefix !==
null ) {
608 $this->currentDomain->getDatabase(),
609 $this->currentDomain->getSchema(),
618 if ( strlen( $schema ) && $this->
getDBname() ===
null ) {
619 throw new DBUnexpectedError( $this,
"Cannot set schema to '$schema'; no database set." );
622 $old = $this->currentDomain->getSchema();
623 if ( $schema !==
null ) {
625 $this->currentDomain->getDatabase(),
627 strlen( $schema ) ? $schema :
null,
628 $this->currentDomain->getTablePrefix()
643 if ( is_null(
$name ) ) {
647 if ( array_key_exists(
$name, $this->lbInfo ) ) {
648 return $this->lbInfo[
$name];
655 if ( is_null(
$value ) ) {
656 $this->lbInfo =
$name;
663 $this->lazyMasterHandle =
$conn;
692 return $this->lastWriteTime ?:
false;
701 $this->trxDoneWrites ||
702 $this->trxIdleCallbacks ||
703 $this->trxPreCommitCallbacks ||
720 return is_string( $id ) ? $id :
null;
729 } elseif ( !$this->trxDoneWrites ) {
734 case self::ESTIMATE_DB_APPLY:
747 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
748 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
751 $applyTime += self::TINY_WRITE_SEC * $omitted;
757 return $this->
trxLevel ? $this->trxWriteCallers : [];
775 $this->trxIdleCallbacks,
776 $this->trxPreCommitCallbacks,
777 $this->trxEndCallbacks
779 foreach ( $callbacks
as $callback ) {
780 $fnames[] = $callback[1];
791 return array_reduce( $this->trxAtomicLevels,
function ( $accum, $v ) {
792 return $accum ===
null ? $v[0] :
"$accum, " . $v[0];
800 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
802 throw new UnexpectedValueException(
"Modifying DBO_IGNORE is not allowed." );
805 if ( $remember === self::REMEMBER_PRIOR ) {
806 array_push( $this->priorFlags, $this->flags );
808 $this->flags |= $flag;
811 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
813 throw new UnexpectedValueException(
"Modifying DBO_IGNORE is not allowed." );
816 if ( $remember === self::REMEMBER_PRIOR ) {
817 array_push( $this->priorFlags, $this->flags );
819 $this->flags &= ~$flag;
823 if ( !$this->priorFlags ) {
827 if ( $state === self::RESTORE_INITIAL ) {
828 $this->flags = reset( $this->priorFlags );
829 $this->priorFlags = [];
831 $this->flags = array_pop( $this->priorFlags );
836 return (
bool)( $this->flags & $flag );
849 return $this->currentDomain->getId();
877 $this->phpError =
false;
878 $this->htmlErrors = ini_set(
'html_errors',
'0' );
879 set_error_handler( [ $this,
'connectionErrorLogger' ] );
888 restore_error_handler();
889 if ( $this->htmlErrors !==
false ) {
890 ini_set(
'html_errors', $this->htmlErrors );
900 if ( $this->phpError ) {
901 $error = preg_replace(
'!\[<a.*</a>\]!',
'', $this->phpError );
902 $error = preg_replace(
'!^.*?:\s?(.*)$!',
'$1', $error );
918 $this->phpError = $errstr;
930 'db_server' => $this->
server,
932 'db_user' => $this->
user,
946 if ( $this->trxAtomicLevels ) {
951 __METHOD__ .
": atomic sections $levels are still open."
953 } elseif ( $this->trxAutomatic ) {
960 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
968 __METHOD__ .
": transaction is still open (from {$this->trxFname})."
972 if ( $this->trxEndCallbacksSuppressed ) {
975 __METHOD__ .
': callbacks are suppressed; cannot properly commit.'
980 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
990 $this->opened =
false;
993 if ( $exception instanceof Exception ) {
1005 throw new RuntimeException(
1006 "Transaction callbacks are still pending:\n" . implode(
', ', $fnames )
1023 if ( !$this->
isOpen() ) {
1034 if ( $this->
getLBInfo(
'replica' ) ===
true ) {
1037 'Write operations are not allowed on replica database connections.'
1041 if ( $reason !==
false ) {
1059 call_user_func( $this->deprecationLogger,
'Use of ' . __METHOD__ .
' is deprecated.' );
1081 abstract protected function doQuery( $sql );
1114 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|\(SELECT)\b/i',
1124 return preg_match(
'/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) :
null;
1143 [
'BEGIN',
'ROLLBACK',
'COMMIT',
'SET',
'SHOW',
'CREATE',
'ALTER' ],
1154 static $qt =
'[`"\']?(\w+)[`"\']?';
1157 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt .
'/i',
1161 $type = $pseudoPermanent ? self::TEMP_PSEUDO_PERMANENT : self::TEMP_NORMAL;
1165 } elseif ( preg_match(
1166 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt .
'/i',
1171 unset( $this->sessionTempTables[
$matches[1]] );
1174 } elseif ( preg_match(
1175 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt .
'/i',
1179 return $this->sessionTempTables[
$matches[1]] ??
null;
1180 } elseif ( preg_match(
1181 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt .
'/i',
1185 return $this->sessionTempTables[
$matches[1]] ??
null;
1196 $ignoreErrors = $this->
hasFlags(
$flags, self::QUERY_SILENCE_ERRORS );
1203 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1204 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1206 # Do not treat temporary table writes as "meaningful writes" that need committing.
1207 # Profile them as reads. Integration tests can override this behavior via $flags.
1208 $pseudoPermanent = $this->
hasFlags(
$flags, self::QUERY_PSEUDO_PERMANENT );
1210 $isEffectiveWrite = ( $tableType !== self::TEMP_NORMAL );
1211 # DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1212 if ( $isEffectiveWrite && $this->
hasFlags(
$flags, self::QUERY_REPLICA_ROLE ) ) {
1216 $isEffectiveWrite =
false;
1219 # Add trace comment to the begin of the sql string, right after the operator.
1220 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1221 $commentedSql = preg_replace(
'/\s|$/',
" /* $fname {$this->agent} */ ", $sql, 1 );
1223 # Send the query to the server and fetch any corresponding errors
1228 $recoverableSR =
false;
1229 $recoverableCL =
false;
1232 # Check if no meaningful session state was lost
1234 # Update session state tracking and try to restore the connection
1236 # Silently resend the query to the server if it is safe and possible
1237 if ( $recoverableCL && $reconnected ) {
1243 # Query probably causes disconnects; reconnect and do not re-run it
1246 $recoverableCL =
false;
1254 if (
$ret ===
false ) {
1255 if ( $priorTransaction ) {
1256 if ( $recoverableSR ) {
1257 # We're ignoring an error that caused just the current query to be aborted.
1258 # But log the cause so we can log a deprecation notice if a caller actually
1260 $this->trxStatusIgnoredCause = [ $lastError, $lastErrno,
$fname ];
1261 } elseif ( !$recoverableCL ) {
1262 # Either the query was aborted or all queries after BEGIN where aborted.
1263 # In the first case, the only options going forward are (a) ROLLBACK, or
1264 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1265 # option is ROLLBACK, since the snapshots would have been released.
1266 $this->
trxStatus = self::STATUS_TRX_ERROR;
1267 $this->trxStatusCause =
1269 $ignoreErrors =
false;
1270 $this->trxStatusIgnoredCause =
null;
1293 # Keep track of whether the transaction has write queries pending
1294 if ( $isEffectiveWrite ) {
1295 $this->lastWriteTime = microtime(
true );
1296 if ( $this->
trxLevel && !$this->trxDoneWrites ) {
1297 $this->trxDoneWrites =
true;
1298 $this->trxProfiler->transactionWritingIn(
1304 $this->queryLogger->debug(
"{$this->getDomainID()} {$commentedSql}" );
1307 $isMaster = !is_null( $this->
getLBInfo(
'master' ) );
1308 # generalizeSQL() will probably cut down the query to reasonable
1309 # logging size most of the time. The substr is really just a sanity check.
1311 $queryProf =
'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1313 $queryProf =
'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1316 # Include query transaction state
1317 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" :
"";
1319 $startTime = microtime(
true );
1321 $this->affectedRowCount =
null;
1325 $queryRuntime = max( microtime(
true ) - $startTime, 0.0 );
1327 if (
$ret !==
false ) {
1328 $this->lastPing = $startTime;
1329 if ( $isEffectiveWrite && $this->
trxLevel ) {
1331 $this->trxWriteCallers[] =
$fname;
1335 if ( $sql === self::PING_QUERY ) {
1336 $this->rttEstimate = $queryRuntime;
1339 $this->trxProfiler->recordQueryCompletion(
1345 $this->queryLogger->debug( $sql, [
1347 'master' => $isMaster,
1348 'runtime' => $queryRuntime,
1366 $this->
begin( __METHOD__ .
" ($fname)", self::TRANSACTION_INTERNAL );
1367 $this->trxAutomatic =
true;
1385 $indicativeOfReplicaRuntime =
true;
1386 if ( $runtime > self::SLOW_WRITE_SEC ) {
1389 if ( $verb ===
'INSERT' ) {
1391 } elseif ( $verb ===
'REPLACE' ) {
1392 $indicativeOfReplicaRuntime = $this->
affectedRows() > self::SMALL_WRITE_ROWS / 2;
1396 $this->trxWriteDuration += $runtime;
1397 $this->trxWriteQueryCount += 1;
1398 $this->trxWriteAffectedRows += $affected;
1399 if ( $indicativeOfReplicaRuntime ) {
1400 $this->trxWriteAdjDuration += $runtime;
1401 $this->trxWriteAdjQueryCount += 1;
1414 if ( $verb ===
'USE' ) {
1415 throw new DBUnexpectedError( $this,
"Got USE query; use selectDomain() instead." );
1418 if ( $verb ===
'ROLLBACK' ) {
1422 if ( $this->
trxStatus < self::STATUS_TRX_OK ) {
1425 "Cannot execute query from $fname while transaction status is ERROR.",
1427 $this->trxStatusCause
1429 } elseif ( $this->
trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1431 call_user_func( $this->deprecationLogger,
1432 "Caller from $fname ignored an error originally raised from $iFname: " .
1433 "[$iLastErrno] $iLastError"
1435 $this->trxStatusIgnoredCause =
null;
1443 "Explicit transaction still active. A caller may have caught an error. "
1459 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1460 # Dropped connections also mean that named locks are automatically released.
1461 # Only allow error suppression in autocommit mode or when the lost transaction
1462 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1463 if ( $this->namedLocksHeld ) {
1465 } elseif ( $this->sessionTempTables ) {
1467 } elseif ( $sql ===
'COMMIT' ) {
1468 return !$priorWritesPending;
1469 } elseif ( $sql ===
'ROLLBACK' ) {
1473 } elseif ( $priorWritesPending ) {
1487 $this->sessionTempTables = [];
1490 $this->namedLocksHeld = [];
1493 $this->trxAtomicCounter = 0;
1494 $this->trxIdleCallbacks = [];
1495 $this->trxPreCommitCallbacks = [];
1497 if ( $this->trxDoneWrites ) {
1498 $this->trxProfiler->transactionWritingOut(
1503 $this->trxWriteAffectedRows
1516 }
catch ( Exception $ex ) {
1522 }
catch ( Exception $ex ) {
1553 if ( $ignoreErrors ) {
1554 $this->queryLogger->debug(
"SQL ERROR (ignored): $error\n" );
1570 $sql1line = mb_substr( str_replace(
"\n",
"\\n", $sql ), 0, 5 * 1024 );
1571 $this->queryLogger->error(
1572 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1574 'method' => __METHOD__,
1577 'sql1line' => $sql1line,
1579 'trace' => (
new RuntimeException() )->getTraceAsString()
1582 $this->queryLogger->debug(
"SQL ERROR: " . $error .
"\n" );
1584 if ( $wasQueryTimeout ) {
1597 $table, $var, $cond =
'',
$fname = __METHOD__,
$options = [], $join_conds = []
1599 if ( $var ===
'*' ) {
1616 if ( $row !==
false ) {
1617 return reset( $row );
1624 $table, $var, $cond =
'',
$fname = __METHOD__,
$options = [], $join_conds = []
1626 if ( $var ===
'*' ) {
1628 } elseif ( !is_string( $var ) ) {
1637 if (
$res ===
false ) {
1642 foreach (
$res as $row ) {
1643 $values[] = $row->value;
1659 $preLimitTail = $postLimitTail =
'';
1665 if ( is_numeric( $key ) ) {
1666 $noKeyOptions[$option] =
true;
1674 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1675 $postLimitTail .=
' FOR UPDATE';
1678 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1679 $postLimitTail .=
' LOCK IN SHARE MODE';
1682 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1683 $startOpts .=
'DISTINCT';
1686 # Various MySQL extensions
1687 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1688 $startOpts .=
' /*! STRAIGHT_JOIN */';
1691 if ( isset( $noKeyOptions[
'HIGH_PRIORITY'] ) ) {
1692 $startOpts .=
' HIGH_PRIORITY';
1695 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1696 $startOpts .=
' SQL_BIG_RESULT';
1699 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1700 $startOpts .=
' SQL_BUFFER_RESULT';
1703 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1704 $startOpts .=
' SQL_SMALL_RESULT';
1707 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1708 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1711 if ( isset( $noKeyOptions[
'SQL_CACHE'] ) ) {
1712 $startOpts .=
' SQL_CACHE';
1715 if ( isset( $noKeyOptions[
'SQL_NO_CACHE'] ) ) {
1716 $startOpts .=
' SQL_NO_CACHE';
1719 if ( isset(
$options[
'USE INDEX'] ) && is_string(
$options[
'USE INDEX'] ) ) {
1724 if ( isset(
$options[
'IGNORE INDEX'] ) && is_string(
$options[
'IGNORE INDEX'] ) ) {
1730 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1743 if ( isset(
$options[
'GROUP BY'] ) ) {
1744 $gb = is_array(
$options[
'GROUP BY'] )
1745 ? implode(
',',
$options[
'GROUP BY'] )
1747 $sql .=
' GROUP BY ' . $gb;
1749 if ( isset(
$options[
'HAVING'] ) ) {
1750 $having = is_array(
$options[
'HAVING'] )
1753 $sql .=
' HAVING ' . $having;
1768 if ( isset(
$options[
'ORDER BY'] ) ) {
1769 $ob = is_array(
$options[
'ORDER BY'] )
1770 ? implode(
',',
$options[
'ORDER BY'] )
1773 return ' ORDER BY ' . $ob;
1790 if ( is_array(
$vars ) ) {
1797 $useIndexes = ( isset(
$options[
'USE INDEX'] ) && is_array(
$options[
'USE INDEX'] ) )
1801 isset(
$options[
'IGNORE INDEX'] ) &&
1802 is_array(
$options[
'IGNORE INDEX'] )
1814 $this->deprecationLogger,
1815 __METHOD__ .
": aggregation used with a locking SELECT ($fname)."
1819 if ( is_array( $table ) ) {
1822 $table, $useIndexes, $ignoreIndexes, $join_conds );
1823 } elseif ( $table !=
'' ) {
1826 [ $table ], $useIndexes, $ignoreIndexes, [] );
1831 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1834 if ( is_array( $conds ) ) {
1838 if ( $conds ===
null || $conds ===
false ) {
1839 $this->queryLogger->warning(
1843 .
' with incorrect parameters: $conds must be a string or an array'
1848 if ( $conds ===
'' || $conds ===
'*' ) {
1849 $sql =
"SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1850 } elseif ( is_string( $conds ) ) {
1851 $sql =
"SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1852 "WHERE $conds $preLimitTail";
1854 throw new DBUnexpectedError( $this, __METHOD__ .
' called with incorrect parameters' );
1857 if ( isset(
$options[
'LIMIT'] ) ) {
1861 $sql =
"$sql $postLimitTail";
1863 if ( isset(
$options[
'EXPLAIN'] ) ) {
1864 $sql =
'EXPLAIN ' . $sql;
1877 if (
$res ===
false ) {
1891 $table, $var =
'*', $conds =
'',
$fname = __METHOD__,
$options = [], $join_conds = []
1895 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
1896 $conds[] =
"$column IS NOT NULL";
1900 $table, [
'rowcount' =>
'COUNT(*)' ], $conds,
$fname,
$options, $join_conds
1904 return isset( $row[
'rowcount'] ) ? (int)$row[
'rowcount'] : 0;
1912 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
1913 $conds[] =
"$column IS NOT NULL";
1927 [
'rowcount' =>
'COUNT(*)' ],
1933 return isset( $row[
'rowcount'] ) ? (int)$row[
'rowcount'] : 0;
1942 foreach ( [
'FOR UPDATE',
'LOCK IN SHARE MODE' ]
as $lock ) {
1943 if ( in_array( $lock,
$options,
true ) ) {
1958 if ( is_string( $key ) ) {
1959 if ( preg_match(
'/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1962 } elseif ( is_string(
$value ) ) {
1963 if ( preg_match(
'/^(?:DISTINCT|DISTINCTROW)$/i',
$value ) ) {
1969 $regex =
'/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1970 foreach ( (
array)$fields
as $field ) {
1971 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1985 if ( $conds ===
null || $conds ===
false ) {
1986 $this->queryLogger->warning(
1990 .
' with incorrect parameters: $conds must be a string or an array'
1995 if ( !is_array( $conds ) ) {
1996 $conds = ( $conds ===
'' ) ? [] : [ $conds ];
2008 if ( is_array( $var ) ) {
2011 } elseif (
count( $var ) == 1 ) {
2012 $column = $var[0] ?? reset( $var );
2024 $table, $conds =
'',
$fname = __METHOD__,
$options = [], $join_conds = []
2029 __METHOD__ .
': no transaction is active nor is DBO_TRX set'
2048 # This does the same as the regexp below would do, but in such a way
2049 # as to avoid crashing php on some large strings.
2050 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
2052 $sql = str_replace(
"\\\\",
'', $sql );
2053 $sql = str_replace(
"\\'",
'', $sql );
2054 $sql = str_replace(
"\\\"",
'', $sql );
2055 $sql = preg_replace(
"/'.*'/s",
"'X'", $sql );
2056 $sql = preg_replace(
'/".*"/s',
"'X'", $sql );
2058 # All newlines, tabs, etc replaced by single space
2059 $sql = preg_replace(
'/\s+/',
' ', $sql );
2062 # except the ones surrounded by characters, e.g. l10n
2063 $sql = preg_replace(
'/-?\d+(,-?\d+)+/s',
'N,...,N', $sql );
2064 $sql = preg_replace(
'/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s',
'N', $sql );
2070 $info = $this->
fieldInfo( $table, $field );
2081 if ( is_null( $info ) ) {
2084 return $info !==
false;
2091 $indexInfo = $this->
indexInfo( $table, $index );
2093 if ( !$indexInfo ) {
2097 return !$indexInfo[0]->Non_unique;
2111 # No rows to insert, easy just return now
2112 if ( !
count( $a ) ) {
2124 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2126 $keys = array_keys( $a[0] );
2129 $keys = array_keys( $a );
2133 " INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
2137 foreach ( $a
as $row ) {
2143 $sql .=
'(' . $this->
makeList( $row ) .
')';
2146 $sql .=
'(' . $this->
makeList( $a ) .
')';
2167 if ( in_array(
'IGNORE',
$options ) ) {
2183 return implode(
' ', $opts );
2191 if ( $conds !== [] && $conds !==
'*' ) {
2201 if ( !is_array( $a ) ) {
2202 throw new DBUnexpectedError( $this, __METHOD__ .
' called with incorrect parameters' );
2208 foreach ( $a
as $field =>
$value ) {
2222 $list .=
"($value)";
2229 $includeNull =
false;
2230 foreach ( array_keys(
$value,
null,
true )
as $nullKey ) {
2231 $includeNull =
true;
2232 unset(
$value[$nullKey] );
2235 throw new InvalidArgumentException(
2236 __METHOD__ .
": empty input for field $field" );
2239 $list .=
"$field IS NULL";
2242 if ( $includeNull ) {
2256 if ( $includeNull ) {
2257 $list .=
" OR $field IS NULL)";
2260 } elseif (
$value ===
null ) {
2262 $list .=
"$field IS ";
2264 $list .=
"$field = ";
2271 $list .=
"$field = ";
2284 if (
count( $sub ) ) {
2286 [ $baseKey =>
$base, $subKey => array_keys( $sub ) ],
2307 public function bitAnd( $fieldLeft, $fieldRight ) {
2308 return "($fieldLeft & $fieldRight)";
2311 public function bitOr( $fieldLeft, $fieldRight ) {
2312 return "($fieldLeft | $fieldRight)";
2316 return 'CONCAT(' . implode(
',', $stringList ) .
')';
2320 $delim, $table, $field, $conds =
'', $join_conds = []
2322 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->
addQuotes( $delim ) .
')';
2324 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
2329 $functionBody =
"$input FROM $startPosition";
2330 if ( $length !==
null ) {
2331 $functionBody .=
" FOR $length";
2333 return 'SUBSTRING(' . $functionBody .
')';
2349 if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2350 throw new InvalidArgumentException(
2351 '$startPosition must be a positive integer'
2354 if ( !( is_int( $length ) && $length >= 0 || $length ===
null ) ) {
2355 throw new InvalidArgumentException(
2356 '$length must be null or an integer greater than or equal to 0'
2364 return "CAST( $field AS CHARACTER )";
2368 return 'CAST( ' . $field .
' AS INTEGER )';
2387 $this->currentDomain->getSchema(),
2388 $this->currentDomain->getTablePrefix()
2399 $this->currentDomain = $domain;
2403 return $this->currentDomain->getDatabase();
2414 __METHOD__ .
': got Subquery instance when expecting a string.'
2418 # Skip the entire process when we have a string quoted on both ends.
2419 # Note that we check the end so that we will still quote any use of
2420 # use of `database`.table. But won't break things if someone wants
2421 # to query a database table with a dot in the name.
2426 # Lets test for any bits of text that should never show up in a table
2427 # name. Basically anything like JOIN or ON which are actually part of
2428 # SQL queries, but may end up inside of the table value to combine
2429 # sql. Such as how the API is doing.
2430 # Note that we use a whitespace test rather than a \b test to avoid
2431 # any remote case where a word like on may be inside of a table name
2432 # surrounded by symbols which may be considered word breaks.
2433 if ( preg_match(
'/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i',
$name ) !== 0 ) {
2434 $this->queryLogger->warning(
2435 __METHOD__ .
": use of subqueries is not supported this way.",
2436 [
'trace' => (
new RuntimeException() )->getTraceAsString() ]
2442 # Split database and table into proper variables.
2445 # Quote $table and apply the prefix if not quoted.
2446 # $tableName might be empty if this is called from Database::replaceVars()
2447 $tableName =
"{$prefix}{$table}";
2448 if ( $format ===
'quoted'
2450 && $tableName !==
''
2455 # Quote $schema and $database and merge them with the table name if needed
2469 # We reverse the explode so that database.table and table both output the correct table.
2470 $dbDetails = explode(
'.',
$name, 3 );
2471 if (
count( $dbDetails ) == 3 ) {
2472 list( $database, $schema, $table ) = $dbDetails;
2473 # We don't want any prefix added in this case
2475 } elseif (
count( $dbDetails ) == 2 ) {
2476 list( $database, $table ) = $dbDetails;
2477 # We don't want any prefix added in this case
2479 # In dbs that support it, $database may actually be the schema
2480 # but that doesn't affect any of the functionality here
2483 list( $table ) = $dbDetails;
2484 if ( isset( $this->tableAliases[$table] ) ) {
2485 $database = $this->tableAliases[$table][
'dbname'];
2486 $schema = is_string( $this->tableAliases[$table][
'schema'] )
2487 ? $this->tableAliases[$table][
'schema']
2489 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
2490 ? $this->tableAliases[$table][
'prefix']
2499 return [ $database, $schema, $prefix, $table ];
2509 if ( strlen( $namespace ) ) {
2513 $relation = $namespace .
'.' . $relation;
2520 $inArray = func_get_args();
2523 foreach ( $inArray
as $name ) {
2531 $inArray = func_get_args();
2534 foreach ( $inArray
as $name ) {
2553 if ( is_string( $table ) ) {
2554 $quotedTable = $this->
tableName( $table );
2555 } elseif ( $table instanceof
Subquery ) {
2556 $quotedTable = (
string)$table;
2558 throw new InvalidArgumentException(
"Table must be a string or Subquery." );
2561 if ( $alias ===
false || $alias === $table ) {
2562 if ( $table instanceof
Subquery ) {
2563 throw new InvalidArgumentException(
"Subquery table missing alias." );
2566 return $quotedTable;
2580 foreach (
$tables as $alias => $table ) {
2581 if ( is_numeric( $alias ) ) {
2599 if ( !$alias || (
string)$alias === (
string)
$name ) {
2614 foreach ( $fields
as $alias => $field ) {
2615 if ( is_numeric( $alias ) ) {
2635 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2639 $use_index = (
array)$use_index;
2640 $ignore_index = (
array)$ignore_index;
2641 $join_conds = (
array)$join_conds;
2643 foreach (
$tables as $alias => $table ) {
2644 if ( !is_string( $alias ) ) {
2649 if ( is_array( $table ) ) {
2651 if (
count( $table ) > 1 ) {
2652 $joinedTable =
'(' .
2654 $table, $use_index, $ignore_index, $join_conds ) .
')';
2657 $innerTable = reset( $table );
2658 $innerAlias =
key( $table );
2661 is_string( $innerAlias ) ? $innerAlias : $innerTable
2669 if ( isset( $join_conds[$alias] ) ) {
2670 list( $joinType, $conds ) = $join_conds[$alias];
2671 $tableClause = $joinType;
2672 $tableClause .=
' ' . $joinedTable;
2673 if ( isset( $use_index[$alias] ) ) {
2676 $tableClause .=
' ' . $use;
2679 if ( isset( $ignore_index[$alias] ) ) {
2681 implode(
',', (
array)$ignore_index[$alias] ) );
2682 if ( $ignore !=
'' ) {
2683 $tableClause .=
' ' . $ignore;
2688 $tableClause .=
' ON (' . $on .
')';
2691 $retJOIN[] = $tableClause;
2692 } elseif ( isset( $use_index[$alias] ) ) {
2694 $tableClause = $joinedTable;
2696 implode(
',', (
array)$use_index[$alias] )
2699 $ret[] = $tableClause;
2700 } elseif ( isset( $ignore_index[$alias] ) ) {
2702 $tableClause = $joinedTable;
2704 implode(
',', (
array)$ignore_index[$alias] )
2707 $ret[] = $tableClause;
2709 $tableClause = $joinedTable;
2711 $ret[] = $tableClause;
2716 $implicitJoins =
$ret ? implode(
',',
$ret ) :
"";
2717 $explicitJoins = $retJOIN ? implode(
' ', $retJOIN ) :
"";
2720 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
2730 return $this->indexAliases[$index] ?? $index;
2734 if (
$s instanceof
Blob ) {
2737 if (
$s ===
null ) {
2739 } elseif ( is_bool(
$s ) ) {
2742 # This will also quote numeric values. This should be harmless,
2743 # and protects against weird problems that occur when they really
2744 # _are_ strings such as article titles and string->number->string
2745 # conversion is not 1:1.
2751 return '"' . str_replace(
'"',
'""',
$s ) .
'"';
2764 return $name[0] ==
'"' && substr(
$name, -1, 1 ) ==
'"';
2773 return str_replace( [ $escapeChar,
'%',
'_' ],
2774 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
2850 $uniqueIndexes = (
array)$uniqueIndexes;
2852 if ( !is_array( reset(
$rows ) ) ) {
2861 $indexWhereClauses = [];
2862 foreach ( $uniqueIndexes
as $index ) {
2863 $indexColumns = (
array)$index;
2864 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2865 if (
count( $indexRowValues ) !=
count( $indexColumns ) ) {
2868 'New record does not provide all values for unique key (' .
2869 implode(
', ', $indexColumns ) .
')'
2871 } elseif ( in_array(
null, $indexRowValues,
true ) ) {
2874 'New record has a null value for unique key (' .
2875 implode(
', ', $indexColumns ) .
')'
2881 if ( $indexWhereClauses ) {
2892 }
catch ( Exception
$e ) {
2910 if ( !is_array( reset(
$rows ) ) ) {
2914 $sql =
"REPLACE INTO $table (" . implode(
',', array_keys(
$rows[0] ) ) .
') VALUES ';
2924 $sql .=
'(' . $this->
makeList( $row ) .
')';
2933 if (
$rows === [] ) {
2937 $uniqueIndexes = (
array)$uniqueIndexes;
2938 if ( !is_array( reset(
$rows ) ) ) {
2942 if (
count( $uniqueIndexes ) ) {
2945 foreach ( $uniqueIndexes
as $index ) {
2946 $index = is_array( $index ) ? $index : [ $index ];
2948 foreach ( $index
as $column ) {
2949 $rowKey[$column] = $row[$column];
2962 # Update any existing conflicting row(s)
2963 if ( $where !==
false ) {
2967 # Now insert any non-conflicting row(s)
2972 }
catch ( Exception
$e ) {
2980 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2987 $delTable = $this->
tableName( $delTable );
2988 $joinTable = $this->
tableName( $joinTable );
2989 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2990 if ( $conds !=
'*' ) {
3000 $sql =
"SHOW COLUMNS FROM $table LIKE \"$field\";";
3001 $res = $this->
query( $sql, __METHOD__ );
3006 if ( preg_match(
'/\((.*)\)/', $row->Type, $m ) ) {
3015 public function delete( $table, $conds,
$fname = __METHOD__ ) {
3017 throw new DBUnexpectedError( $this, __METHOD__ .
' called with no conditions' );
3021 $sql =
"DELETE FROM $table";
3023 if ( $conds !=
'*' ) {
3024 if ( is_array( $conds ) ) {
3027 $sql .=
' WHERE ' . $conds;
3036 $destTable, $srcTable, $varMap, $conds,
3037 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3039 static $hints = [
'NO_AUTO_COLUMNS' ];
3041 $insertOptions = (
array)$insertOptions;
3042 $selectOptions = (
array)$selectOptions;
3044 if ( $this->cliMode && $this->
isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3053 array_diff( $insertOptions, $hints ),
3064 array_diff( $insertOptions, $hints ),
3099 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3105 foreach ( $varMap
as $dstColumn => $sourceColumnOrSql ) {
3108 $selectOptions[] =
'FOR UPDATE';
3110 $srcTable, implode(
',', $fields ), $conds,
$fname, $selectOptions, $selectJoinConds
3118 $this->
startAtomic( $fname, self::ATOMIC_CANCELABLE );
3121 foreach (
$res as $row ) {
3134 if (
$rows && $ok ) {
3146 }
catch ( Exception
$e ) {
3168 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3170 $destTable = $this->
tableName( $destTable );
3172 if ( !is_array( $insertOptions ) ) {
3173 $insertOptions = [ $insertOptions ];
3180 array_values( $varMap ),
3187 $sql =
"INSERT $insertOptions" .
3188 " INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
') ' .
3214 if ( !is_numeric( $limit ) ) {
3216 "Invalid non-numeric limit passed to limitResult()\n" );
3219 return "$sql LIMIT "
3220 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
3229 $glue = $all ?
') UNION ALL (' :
') UNION (';
3231 return '(' . implode( $glue, $sqls ) .
')';
3235 $table,
$vars,
array $permute_conds, $extra_conds =
'',
$fname = __METHOD__,
3240 foreach ( $permute_conds
as $field => $values ) {
3245 $values = array_unique( $values );
3247 foreach ( $conds
as $cond ) {
3250 $newConds[] = $cond;
3256 $extra_conds = $extra_conds ===
'' ? [] : (
array)$extra_conds;
3260 if (
count( $conds ) === 1 &&
3273 $limit =
$options[
'LIMIT'] ??
null;
3274 $offset =
$options[
'OFFSET'] ??
false;
3279 if ( array_key_exists(
'INNER ORDER BY',
$options ) ) {
3282 if ( $limit !==
null && is_numeric( $offset ) && $offset != 0 ) {
3286 $options[
'LIMIT'] = $limit + $offset;
3292 foreach ( $conds
as $cond ) {
3298 if ( $limit !==
null ) {
3299 $sql = $this->
limitResult( $sql, $limit, $offset );
3306 if ( is_array( $cond ) ) {
3310 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3314 return "REPLACE({$orig}, {$old}, {$new})";
3366 $args = func_get_args();
3367 $function = array_shift(
$args );
3370 $this->
begin( __METHOD__ );
3377 $retVal = $function( ...
$args );
3382 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3388 }
while ( --$tries > 0 );
3390 if ( $tries <= 0 ) {
3395 $this->
commit( __METHOD__ );
3402 # Real waits are implemented in the subclass.
3430 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
3431 $this->trxAutomatic =
true;
3447 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
3448 $this->trxAutomatic =
true;
3455 $this->
startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3459 }
catch ( Exception
$e ) {
3470 if ( $this->
trxLevel && $this->trxAtomicLevels ) {
3471 $levelInfo = end( $this->trxAtomicLevels );
3473 return $levelInfo[1];
3486 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3487 if ( $info[2] === $old ) {
3488 $this->trxPreCommitCallbacks[$key][2] = $new;
3491 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3492 if ( $info[2] === $old ) {
3493 $this->trxIdleCallbacks[$key][2] = $new;
3496 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3497 if ( $info[2] === $old ) {
3498 $this->trxEndCallbacks[$key][2] = $new;
3509 $this->trxIdleCallbacks = array_filter(
3510 $this->trxIdleCallbacks,
3511 function ( $entry )
use ( $sectionIds ) {
3512 return !in_array( $entry[2], $sectionIds,
true );
3515 $this->trxPreCommitCallbacks = array_filter(
3516 $this->trxPreCommitCallbacks,
3517 function ( $entry )
use ( $sectionIds ) {
3518 return !in_array( $entry[2], $sectionIds,
true );
3522 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3523 if ( in_array( $entry[2], $sectionIds,
true ) ) {
3524 $callback = $entry[0];
3525 $this->trxEndCallbacks[$key][0] =
function ()
use ( $callback ) {
3526 return $callback( self::TRIGGER_ROLLBACK, $this );
3534 $this->trxRecurringCallbacks[
$name] = $callback;
3536 unset( $this->trxRecurringCallbacks[
$name] );
3549 $this->trxEndCallbacksSuppressed = $suppress;
3564 throw new DBUnexpectedError( $this, __METHOD__ .
': a transaction is still open.' );
3567 if ( $this->trxEndCallbacksSuppressed ) {
3576 $callbacks = array_merge(
3577 $this->trxIdleCallbacks,
3578 $this->trxEndCallbacks
3580 $this->trxIdleCallbacks = [];
3581 $this->trxEndCallbacks = [];
3582 foreach ( $callbacks
as $callback ) {
3584 list( $phpCallback ) = $callback;
3588 call_user_func( $phpCallback, $trigger, $this );
3589 }
catch ( Exception $ex ) {
3590 call_user_func( $this->errorLogger, $ex );
3595 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
3605 }
while (
count( $this->trxIdleCallbacks ) );
3607 if (
$e instanceof Exception ) {
3629 $this->trxPreCommitCallbacks = [];
3630 foreach ( $callbacks
as $callback ) {
3633 list( $phpCallback ) = $callback;
3634 $phpCallback( $this );
3635 }
catch ( Exception $ex ) {
3640 }
while (
count( $this->trxPreCommitCallbacks ) );
3642 if (
$e instanceof Exception ) {
3659 if ( $this->trxEndCallbacksSuppressed ) {
3666 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3668 $phpCallback( $trigger, $this );
3669 }
catch ( Exception $ex ) {
3675 if (
$e instanceof Exception ) {
3728 if ( strlen( $savepointId ) > 30 ) {
3733 'There have been an excessively large number of atomic sections in a transaction'
3734 .
" started by $this->trxFname (at $fname)"
3738 return $savepointId;
3742 $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3747 $this->
begin( $fname, self::TRANSACTION_INTERNAL );
3756 $this->trxAutomaticAtomic =
true;
3758 } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3764 $this->trxAtomicLevels[] = [
$fname, $sectionId, $savepointId ];
3765 $this->queryLogger->debug(
'startAtomic: entering level ' .
3766 (
count( $this->trxAtomicLevels ) - 1 ) .
" ($fname)" );
3772 if ( !$this->
trxLevel || !$this->trxAtomicLevels ) {
3773 throw new DBUnexpectedError( $this,
"No atomic section is open (got $fname)." );
3777 $pos =
count( $this->trxAtomicLevels ) - 1;
3778 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3779 $this->queryLogger->debug(
"endAtomic: leaving level $pos ($fname)" );
3781 if ( $savedFname !==
$fname ) {
3784 "Invalid atomic section ended (got $fname but expected $savedFname)."
3789 array_pop( $this->trxAtomicLevels );
3791 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3792 $this->
commit( $fname, self::FLUSHING_INTERNAL );
3793 } elseif ( $savepointId !==
null && $savepointId !== self::$NOT_APPLICABLE ) {
3800 if ( $currentSectionId ) {
3808 if ( !$this->
trxLevel || !$this->trxAtomicLevels ) {
3809 throw new DBUnexpectedError( $this,
"No atomic section is open (got $fname)." );
3812 $excisedFnames = [];
3813 if ( $sectionId !==
null ) {
3816 foreach ( $this->trxAtomicLevels
as $i =>
list( $asFname, $asId, $spId ) ) {
3817 if ( $asId === $sectionId ) {
3826 $len =
count( $this->trxAtomicLevels );
3827 for ( $i = $pos + 1; $i < $len; ++$i ) {
3828 $excisedFnames[] = $this->trxAtomicLevels[$i][0];
3829 $excisedIds[] = $this->trxAtomicLevels[$i][1];
3831 $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
3836 $pos =
count( $this->trxAtomicLevels ) - 1;
3837 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3839 if ( $excisedFnames ) {
3840 $this->queryLogger->debug(
"cancelAtomic: canceling level $pos ($savedFname) " .
3841 "and descendants " . implode(
', ', $excisedFnames ) );
3843 $this->queryLogger->debug(
"cancelAtomic: canceling level $pos ($savedFname)" );
3846 if ( $savedFname !==
$fname ) {
3849 "Invalid atomic section ended (got $fname but expected $savedFname)."
3854 array_pop( $this->trxAtomicLevels );
3857 if ( $savepointId !==
null ) {
3859 if ( $savepointId === self::$NOT_APPLICABLE ) {
3860 $this->
rollback( $fname, self::FLUSHING_INTERNAL );
3864 $this->trxStatusIgnoredCause =
null;
3866 } elseif ( $this->
trxStatus > self::STATUS_TRX_ERROR ) {
3868 $this->
trxStatus = self::STATUS_TRX_ERROR;
3871 "Uncancelable atomic section canceled (got $fname)."
3875 $this->affectedRowCount = 0;
3879 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
3881 $sectionId = $this->
startAtomic( $fname, $cancelable );
3884 }
catch ( Exception
$e ) {
3894 final public function begin(
$fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3895 static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
3896 if ( !in_array( $mode, $modes,
true ) ) {
3897 throw new DBUnexpectedError( $this,
"$fname: invalid mode parameter '$mode'." );
3902 if ( $this->trxAtomicLevels ) {
3904 $msg =
"$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3906 } elseif ( !$this->trxAutomatic ) {
3907 $msg =
"$fname: Explicit transaction already active (from {$this->trxFname}).";
3910 $msg =
"$fname: Implicit transaction already active (from {$this->trxFname}).";
3914 $msg =
"$fname: Implicit transaction expected (DBO_TRX set).";
3922 $this->trxStatusIgnoredCause =
null;
3923 $this->trxAtomicCounter = 0;
3925 $this->trxFname =
$fname;
3926 $this->trxDoneWrites =
false;
3927 $this->trxAutomaticAtomic =
false;
3928 $this->trxAtomicLevels = [];
3929 $this->trxShortId = sprintf(
'%06x', mt_rand( 0, 0xffffff ) );
3930 $this->trxWriteDuration = 0.0;
3931 $this->trxWriteQueryCount = 0;
3932 $this->trxWriteAffectedRows = 0;
3933 $this->trxWriteAdjDuration = 0.0;
3934 $this->trxWriteAdjQueryCount = 0;
3935 $this->trxWriteCallers = [];
3938 $this->trxReplicaLag =
null;
3943 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
3953 $this->
query(
'BEGIN', $fname );
3957 final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
3958 static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
3959 if ( !in_array( $flush, $modes,
true ) ) {
3960 throw new DBUnexpectedError( $this,
"$fname: invalid flush parameter '$flush'." );
3963 if ( $this->
trxLevel && $this->trxAtomicLevels ) {
3968 "$fname: Got COMMIT while atomic sections $levels are still open."
3972 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3975 } elseif ( !$this->trxAutomatic ) {
3978 "$fname: Flushing an explicit transaction, getting out of sync."
3982 $this->queryLogger->error(
3983 "$fname: No transaction to commit, something got out of sync." );
3985 } elseif ( $this->trxAutomatic ) {
3988 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3998 $this->
trxStatus = self::STATUS_TRX_NONE;
4000 if ( $this->trxDoneWrites ) {
4001 $this->lastWriteTime = microtime(
true );
4002 $this->trxProfiler->transactionWritingOut(
4007 $this->trxWriteAffectedRows
4012 if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4026 $this->
query(
'COMMIT', $fname );
4031 final public function rollback( $fname = __METHOD__, $flush =
'' ) {
4034 if ( $flush !== self::FLUSHING_INTERNAL
4035 && $flush !== self::FLUSHING_ALL_PEERS
4040 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
4048 $this->
trxStatus = self::STATUS_TRX_NONE;
4049 $this->trxAtomicLevels = [];
4053 if ( $this->trxDoneWrites ) {
4054 $this->trxProfiler->transactionWritingOut(
4059 $this->trxWriteAffectedRows
4066 $this->trxIdleCallbacks = [];
4067 $this->trxPreCommitCallbacks = [];
4070 if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4073 }
catch ( Exception
$e ) {
4078 }
catch ( Exception
$e ) {
4082 $this->affectedRowCount = 0;
4094 # Disconnects cause rollback anyway, so ignore those errors
4095 $ignoreErrors =
true;
4096 $this->
query(
'ROLLBACK', $fname, $ignoreErrors );
4107 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
4111 $this->
commit( $fname, self::FLUSHING_INTERNAL );
4119 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
4121 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4125 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4129 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4133 $t =
new ConvertibleTimestamp( $ts );
4135 return $t->getTimestamp( TS_MW );
4139 if ( is_null( $ts ) ) {
4147 return ( $this->affectedRowCount ===
null )
4175 } elseif (
$result ===
true ) {
4183 public function ping( &$rtt =
null ) {
4185 if ( $this->
isOpen() && ( microtime(
true ) - $this->lastPing ) < self::PING_TTL ) {
4186 if ( !func_num_args() || $this->rttEstimate > 0 ) {
4194 $ok = ( $this->
query( self::PING_QUERY, __METHOD__,
true ) !==
false );
4212 $this->opened =
false;
4213 $this->conn =
false;
4226 $this->lastPing = microtime(
true );
4229 $this->connLogger->warning(
4230 $fname .
': lost connection to {dbserver}; reconnected',
4233 'trace' => (
new RuntimeException() )->getTraceAsString()
4239 $this->connLogger->error(
4240 $fname .
': lost connection to {dbserver} permanently',
4268 return ( $this->
trxLevel && $this->trxReplicaLag !==
null )
4282 'since' => microtime(
true )
4306 $res = [
'lag' => 0,
'since' => INF,
'pending' =>
false ];
4307 foreach ( func_get_args()
as $db ) {
4309 $status = $db->getSessionLagStatus();
4310 if (
$status[
'lag'] ===
false ) {
4311 $res[
'lag'] =
false;
4312 } elseif (
$res[
'lag'] !==
false ) {
4316 $res[
'pending'] =
$res[
'pending'] ?: $db->writesPending();
4335 if ( $b instanceof
Blob ) {
4346 callable $lineCallback =
null,
4347 callable $resultCallback =
null,
4349 callable $inputCallback =
null
4351 Wikimedia\suppressWarnings();
4352 $fp = fopen( $filename,
'r' );
4353 Wikimedia\restoreWarnings();
4355 if ( $fp ===
false ) {
4356 throw new RuntimeException(
"Could not open \"{$filename}\".\n" );
4360 $fname = __METHOD__ .
"( $filename )";
4365 $fp, $lineCallback, $resultCallback,
$fname, $inputCallback );
4366 }
catch ( Exception
$e ) {
4377 $this->schemaVars =
$vars;
4382 callable $lineCallback =
null,
4383 callable $resultCallback =
null,
4385 callable $inputCallback =
null
4387 $delimiterReset =
new ScopedCallback(
4395 while ( !feof( $fp ) ) {
4396 if ( $lineCallback ) {
4397 call_user_func( $lineCallback );
4400 $line = trim( fgets( $fp ) );
4402 if (
$line ==
'' ) {
4418 if ( $done || feof( $fp ) ) {
4421 if ( $inputCallback ) {
4422 $callbackResult = $inputCallback( $cmd );
4424 if ( is_string( $callbackResult ) || !$callbackResult ) {
4425 $cmd = $callbackResult;
4432 if ( $resultCallback ) {
4433 $resultCallback(
$res, $this );
4436 if (
$res ===
false ) {
4439 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4446 ScopedCallback::consume( $delimiterReset );
4458 if ( $this->delimiter ) {
4460 $newLine = preg_replace(
4461 '/' . preg_quote( $this->delimiter,
'/' ) .
'$/',
'', $newLine );
4462 if ( $newLine != $prev ) {
4492 return preg_replace_callback(
4494 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4495 \'\{\$ (\w+) }\' | # 3. addQuotes
4496 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4497 /\*\$ (\w+) \*/ # 5. leave unencoded
4502 if ( isset( $m[1] ) && $m[1] !==
'' ) {
4503 if ( $m[1] ===
'i' ) {
4508 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3],
$vars ) ) {
4510 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4],
$vars ) ) {
4512 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5],
$vars ) ) {
4513 return $vars[$m[5]];
4529 if ( $this->schemaVars ) {
4552 return !isset( $this->namedLocksHeld[$lockName] );
4555 public function lock( $lockName, $method, $timeout = 5 ) {
4556 $this->namedLocksHeld[$lockName] = 1;
4561 public function unlock( $lockName, $method ) {
4562 unset( $this->namedLocksHeld[$lockName] );
4573 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4577 if ( !$this->
lock( $lockKey,
$fname, $timeout ) ) {
4581 $unlocker =
new ScopedCallback(
function ()
use ( $lockKey,
$fname ) {
4597 $this->
commit( $fname, self::FLUSHING_INTERNAL );
4612 throw new DBUnexpectedError( $this,
"Transaction writes or callbacks still pending." );
4661 public function dropTable( $tableName, $fName = __METHOD__ ) {
4662 if ( !$this->
tableExists( $tableName, $fName ) ) {
4665 $sql =
"DROP TABLE " . $this->
tableName( $tableName ) .
" CASCADE";
4667 return $this->
query( $sql, $fName );
4675 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() )
4681 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() ) {
4685 return ConvertibleTimestamp::convert( $format, $expiry );
4700 $reason = $this->
getLBInfo(
'readOnlyReason' );
4702 return is_string( $reason ) ? $reason :
false;
4706 $this->tableAliases = $aliases;
4710 $this->indexAliases = $aliases;
4734 if ( !$this->conn ) {
4737 'DB connection was already closed or the connection dropped.'
4757 $this->connLogger->warning(
4758 "Cloning " .
static::class .
" is not recommended; forking connection:\n" .
4759 (
new RuntimeException() )->getTraceAsString()
4764 $this->opened =
false;
4765 $this->conn =
false;
4766 $this->trxEndCallbacks = [];
4776 $this->lastPing = microtime(
true );
4786 throw new RuntimeException(
'Database serialization may cause problems, since ' .
4787 'the connection is not restored on wakeup.' );
4794 if ( $this->
trxLevel && $this->trxDoneWrites ) {
4795 trigger_error(
"Uncommitted DB writes (transaction from {$this->trxFname})." );
4799 if ( $danglingWriters ) {
4800 $fnames = implode(
', ', $danglingWriters );
4801 trigger_error(
"DB transaction writes or callbacks still pending ($fnames)." );
4804 if ( $this->conn ) {
4807 Wikimedia\suppressWarnings();
4809 Wikimedia\restoreWarnings();
4810 $this->conn =
false;
4811 $this->opened =
false;
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, 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. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
processing should stop and the error should be shown to the user * false
Simple store for keeping values in an associative array for the current process.
static newFromId( $domain)
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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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 since 1.28! 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 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
Class representing a cache/ephemeral data store.
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
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
if(is_array( $mode)) switch( $mode) $input
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
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
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
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Allows to change the fields on the form that will be generated $name
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
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
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
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 & $options
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
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
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.
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
Advanced database interface for IDatabase handles that include maintenance methods.