113 parent::__construct( $config );
115 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
116 $this->swiftUser = $config[
'swiftUser'];
117 $this->swiftKey = $config[
'swiftKey'];
119 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
120 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
121 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
122 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
123 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
124 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
129 $this->memCache = $config[
'wanCache'];
132 $this->containerStatCache =
new MapCacheLRU( 300 );
134 if ( !empty( $config[
'cacheAuthInfo'] ) &&
isset( $config[
'srvCache'] ) ) {
135 $this->srvCache = $config[
'srvCache'];
139 $this->readUsers = $config[
'readUsers'] ?? [];
140 $this->writeUsers = $config[
'writeUsers'] ?? [];
141 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
142 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
162 if ( $rel ===
null ) {
182 unset( $headers[
'content-type' ] );
213 foreach ( $rawHeaders as $name =>
$value ) {
215 if (
preg_match(
'/^content-length$/', $name ) ) {
224 if (
isset( $headers[
'content-disposition'] ) ) {
227 foreach ( explode(
';', $headers[
'content-disposition'] ) as $part ) {
228 $part =
trim( $part );
229 $new = ( $disposition ===
'' ) ? $part :
"{$disposition};{$part}";
230 if (
strlen( $new ) <= 255 ) {
248 foreach ( $rawHeaders as $name =>
$value ) {
250 if (
strpos( $name,
'x-object-meta-' ) === 0 ) {
275 if ( $dstRel ===
null ) {
282 $contentType =
$params[
'headers'][
'content-type']
299 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
300 if ( $rcode === 201 ) {
302 }
elseif ( $rcode === 412 ) {
310 if ( !empty(
$params[
'async'] ) ) {
323 if ( $dstRel ===
null ) {
332 if ( $sha1Hash ===
false ) {
338 $contentType =
$params[
'headers'][
'content-type']
342 if ( $handle ===
false ) {
362 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
363 if ( $rcode === 201 ) {
365 }
elseif ( $rcode === 412 ) {
373 $opHandle->resourcesToClose[] = $handle;
375 if ( !empty(
$params[
'async'] ) ) {
388 if ( $srcRel ===
null ) {
395 if ( $dstRel ===
null ) {
412 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
413 if ( $rcode === 201 ) {
415 }
elseif ( $rcode === 404 ) {
423 if ( !empty(
$params[
'async'] ) ) {
436 if ( $srcRel ===
null ) {
443 if ( $dstRel ===
null ) {
459 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
461 'method' =>
'DELETE',
469 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
470 if (
$request[
'method'] ===
'PUT' && $rcode === 201 ) {
474 }
elseif ( $rcode === 404 ) {
482 if ( !empty(
$params[
'async'] ) ) {
495 if ( $srcRel ===
null ) {
502 'method' =>
'DELETE',
509 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
510 if ( $rcode === 204 ) {
512 }
elseif ( $rcode === 404 ) {
513 if ( empty(
$params[
'ignoreMissingSource'] ) ) {
522 if ( !empty(
$params[
'async'] ) ) {
535 if ( $srcRel ===
null ) {
542 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
543 if ( $stat && !
isset( $stat[
'xattr'] ) ) {
544 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
554 foreach ( $stat[
'xattr'][
'metadata'] as $name =>
$value ) {
555 $metaHdrs[
"x-object-meta-$name"] =
$value;
557 $customHdrs = $this->
sanitizeHdrs( $params ) + $stat[
'xattr'][
'headers'];
567 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) =
$request[
'response'];
568 if ( $rcode === 202 ) {
570 }
elseif ( $rcode === 404 ) {
578 if ( !empty(
$params[
'async'] ) ) {
594 }
elseif ( $stat ===
null ) {
595 $status->fatal(
'backend-fail-internal', $this->
name );
596 $this->logger->error( __METHOD__ .
': cannot get container stat' );
602 if ( $stat ===
false ) {
612 if ( empty(
$params[
'noAccess'] ) ) {
626 }
elseif ( $stat ===
false ) {
629 $status->fatal(
'backend-fail-internal', $this->
name );
630 $this->logger->error( __METHOD__ .
': cannot get container stat' );
650 }
elseif ( $stat ===
false ) {
653 $status->fatal(
'backend-fail-internal', $this->
name );
654 $this->logger->error( __METHOD__ .
': cannot get container stat' );
670 if ( $stat ===
false ) {
673 $status->fatal(
'backend-fail-internal', $this->
name );
674 $this->logger->error( __METHOD__ .
': cannot get container stat' );
680 if ( $stat[
'count'] == 0 ) {
693 return reset( $stats );
710 return $timestamp->getTimestamp( $format );
711 }
catch ( Exception
$e ) {
724 if (
isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
730 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
731 [
'path' => $path ] );
733 $objHdrs[
'x-object-meta-sha1base36'] =
false;
749 $tmpFile = $this->
getLocalCopy( [
'src' => $path,
'latest' => 1 ] );
751 $hash = $tmpFile->getSha1Base36();
752 if ( $hash !==
false ) {
753 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
755 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
757 list( $rcode ) = $this->
http->run( [
759 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
762 if ( $rcode >= 200 && $rcode <= 299 ) {
771 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
772 [
'path' => $path ] );
787 foreach (
$params[
'srcs'] as $path ) {
789 if ( $srcRel ===
null || !$auth ) {
790 $contents[
$path] =
false;
794 $handle =
fopen(
'php://temp',
'wb' );
798 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
804 $contents[
$path] =
false;
807 $opts = [
'maxConnsPerHost' =>
$params[
'concurrency'] ];
808 $reqs = $this->
http->runMulti( $reqs, $opts );
809 foreach ( $reqs as $path => $op ) {
810 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
811 if ( $rcode >= 200 && $rcode <= 299 ) {
812 rewind( $op[
'stream'] );
814 }
elseif ( $rcode === 404 ) {
815 $contents[
$path] =
false;
817 $this->
onError(
null, __METHOD__,
818 [
'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
827 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
830 return ( count(
$status->value ) ) > 0;
871 if ( $after === INF ) {
877 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
879 if ( !empty(
$params[
'topOnly'] ) ) {
885 foreach ( $objects as $object ) {
886 if (
substr( $object, -1 ) ===
'/' ) {
892 $getParentDir =
function (
$path ) {
906 foreach ( $objects as $object ) {
909 if ( $objectDir !==
false && $objectDir !== $dir ) {
914 if (
strcmp( $objectDir, $lastDir ) > 0 ) {
917 $dirs[] =
"{$pDir}/";
919 }
while ( $pDir !==
false
920 &&
strcmp( $pDir, $lastDir ) > 0
929 if ( count( $objects ) < $limit ) {
932 $after = end( $objects );
951 if ( $after === INF ) {
957 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
960 if ( !empty(
$params[
'topOnly'] ) ) {
961 if ( !empty(
$params[
'adviseStat'] ) ) {
968 if ( !empty(
$params[
'adviseStat'] ) ) {
984 if ( count( $objects ) < $limit ) {
987 $after = end( $objects );
1005 foreach ( $objects as $object ) {
1007 if (
isset( $object->subdir ) || !isset( $object->name ) ) {
1013 'size' => (
int)$object->bytes,
1016 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1019 $names[] = [ $object->name,
$stat ];
1022 $names[] = [ $object,
null ];
1036 $this->cheapCache->setField( $path,
'stat', $val );
1042 if ( !
isset( $stat[
'xattr'] ) ) {
1048 return $stat[
'xattr'];
1057 $params[
'requireSHA1'] =
true;
1061 return $stat[
'sha1'];
1073 if ( $srcRel ===
null ) {
1102 if ( empty(
$params[
'allowOB'] ) ) {
1107 $handle =
fopen(
'php://output',
'wb' );
1108 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1110 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1113 'stream' => $handle,
1114 'flags' => [
'relayResponseHeaders' => empty(
$params[
'headless'] ) ]
1117 if ( $rcode >= 200 && $rcode <= 299 ) {
1119 }
elseif ( $rcode === 404 ) {
1144 foreach (
$params[
'srcs'] as $path ) {
1146 if ( $srcRel ===
null || !$auth ) {
1147 $tmpFiles[
$path] =
null;
1155 $handle =
fopen( $tmpFile->getPath(),
'wb' );
1159 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1162 'stream' => $handle,
1168 $tmpFiles[
$path] = $tmpFile;
1171 $isLatest = ( $this->isRGW || !empty(
$params[
'latest'] ) );
1172 $opts = [
'maxConnsPerHost' =>
$params[
'concurrency'] ];
1173 $reqs = $this->
http->runMulti( $reqs, $opts );
1174 foreach ( $reqs as $path => $op ) {
1175 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1177 if ( $rcode >= 200 && $rcode <= 299 ) {
1178 $size = $tmpFiles[
$path] ? $tmpFiles[
$path]->getSize() : 0;
1180 if ( $size != $rhdrs[
'content-length'] ) {
1181 $tmpFiles[
$path] =
null;
1182 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1183 $this->
onError(
null, __METHOD__,
1184 [
'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1189 $this->cheapCache->setField( $path,
'stat', $stat );
1190 }
elseif ( $rcode === 404 ) {
1191 $tmpFiles[
$path] =
false;
1193 $tmpFiles[
$path] =
null;
1194 $this->
onError(
null, __METHOD__,
1195 [
'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1203 if ( $this->swiftTempUrlKey !=
'' ||
1204 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1207 if ( $srcRel ===
null ) {
1216 $ttl =
$params[
'ttl'] ?? 86400;
1217 $expires = time() + $ttl;
1219 if ( $this->swiftTempUrlKey !=
'' ) {
1220 $url = $this->
storageUrl( $auth, $srcCont, $srcRel );
1224 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1225 $this->swiftTempUrlKey
1228 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1236 "GET\n\n\n{$expires}\n{$spath}",
1237 $this->rgwS3SecretKey,
1246 'Signature' => $signature,
1247 'Expires' => $expires,
1248 'AWSAccessKeyId' => $this->rgwS3AccessKey
1270 if ( !empty(
$params[
'latest'] ) ) {
1271 $hdrs[
'x-newest'] =
'true';
1288 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1289 $statuses[$index] = $this->
newStatus(
'backend-fail-connect', $this->
name );
1296 $httpReqsByStage = [];
1297 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1299 $reqs = $fileOpHandle->httpOp;
1301 foreach ( $reqs as $stage => &
$req ) {
1302 list( $container, $relPath ) =
$req[
'url'];
1304 $req[
'headers'] =
$req[
'headers'] ?? [];
1306 $httpReqsByStage[$stage][$index] =
$req;
1312 $reqCount = count( $httpReqsByStage );
1313 for ( $stage = 0; $stage <
$reqCount; ++$stage ) {
1314 $httpReqs = $this->
http->runMulti( $httpReqsByStage[$stage] );
1315 foreach ( $httpReqs as $index => $httpReq ) {
1317 $callback = $fileOpHandles[$index]->callback;
1318 $callback( $httpReq, $statuses[$index] );
1321 if ( !$statuses[$index]->isOK() ) {
1322 $stages = count( $fileOpHandles[$index]->httpOp );
1324 unset( $httpReqsByStage[
$s][$index] );
1360 $status->fatal(
'backend-fail-connect', $this->
name );
1365 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1367 'url' => $this->
storageUrl( $auth, $container ),
1369 'x-container-read' => implode(
',',
$readUsers ),
1370 'x-container-write' => implode(
',',
$writeUsers )
1374 if ( $rcode != 204 && $rcode !== 202 ) {
1375 $status->fatal(
'backend-fail-internal', $this->
name );
1376 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1377 [
'rcode' => $rcode ] );
1394 if ( $bypassCache ) {
1395 $this->containerStatCache->clear( $container );
1396 }
elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1399 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1405 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1407 'url' => $this->
storageUrl( $auth, $container ),
1411 if ( $rcode === 204 ) {
1413 'count' => $rhdrs[
'x-container-object-count'],
1414 'bytes' => $rhdrs[
'x-container-bytes-used']
1416 if ( $bypassCache ) {
1419 $this->containerStatCache->setField( $container,
'stat', $stat );
1422 }
elseif ( $rcode === 404 ) {
1425 $this->
onError(
null, __METHOD__,
1426 [
'cont' => $container ], $rerr, $rcode, $rdesc );
1432 return $this->containerStatCache->getField( $container,
'stat' );
1447 $status->fatal(
'backend-fail-connect', $this->
name );
1453 if ( empty(
$params[
'noAccess'] ) ) {
1463 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1465 'url' => $this->
storageUrl( $auth, $container ),
1467 'x-container-read' => implode(
',',
$readUsers ),
1468 'x-container-write' => implode(
',',
$writeUsers )
1472 if ( $rcode === 201 ) {
1474 }
elseif ( $rcode === 202 ) {
1495 $status->fatal(
'backend-fail-connect', $this->
name );
1500 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1501 'method' =>
'DELETE',
1502 'url' => $this->
storageUrl( $auth, $container ),
1506 if ( $rcode >= 200 && $rcode <= 299 ) {
1507 $this->containerStatCache->clear( $container );
1508 }
elseif ( $rcode === 404 ) {
1510 }
elseif ( $rcode === 409 ) {
1532 $fullCont,
$type, $limit, $after =
null, $prefix =
null, $delim =
null
1538 $status->fatal(
'backend-fail-connect', $this->
name );
1543 $query = [
'limit' => $limit ];
1544 if (
$type ===
'info' ) {
1545 $query[
'format'] =
'json';
1547 if ( $after !==
null ) {
1550 if ( $prefix !==
null ) {
1551 $query[
'prefix'] = $prefix;
1553 if ( $delim !==
null ) {
1554 $query[
'delimiter'] = $delim;
1557 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1559 'url' => $this->
storageUrl( $auth, $fullCont ),
1565 if ( $rcode === 200 ) {
1566 if (
$type ===
'info' ) {
1567 $status->value = FormatJson::decode(
trim( $rbody ) );
1571 }
elseif ( $rcode === 204 ) {
1573 }
elseif ( $rcode === 404 ) {
1583 foreach ( $containerInfo as $container => $info ) {
1584 $this->containerStatCache->setField( $container,
'stat', $info );
1594 foreach (
$params[
'srcs'] as $path ) {
1596 if ( $srcRel ===
null ) {
1597 $stats[
$path] =
false;
1600 $stats[
$path] =
null;
1606 if ( $cstat ===
false ) {
1607 $stats[
$path] =
false;
1610 $stats[
$path] =
null;
1616 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1621 $opts = [
'maxConnsPerHost' =>
$params[
'concurrency'] ];
1622 $reqs = $this->
http->runMulti( $reqs, $opts );
1624 foreach (
$params[
'srcs'] as $path ) {
1629 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[
$path][
'response'];
1630 if ( $rcode === 200 || $rcode === 204 ) {
1632 if ( !empty(
$params[
'requireSHA1'] ) ) {
1637 if ( $this->isRGW ) {
1638 $stat[
'latest'] =
true;
1640 }
elseif ( $rcode === 404 ) {
1644 $this->
onError(
null, __METHOD__,
$params, $rerr, $rcode, $rdesc );
1660 $headers = $this->
sanitizeHdrs( [
'headers' => $rhdrs ] );
1666 'size' =>
isset( $rhdrs[
'content-length'] ) ? (
int)$rhdrs[
'content-length'] : 0,
1667 'sha1' => $metadata[
'sha1base36'] ??
null,
1669 'md5' =>
ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1670 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1678 if ( $this->authErrorTimestamp !==
null ) {
1679 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1682 $this->authErrorTimestamp =
null;
1688 if ( !$this->authCreds || $reAuth ) {
1689 $this->authSessionTimestamp = 0;
1691 $creds = $this->srvCache->get( $cacheKey );
1693 if (
isset( $creds[
'auth_token'] ) &&
isset( $creds[
'storage_url'] ) ) {
1694 $this->authCreds =
$creds;
1696 $this->authSessionTimestamp = time() -
ceil( $this->authTTL / 2 );
1698 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->
http->run( [
1700 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1702 'x-auth-user' => $this->swiftUser,
1703 'x-auth-key' => $this->swiftKey
1707 if ( $rcode >= 200 && $rcode <= 299 ) {
1708 $this->authCreds = [
1709 'auth_token' => $rhdrs[
'x-auth-token'],
1710 'storage_url' => ( $this->swiftStorageUrl !==
null )
1711 ? $this->swiftStorageUrl
1712 : $rhdrs[
'x-storage-url']
1715 $this->srvCache->set( $cacheKey, $this->authCreds,
ceil( $this->authTTL / 2 ) );
1716 $this->authSessionTimestamp = time();
1717 }
elseif ( $rcode === 401 ) {
1718 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1719 $this->authErrorTimestamp = time();
1723 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode );
1724 $this->authErrorTimestamp = time();
1730 if (
substr( $this->authCreds[
'storage_url'], -3 ) ===
'/v1' ) {
1731 $this->isRGW =
true;
1745 $parts = [ $creds[
'storage_url'] ];
1746 if (
strlen( $container ) ) {
1749 if (
strlen( $object ) ) {
1753 return implode(
'/', $parts );
1761 return [
'x-auth-token' => $creds[
'auth_token'] ];
1771 return 'swiftcredentials:' .
md5(
$username .
':' . $this->swiftAuthUrl );
1787 $status->fatal(
'backend-fail-internal', $this->
name );
1789 if (
$code == 401 ) {
1792 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1797 'req_params' => FormatJson::encode(
$params ),
1801 $msgParams[
'err'] =
$err;
1803 $this->logger->error( $msg, $msgParams );
1872 if (
substr( $this->dir, -1 ) ===
'/' ) {
1873 $this->dir =
substr( $this->dir, 0, -1 );
1875 if ( $this->dir ==
'' ) {
1876 $this->suffixStart = 0;
1878 $this->suffixStart =
strlen( $this->dir ) + 1;
1896 next( $this->bufferIter );
1900 if ( !$this->
valid() && count( $this->bufferIter ) ) {
1902 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1912 $this->bufferAfter =
null;
1914 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1923 if ( $this->bufferIter ===
null ) {
1926 return ( current( $this->bufferIter ) !==
false );
1952 return substr(
current( $this->bufferIter ), $this->suffixStart, -1 );
1969 list( $path, $stat ) =
current( $this->bufferIter );
1970 $relPath =
substr( $path, $this->suffixStart );
1972 $storageDir =
rtrim( $this->params[
'dir'],
'/' );
1973 $this->backend->loadListingStatInternal(
"$storageDir/$relPath", $stat );
Apache License January http
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
Class representing a cache/ephemeral data store.
A BagOStuff object with no objects in it.
File backend exception for checked exceptions (e.g.
FileBackendStore helper class for performing asynchronous file operations.
FileBackendStore $backend
Base class for all backends using particular storage medium.
setContainerCache( $container, array $val)
Set the cached info for a container.
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
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.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
deleteFileCache( $path)
Delete the cached stat info for a file path.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getLocalCopy(array $params)
Get a local copy on disk of the file at a storage path in the backend.
string $name
Unique backend name.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
newStatus()
Yields the result of the status wrapper callback on either:
scopedProfileSection( $section)
const ATTR_HEADERS
Bitfield flags for supported features.
Library for creating and parsing MW-style timestamps.
Handles a simple LRU key/value map with a maximum number of entries.
Class to handle multiple HTTP requests.
Class for process caching individual properties of expiring items.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Iterator for listing directories.
pageFromList( $container, $dir, &$after, $limit, array $params)
Get the given list portion (page)
Iterator for listing regular files.
pageFromList( $container, $dir, &$after, $limit, array $params)
Get the given list portion (page)
SwiftFileBackend helper class to page through listings.
string $dir
Storage directory.
string $container
Container name.
__construct(SwiftFileBackend $backend, $fullCont, $dir, array $params)
string $bufferAfter
List items after this path.
pageFromList( $container, $dir, &$after, $limit, array $params)
Get the given list portion (page)
array $bufferIter
List of path or (path,stat array) entries.
SwiftFileBackend $backend
Class for an OpenStack Swift (or Ceph RGW) based file backend.
string $swiftUser
Swift user (account:user) to authenticate as.
sanitizeHdrs(array $params)
Sanitize and filter the custom headers from a $params array.
string $swiftAuthUrl
Authentication base URL (without version)
string $swiftTempUrlKey
Shared secret value for making temp URLs.
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path.
getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
doPublishInternal( $fullCont, $dir, array $params)
doCreateInternal(array $params)
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
doGetFileSha1base36(array $params)
array $writeUsers
Additional users (account:user) with write permissions on public containers.
__construct(array $config)
doGetFileXAttributes(array $params)
onError( $status, $func, array $params, $err='', $code=0, $desc='')
Log an unexpected exception for this backend.
buildFileObjectListing(array $params, $dir, array $objects)
Build a list of file objects, filtering out any directories and extracting any stat info if provided ...
authTokenHeaders(array $creds)
getStatFromHeaders(array $rhdrs)
string $swiftStorageUrl
Override of storage base URL.
createContainer( $container, array $params)
Create a Swift container.
doCopyInternal(array $params)
getCredsCacheKey( $username)
Get the cache key for a container.
getDirectoryListInternal( $fullCont, $dir, array $params)
string $rgwS3AccessKey
S3 access key (RADOS Gateway)
setContainerAccess( $container, array $readUsers, array $writeUsers)
Set read/write permissions for a Swift container.
getFileHttpUrl(array $params)
array $secureWriteUsers
Additional users (account:user) with write permissions on private containers.
getCustomHeaders(array $rawHeaders)
int $authTTL
TTL in seconds.
headersFromParams(array $params)
Get headers to send to Swift when reading a file based on a FileBackend params array,...
getMetadata(array $rawHeaders)
bool $isRGW
Whether the server is an Ceph RGW.
doStoreInternal(array $params)
int $authErrorTimestamp
UNIX timestamp.
getMetadataHeaders(array $rawHeaders)
int $authSessionTimestamp
UNIX timestamp.
loadListingStatInternal( $path, array $val)
Do not call this function outside of SwiftFileBackendFileList.
doPrepareInternal( $fullCont, $dir, array $params)
doSecureInternal( $fullCont, $dir, array $params)
getFileListInternal( $fullCont, $dir, array $params)
doMoveInternal(array $params)
addMissingHashMetadata(array $objHdrs, $path)
Fill in any missing object metadata and save it to Swift.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
deleteContainer( $container, array $params)
Delete a Swift container.
doGetFileStat(array $params)
doGetLocalCopyMulti(array $params)
string $rgwS3SecretKey
S3 authentication key (RADOS Gateway)
doGetFileContentsMulti(array $params)
storageUrl(array $creds, $container=null, $object=null)
convertSwiftDate( $ts, $format=TS_MW)
Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
doStreamFile(array $params)
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
sanitizeHdrsStrict(array $params)
Sanitize and filter the custom headers from a $params array.
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
array $readUsers
Additional users (account:user) with read permissions on public containers.
array $secureReadUsers
Additional users (account:user) with read permissions on private containers.
doCleanInternal( $fullCont, $dir, array $params)
ProcessCacheLRU $containerStatCache
Container stat cache.
getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
string $swiftKey
Secret key for user.
doDirectoryExists( $fullCont, $dir, array $params)
objectListing( $fullCont, $type, $limit, $after=null, $prefix=null, $delim=null)
Get a list of objects under a container.
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doExecuteOpHandlesInternal(array $fileOpHandles)
doDeleteInternal(array $params)
doDescribeInternal(array $params)
getContainerStat( $container, $bypassCache=false)
Get a Swift container stat array, possibly from process cache.
array $httpOp
List of Requests for MultiHttpClient.
__construct(SwiftFileBackend $backend, Closure $callback, array $httpOp)
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
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
this hook is for auditing only $req
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 you ll probably need to make sure the header is varied on $request
> 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. '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) name
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
this hook is for auditing only or null if authentication failed before getting that far $username
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
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
processing should stop and the error should be shown to the user * false
returning false will NOT prevent logging $e
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))
if(!is_readable( $file)) $ext