23use Wikimedia\Timestamp\ConvertibleTimestamp;
72 parent::__construct( $config );
73 $this->mimeCallback = isset( $config[
'mimeCallback'] )
74 ? $config[
'mimeCallback']
77 $this->memCache = WANObjectCache::newEmpty();
79 $this->expensiveCache =
new ProcessCacheLRU( self::CACHE_EXPENSIVE_SIZE );
294 if ( $nsrc !== $ndst &&
$status->isOK() ) {
319 if ( count(
$params[
'headers'] ) ) {
358 $start_time = microtime(
true );
360 $sec = microtime(
true ) - $start_time;
362 $this->logger->error( static::class .
"-{$this->name}" .
363 " failed to concatenate " . count(
$params[
'srcs'] ) .
" file(s) [$sec sec]" );
381 Wikimedia\suppressWarnings();
382 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
383 Wikimedia\restoreWarnings();
385 $status->fatal(
'backend-fail-opentemp', $tmpPath );
392 foreach ( $fsFiles as $path => &$fsFile ) {
396 $status->fatal(
'backend-fail-read', $path );
405 $tmpHandle = fopen( $tmpPath,
'ab' );
406 if ( $tmpHandle ===
false ) {
407 $status->fatal(
'backend-fail-opentemp', $tmpPath );
413 foreach ( $fsFiles as $virtualSource => $fsFile ) {
415 $sourceHandle = fopen( $fsFile->getPath(),
'rb' );
416 if ( $sourceHandle ===
false ) {
417 fclose( $tmpHandle );
418 $status->fatal(
'backend-fail-read', $virtualSource );
423 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
424 fclose( $sourceHandle );
425 fclose( $tmpHandle );
426 $status->fatal(
'backend-fail-writetemp', $tmpPath );
430 fclose( $sourceHandle );
432 if ( !fclose( $tmpHandle ) ) {
433 $status->fatal(
'backend-fail-closetemp', $tmpPath );
448 if ( $dir ===
null ) {
454 if ( $shard !==
null ) {
457 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
483 if ( $dir ===
null ) {
489 if ( $shard !==
null ) {
492 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
518 if ( $dir ===
null ) {
524 if ( $shard !==
null ) {
527 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
555 if ( $subDirsRel !==
null ) {
556 foreach ( $subDirsRel as $subDirRel ) {
557 $subDir =
$params[
'dir'] .
"/{$subDirRel}";
560 unset( $subDirsRel );
565 if ( $dir ===
null ) {
572 $filesLockEx = [
$params[
'dir'] ];
578 if ( $shard !==
null ) {
582 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
608 return ( $stat ===
null ) ? null : (bool)$stat;
615 return $stat ? $stat[
'mtime'] :
false;
622 return $stat ? $stat[
'size'] :
false;
627 if ( $path ===
null ) {
631 $latest = !empty(
$params[
'latest'] );
632 if ( !$latest && !$this->cheapCache->has( $path,
'stat', self::CACHE_TTL ) ) {
635 if ( $this->cheapCache->has( $path,
'stat', self::CACHE_TTL ) ) {
636 $stat = $this->cheapCache->get( $path,
'stat' );
639 if ( is_array( $stat ) ) {
640 if ( !$latest || $stat[
'latest'] ) {
643 } elseif ( in_array( $stat, [
'NOT_EXIST',
'NOT_EXIST_LATEST' ] ) ) {
644 if ( !$latest || $stat ===
'NOT_EXIST_LATEST' ) {
650 if ( is_array( $stat ) ) {
652 $stat[
'latest'] = isset( $stat[
'latest'] ) ? $stat[
'latest'] : $latest;
653 $this->cheapCache->set( $path,
'stat', $stat );
655 if ( isset( $stat[
'sha1'] ) ) {
656 $this->cheapCache->set( $path,
'sha1',
657 [
'hash' => $stat[
'sha1'],
'latest' => $latest ] );
659 if ( isset( $stat[
'xattr'] ) ) {
661 $this->cheapCache->set( $path,
'xattr',
662 [
'map' => $stat[
'xattr'],
'latest' => $latest ] );
664 } elseif ( $stat ===
false ) {
665 $this->cheapCache->set( $path,
'stat', $latest ?
'NOT_EXIST_LATEST' :
'NOT_EXIST' );
666 $this->cheapCache->set( $path,
'xattr', [
'map' =>
false,
'latest' => $latest ] );
667 $this->cheapCache->set( $path,
'sha1', [
'hash' =>
false,
'latest' => $latest ] );
668 $this->logger->debug( __METHOD__ .
": File $path does not exist.\n" );
670 $this->logger->warning( __METHOD__ .
": Could not stat file $path.\n" );
699 Wikimedia\suppressWarnings();
700 $contents[
$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) :
false;
701 Wikimedia\restoreWarnings();
709 if ( $path ===
null ) {
713 $latest = !empty(
$params[
'latest'] );
714 if ( $this->cheapCache->has( $path,
'xattr', self::CACHE_TTL ) ) {
715 $stat = $this->cheapCache->get( $path,
'xattr' );
718 if ( !$latest || $stat[
'latest'] ) {
724 $this->cheapCache->set( $path,
'xattr', [
'map' => $fields,
'latest' => $latest ] );
735 return [
'headers' => [],
'metadata' => [] ];
740 if ( $path ===
null ) {
744 $latest = !empty(
$params[
'latest'] );
745 if ( $this->cheapCache->has( $path,
'sha1', self::CACHE_TTL ) ) {
746 $stat = $this->cheapCache->get( $path,
'sha1' );
749 if ( !$latest || $stat[
'latest'] ) {
750 return $stat[
'hash'];
754 $this->cheapCache->set( $path,
'sha1', [
'hash' => $hash,
'latest' => $latest ] );
769 return $fsFile->getSha1Base36();
787 $latest = !empty(
$params[
'latest'] );
789 foreach (
$params[
'srcs'] as $src ) {
791 if ( $path ===
null ) {
792 $fsFiles[$src] =
null;
793 } elseif ( $this->expensiveCache->has( $path,
'localRef' ) ) {
794 $val = $this->expensiveCache->get( $path,
'localRef' );
797 if ( !$latest || $val[
'latest'] ) {
798 $fsFiles[$src] = $val[
'object'];
803 $params[
'srcs'] = array_diff(
$params[
'srcs'], array_keys( $fsFiles ) );
805 $fsFiles[
$path] = $fsFile;
807 $this->expensiveCache->set( $path,
'localRef',
808 [
'object' => $fsFile,
'latest' => $latest ] );
854 $params[
'options'] = isset(
$params[
'options'] ) ?
$params[
'options'] : [];
858 if ( ( empty(
$params[
'headless'] ) ||
$params[
'headers'] ) && headers_sent() ) {
859 print "Headers already sent, terminating.\n";
886 'obResetFunc' => $this->obResetFunc,
887 'streamMimeFunc' => $this->streamMimeFunc
905 if ( $dir ===
null ) {
908 if ( $shard !==
null ) {
911 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
919 } elseif ( $exists ===
null ) {
940 if ( $dir ===
null ) {
943 if ( $shard !==
null ) {
947 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
970 if ( $dir ===
null ) {
973 if ( $shard !==
null ) {
977 $this->logger->debug( __METHOD__ .
": iterating over all container shards.\n" );
1011 'store' => StoreFileOp::class,
1012 'copy' => CopyFileOp::class,
1013 'move' => MoveFileOp::class,
1014 'delete' => DeleteFileOp::class,
1015 'create' => CreateFileOp::class,
1016 'describe' => DescribeFileOp::class,
1017 'null' => NullFileOp::class
1022 foreach ( $ops as $operation ) {
1023 $opName = $operation[
'op'];
1024 if ( isset( $supportedOps[$opName] ) ) {
1025 $class = $supportedOps[$opName];
1029 $performOps[] =
new $class( $this,
$params, $this->logger );
1050 $paths = [
'sh' => [],
'ex' => [] ];
1051 foreach ( $performOps as $fileOp ) {
1052 $paths[
'sh'] = array_merge( $paths[
'sh'], $fileOp->storagePathsRead() );
1053 $paths[
'ex'] = array_merge( $paths[
'ex'], $fileOp->storagePathsChanged() );
1056 $paths[
'sh'] = array_diff( $paths[
'sh'], $paths[
'ex'] );
1058 $paths[
'sh'] = array_merge( $paths[
'sh'], array_map(
'dirname', $paths[
'ex'] ) );
1061 LockManager::LOCK_UW => $paths[
'sh'],
1062 LockManager::LOCK_EX => $paths[
'ex']
1077 $ops = array_map( [ $this,
'sanitizeOpHeaders' ], $ops );
1083 if ( empty( $opts[
'nonLocking'] ) ) {
1095 if ( empty( $opts[
'preserveCache'] ) ) {
1101 foreach ( $performOps as $performOp ) {
1102 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1103 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1107 $this->cheapCache->resize( max( 2 * count( $paths ), self::CACHE_CHEAP_SIZE ) );
1112 $ok = $this->
preloadFileStat( [
'srcs' => $paths,
'latest' =>
true ] );
1120 $subStatus = $this->
newStatus(
'backend-fail-internal', $this->
name );
1121 foreach ( $ops as $i => $op ) {
1122 $subStatus->success[$i] =
false;
1123 ++$subStatus->failCount;
1125 $this->logger->error( static::class .
"-{$this->name} " .
1126 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1131 $status->success = $subStatus->success;
1134 $this->cheapCache->resize( self::CACHE_CHEAP_SIZE );
1144 $ops = array_map( [ $this,
'sanitizeOpHeaders' ], $ops );
1149 $supportedOps = [
'create',
'store',
'copy',
'move',
'delete',
'describe',
'null' ];
1151 $async = ( $this->parallelize ===
'implicit' && count( $ops ) > 1 );
1155 $fileOpHandles = [];
1156 $curFileOpHandles = [];
1158 foreach ( $ops as $index =>
$params ) {
1159 if ( !in_array(
$params[
'op'], $supportedOps ) ) {
1160 throw new FileBackendError(
"Operation '{$params['op']}' is not supported." );
1162 $method =
$params[
'op'] .
'Internal';
1163 $subStatus = $this->$method( [
'async' => $async ] +
$params );
1165 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1166 $fileOpHandles[] = $curFileOpHandles;
1167 $curFileOpHandles = [];
1169 $curFileOpHandles[$index] = $subStatus->value;
1171 $statuses[$index] = $subStatus;
1174 if ( count( $curFileOpHandles ) ) {
1175 $fileOpHandles[] = $curFileOpHandles;
1178 foreach ( $fileOpHandles as $fileHandleBatch ) {
1182 foreach ( $statuses as $index => $subStatus ) {
1184 if ( $subStatus->isOK() ) {
1185 $status->success[$index] =
true;
1188 $status->success[$index] =
false;
1208 foreach ( $fileOpHandles as $fileOpHandle ) {
1210 throw new InvalidArgumentException(
"Expected FileBackendStoreOpHandle object." );
1211 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1212 throw new InvalidArgumentException(
"Expected handle for this file backend." );
1217 foreach ( $fileOpHandles as $fileOpHandle ) {
1218 $fileOpHandle->closeResources();
1233 if ( count( $fileOpHandles ) ) {
1234 throw new LogicException(
"Backend does not support asynchronous operations." );
1252 static $longs = [
'content-disposition' ];
1254 if ( isset( $op[
'headers'] ) ) {
1256 foreach ( $op[
'headers'] as $name =>
$value ) {
1257 $name = strtolower( $name );
1258 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1259 if ( strlen( $name ) > 255 || strlen(
$value ) > $maxHVLen ) {
1260 trigger_error(
"Header '$name: $value' is too long." );
1265 $op[
'headers'] = $newHeaders;
1273 foreach ( $paths as $path ) {
1275 $fullConts[] = $fullCont;
1283 if ( is_array( $paths ) ) {
1284 $paths = array_map(
'FileBackend::normalizeStoragePath', $paths );
1285 $paths = array_filter( $paths,
'strlen' );
1287 if ( $paths ===
null ) {
1288 $this->cheapCache->clear();
1289 $this->expensiveCache->clear();
1291 foreach ( $paths as $path ) {
1292 $this->cheapCache->clear( $path );
1293 $this->expensiveCache->clear( $path );
1313 $params[
'concurrency'] = ( $this->parallelize !==
'off' ) ? $this->concurrency : 1;
1315 if ( $stats ===
null ) {
1319 $latest = !empty(
$params[
'latest'] );
1320 foreach ( $stats as $path => $stat ) {
1322 if ( $path ===
null ) {
1325 if ( is_array( $stat ) ) {
1327 $stat[
'latest'] = isset( $stat[
'latest'] ) ? $stat[
'latest'] : $latest;
1328 $this->cheapCache->set( $path,
'stat', $stat );
1330 if ( isset( $stat[
'sha1'] ) ) {
1331 $this->cheapCache->set( $path,
'sha1',
1332 [
'hash' => $stat[
'sha1'],
'latest' => $latest ] );
1334 if ( isset( $stat[
'xattr'] ) ) {
1336 $this->cheapCache->set( $path,
'xattr',
1337 [
'map' => $stat[
'xattr'],
'latest' => $latest ] );
1339 } elseif ( $stat ===
false ) {
1340 $this->cheapCache->set( $path,
'stat',
1341 $latest ?
'NOT_EXIST_LATEST' :
'NOT_EXIST' );
1342 $this->cheapCache->set( $path,
'xattr',
1343 [
'map' =>
false,
'latest' => $latest ] );
1344 $this->cheapCache->set( $path,
'sha1',
1345 [
'hash' =>
false,
'latest' => $latest ] );
1346 $this->logger->debug( __METHOD__ .
": File $path does not exist.\n" );
1349 $this->logger->warning( __METHOD__ .
": Could not stat file $path.\n" );
1412 return (
bool)preg_match(
'/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1430 if ( $backend === $this->
name ) {
1432 if ( $relPath !==
null && self::isValidShortContainerName( $shortCont ) ) {
1437 if ( $relPath !==
null ) {
1440 if ( self::isValidContainerName( $container ) ) {
1443 if ( $container !==
null ) {
1444 return [ $container, $relPath, $cShard ];
1451 return [
null,
null, null ];
1471 if ( $cShard !==
null && substr( $relPath, -1 ) !==
'/' ) {
1472 return [ $container, $relPath ];
1475 return [
null, null ];
1488 if ( $levels == 1 || $levels == 2 ) {
1490 $char = (
$base == 36 ) ?
'[0-9a-z]' :
'[0-9a-f]';
1493 if ( $levels === 1 ) {
1494 $hashDirRegex =
'(' . $char .
')';
1497 $hashDirRegex = $char .
'/(' . $char .
'{2})';
1499 $hashDirRegex =
'(' . $char .
')/(' . $char .
')';
1506 if ( preg_match(
"!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1507 return '.' . implode(
'', array_slice( $m, 1 ) );
1527 return ( $shard !==
null );
1539 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1540 $config = $this->shardViaHashLevels[$container];
1541 $hashLevels = (int)$config[
'levels'];
1542 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1543 $hashBase = (int)$config[
'base'];
1544 if ( $hashBase == 16 || $hashBase == 36 ) {
1545 return [ $hashLevels, $hashBase, $config[
'repeat'] ];
1550 return [ 0, 0,
false ];
1562 if ( $digits > 0 ) {
1563 $numShards = pow(
$base, $digits );
1564 for ( $index = 0; $index < $numShards; $index++ ) {
1565 $shards[] =
'.' . Wikimedia\base_convert( $index, 10,
$base, $digits );
1579 if ( $this->domainId !=
'' ) {
1580 return "{$this->domainId}-$container";
1609 return $relStoragePath;
1619 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1629 $this->memCache->set( $this->
containerCacheKey( $container ), $val, 14 * 86400 );
1639 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1640 trigger_error(
"Unable to delete stat cache for container $container." );
1657 foreach ( $items as $item ) {
1658 if ( self::isStoragePath( $item ) ) {
1660 } elseif ( is_string( $item ) ) {
1665 foreach ( $paths as $path ) {
1667 if ( $fullCont !==
null ) {
1674 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1675 foreach ( $values as $cacheKey => $val ) {
1676 $contInfo[$contNames[$cacheKey]] = $val;
1700 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1713 if ( $path ===
null ) {
1716 $mtime = ConvertibleTimestamp::convert( TS_UNIX, $val[
'mtime'] );
1717 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1720 $this->memCache->set( $key, $val, $ttl );
1733 if ( $path ===
null ) {
1736 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1737 trigger_error(
"Unable to delete stat cache for file $path." );
1754 foreach ( $items as $item ) {
1755 if ( self::isStoragePath( $item ) ) {
1760 $paths = array_filter( $paths,
'strlen' );
1762 foreach ( $paths as $path ) {
1764 if ( $rel !==
null ) {
1769 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1770 foreach ( $values as $cacheKey => $val ) {
1771 $path = $pathNames[$cacheKey];
1772 if ( is_array( $val ) ) {
1773 $val[
'latest'] =
false;
1774 $this->cheapCache->set( $path,
'stat', $val );
1775 if ( isset( $val[
'sha1'] ) ) {
1776 $this->cheapCache->set( $path,
'sha1',
1777 [
'hash' => $val[
'sha1'],
'latest' =>
false ] );
1779 if ( isset( $val[
'xattr'] ) ) {
1781 $this->cheapCache->set( $path,
'xattr',
1782 [
'map' => $val[
'xattr'],
'latest' =>
false ] );
1796 $newXAttr = [
'headers' => [],
'metadata' => [] ];
1798 foreach ( $xattr[
'headers'] as $name =>
$value ) {
1799 $newXAttr[
'headers'][strtolower( $name )] =
$value;
1802 foreach ( $xattr[
'metadata'] as $name =>
$value ) {
1803 $newXAttr[
'metadata'][strtolower( $name )] =
$value;
1816 $opts[
'concurrency'] = 1;
1817 if ( $this->parallelize ===
'implicit' ) {
1818 if ( !isset( $opts[
'parallelize'] ) || $opts[
'parallelize'] ) {
1821 } elseif ( $this->parallelize ===
'explicit' ) {
1822 if ( !empty( $opts[
'parallelize'] ) ) {
1839 if ( $this->mimeCallback ) {
1840 return call_user_func_array( $this->mimeCallback, func_get_args() );
1843 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) :
false;
1844 return $mime ?:
'unknown/unknown';
1870 array_map(
'fclose', $this->resourcesToClose );
1911 $iter =
new AppendIterator();
1912 foreach ( $suffixes as $suffix ) {
1913 $iter->append( $this->
listFromShard( $this->container . $suffix ) );
1916 parent::__construct( $iter );
1920 $rel = $this->getInnerIterator()->current();
1921 $path = $this->params[
'dir'] .
"/{$rel}";
1922 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1924 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1928 $this->multiShardPaths[$rel] = 1;
1936 $this->multiShardPaths = [];
1953 $list = $this->backend->getDirectoryListInternal(
1955 if ( $list ===
null ) {
1956 return new ArrayIterator( [] );
1958 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1968 $list = $this->backend->getFileListInternal(
1970 if ( $list ===
null ) {
1971 return new ArrayIterator( [] );
1973 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
interface is intended to be more or less compatible with the PHP memcached client.
A BagOStuff object with no objects in it.
static placeholderProps()
Placeholder file properties to use for files that don't exist.
File backend exception for checked exceptions (e.g.
FileBackendStore helper class for performing asynchronous file operations.
closeResources()
Close all open file handles.
FileBackendStore $backend
Iterator for listing directories.
listFromShard( $container)
Get the list for a given container shard.
Iterator for listing regular files.
listFromShard( $container)
Get the list for a given container shard.
FileBackendStore helper function to handle listings that span container shards.
__construct(FileBackendStore $backend, $container, $dir, array $suffixes, array $params)
string $container
Full container name.
string $directory
Resolved relative path.
FileBackendStore $backend
listFromShard( $container)
Get the list for a given container shard.
Base class for all backends using particular storage medium.
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
containerCacheKey( $container)
Get the cache key for a container.
doGetLocalReferenceMulti(array $params)
resolveContainerName( $container)
Resolve a container name, checking if it's allowed by the backend.
static normalizeXAttributes(array $xattr)
Normalize file headers/metadata to the FileBackend::getFileXAttributes() format.
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and returns a map of storage paths...
setFileCache( $path, array $val)
Set the cached stat info for a file path.
moveInternal(array $params)
Move a file from one storage path to another in the backend.
setContainerCache( $container, array $val)
Set the cached info for a container.
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path.
doGetFileContentsMulti(array $params)
doStreamFile(array $params)
const CACHE_EXPENSIVE_SIZE
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
doGetLocalCopyMulti(array $params)
getScopedLocksForOps(array $ops, StatusValue $status)
Get an array of scoped locks needed for a batch of file operations.
doQuickOperationsInternal(array $ops)
doCleanInternal( $container, $dir, array $params)
callable $mimeCallback
Method to get the MIME type of files.
getPathsToLockForOpsInternal(array $performOps)
Get a list of storage paths to lock for a list of operations Returns an array with LockManager::LOCK_...
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
doPrepareInternal( $container, $dir, array $params)
concatenate(array $params)
Concatenate a list of storage files into a single file system file.
storeInternal(array $params)
Store a file into the backend from a file on disk.
getFileProps(array $params)
Get the properties of the file at a storage path in the backend.
getDirectoryList(array $params)
Get an iterator to list all directories under a storage directory.
resolveStoragePath( $storagePath)
Splits a storage path into an internal container name, an internal relative file name,...
copyInternal(array $params)
Copy a file from one storage path to another in the backend.
doStoreInternal(array $params)
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doGetFileStat(array $params)
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
doPublishInternal( $container, $dir, array $params)
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
ProcessCacheLRU $expensiveCache
Map of paths to large (RAM/disk) cache items.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the file at a storage path in the backend.
static isValidContainerName( $container)
Check if a full container name is valid.
getFileListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
doCopyInternal(array $params)
getLocalCopyMulti(array $params)
Like getLocalCopy() except it takes an array of storage paths and returns a map of storage paths to T...
getFileContentsMulti(array $params)
Like getFileContents() except it takes an array of storage paths and returns a map of storage paths t...
doClearCache(array $paths=null)
Clears any additional stat caches for storage paths.
fullContainerName( $container)
Get the full container name, including the wiki ID prefix.
primeFileCache(array $items)
Do a batch lookup from cache for file stats for all paths used in a list of storage paths or FileOp o...
doOperationsInternal(array $ops, array $opts)
isSingleShardPathInternal( $storagePath)
Check if a storage path maps to a single shard.
directoryExists(array $params)
Check if a directory exists at a given storage path.
doDeleteInternal(array $params)
getContainerSuffixes( $container)
Get a list of full container shard suffixes for a container.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
sanitizeOpHeaders(array $op)
Normalize and filter HTTP headers from a file operation.
doDescribeInternal(array $params)
doGetFileSha1Base36(array $params)
deleteInternal(array $params)
Delete a file at the storage path.
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
doMoveInternal(array $params)
maxFileSizeInternal()
Get the maximum allowable file size given backend medium restrictions and basic performance constrain...
describeInternal(array $params)
Alter metadata for a file at the storage path.
streamFile(array $params)
Stream the file at a storage path in the backend.
getOperationsInternal(array $ops)
Return a list of FileOp objects from a list of operations.
deleteFileCache( $path)
Delete the cached stat info for a file path.
setConcurrencyFlags(array $opts)
Set the 'concurrency' option from a list of operation options.
getFileXAttributes(array $params)
Get metadata about a file at a storage path in the backend.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
ProcessCacheLRU $cheapCache
Map of paths to small (RAM/disk) cache items.
preloadCache(array $paths)
Preload persistent file stat cache and property cache into in-process cache.
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
doDirectoryExists( $container, $dir, array $params)
getFileHttpUrl(array $params)
__construct(array $config)
doGetFileXAttributes(array $params)
doExecuteOpHandlesInternal(array $fileOpHandles)
nullInternal(array $params)
No-op file operation that does nothing.
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
array $shardViaHashLevels
Map of container names to sharding config.
fileCacheKey( $path)
Get the cache key for a file path.
doConcatenate(array $params)
doSecureInternal( $container, $dir, array $params)
doCreateInternal(array $params)
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getDirectoryListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
static isValidShortContainerName( $container)
Check if a short container name is valid.
getContainerHashLevels( $container)
Get the sharding config for a container.
getContainerShard( $container, $relPath)
Get the container name shard suffix for a given path.
deleteContainerCache( $container)
Delete the cached info for a container.
createInternal(array $params)
Create a file in the backend with the given contents.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
static normalizeContainerPath( $path)
Validate and normalize a relative storage path.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
getTopDirectoryList(array $params)
Same as FileBackend::getDirectoryList() except only lists directories that are immediately under the ...
newStatus()
Yields the result of the status wrapper callback on either:
scopedProfileSection( $section)
static normalizeStoragePath( $storagePath)
Normalize a storage path by cleaning up directory separators.
int $concurrency
How many operations can be done in parallel.
getLocalReference(array $params)
Returns a file system file, identical to the file at a storage path.
static attempt(array $performOps, array $opts, FileJournal $journal)
Attempt to perform a series of file operations.
Functions related to the output of file content.
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Class for process caching individual properties of expiring items.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Multi-datacenter aware caching interface.
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
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. '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
> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. '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) name
processing should stop and the error should be shown to the user * false
while(( $__line=Maintenance::readconsole()) !==false) print
if( $ext=='php'|| $ext=='php5') $mime
The most up to date schema for the tables in the database will always be tables sql in the maintenance directory