20use Shellbox\Command\BoxedCommand;
21use Wikimedia\AtEase\AtEase;
145 protected $fileFactory = [ UnregisteredLocalFile::class,
'newFromTitle' ];
182 || !array_key_exists(
'name', $info )
183 || !array_key_exists(
'backend', $info )
185 throw new InvalidArgumentException( __CLASS__ .
186 " requires an array of options having both 'name' and 'backend' keys.\n" );
190 $this->name = $info[
'name'];
192 $this->backend = $info[
'backend'];
195 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info[
'backend'] );
199 $optionalSettings = [
200 'descBaseUrl',
'scriptDirUrl',
'articleUrl',
'fetchDescription',
201 'thumbScriptUrl',
'pathDisclosureProtection',
'descriptionCacheExpiry',
202 'favicon',
'thumbProxyUrl',
'thumbProxySecret',
'disableLocalTransform'
204 foreach ( $optionalSettings as $var ) {
205 if ( isset( $info[$var] ) ) {
206 $this->$var = $info[$var];
212 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE );
213 $this->initialCapital = $info[
'initialCapital'] ?? $localCapitalLinks;
214 if ( $localCapitalLinks && !$this->initialCapital ) {
222 throw new InvalidArgumentException(
223 'File repos with initial capital false are not allowed on wikis where the File ' .
224 'namespace has initial capital true' );
227 $this->url = $info[
'url'] ??
false;
228 $defaultThumbUrl = $this->url ? $this->url .
'/thumb' :
false;
229 $this->thumbUrl = $info[
'thumbUrl'] ?? $defaultThumbUrl;
230 $this->hashLevels = $info[
'hashLevels'] ?? 2;
232 $this->transformVia404 = !empty( $info[
'transformVia404'] );
233 $this->abbrvThreshold = $info[
'abbrvThreshold'] ?? 255;
234 $this->isPrivate = !empty( $info[
'isPrivate'] );
236 $this->zones = $info[
'zones'] ?? [];
237 foreach ( [
'public',
'thumb',
'transcoded',
'temp',
'deleted' ] as $zone ) {
238 if ( !isset( $this->zones[$zone][
'container'] ) ) {
239 $this->zones[$zone][
'container'] =
"{$this->name}-{$zone}";
241 if ( !isset( $this->zones[$zone][
'directory'] ) ) {
242 $this->zones[$zone][
'directory'] =
'';
244 if ( !isset( $this->zones[$zone][
'urlsByExt'] ) ) {
245 $this->zones[$zone][
'urlsByExt'] = [];
251 $this->wanCache = $info[
'wanCache'] ?? WANObjectCache::newEmpty();
270 return $this->backend->getReadOnlyReason();
279 foreach ( (array)$doZones as $zone ) {
281 if ( $root ===
null ) {
282 throw new RuntimeException(
"No '$zone' zone defined in the {$this->name} repo." );
294 return str_starts_with(
$url,
'mwrepo://' );
306 $path =
'mwrepo://' . $this->name;
307 if ( $suffix !==
false ) {
308 $path .=
'/' . rawurlencode( $suffix );
322 if ( in_array( $zone, [
'public',
'thumb',
'transcoded' ] ) ) {
324 if ( $ext !==
null && isset( $this->zones[$zone][
'urlsByExt'][$ext] ) ) {
327 return $this->zones[$zone][
'urlsByExt'][$ext];
328 } elseif ( isset( $this->zones[$zone][
'url'] ) ) {
330 return $this->zones[$zone][
'url'];
340 return $this->thumbUrl;
342 return "{$this->url}/transcoded";
352 return (
bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
364 if ( !str_starts_with(
$url,
'mwrepo://' ) ) {
365 throw new InvalidArgumentException( __METHOD__ .
': unknown protocol' );
367 $bits = explode(
'/', substr(
$url, 9 ), 3 );
368 if ( count( $bits ) != 3 ) {
369 throw new InvalidArgumentException( __METHOD__ .
": invalid mwrepo URL: $url" );
371 [ $repo, $zone, $rel ] = $bits;
372 if ( $repo !== $this->name ) {
373 throw new InvalidArgumentException( __METHOD__ .
": fetching from a foreign repo is not supported" );
375 $base = $this->getZonePath( $zone );
377 throw new InvalidArgumentException( __METHOD__ .
": invalid zone: $zone" );
380 return $base .
'/' . rawurldecode( $rel );
390 if ( !isset( $this->zones[$zone] ) ) {
391 return [
null, null ];
394 return [ $this->zones[$zone][
'container'], $this->zones[$zone][
'directory'] ];
404 [ $container, $base ] = $this->getZoneLocation( $zone );
405 if ( $container ===
null || $base ===
null ) {
408 $backendName = $this->backend->getName();
413 return "mwstore://$backendName/{$container}{$base}";
427 public function newFile( $title, $time =
false ) {
428 $title = File::normalizeTitle( $title );
433 if ( $this->oldFileFactory ) {
434 return call_user_func( $this->oldFileFactory, $title, $this, $time );
439 return call_user_func( $this->fileFactory, $title, $this );
462 public function findFile( $title, $options = [] ) {
463 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
464 throw new InvalidArgumentException(
465 __METHOD__ .
' called with the `private` option set to something ' .
466 'other than an Authority object'
470 $title = File::normalizeTitle( $title );
474 if ( isset( $options[
'bypassCache'] ) ) {
475 $options[
'latest'] = $options[
'bypassCache'];
477 $time = $options[
'time'] ??
false;
478 $flags = !empty( $options[
'latest'] ) ? IDBAccessObject::READ_LATEST : 0;
479 # First try the current version of the file to see if it precedes the timestamp
480 $img = $this->newFile( $title );
484 $img->load( $flags );
485 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
488 # Now try an old version of the file
489 if ( $time !==
false ) {
490 $img = $this->newFile( $title, $time );
492 $img->load( $flags );
493 if ( $img->exists() ) {
494 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
498 !empty( $options[
'private'] ) &&
499 $img->userCan( File::DELETED_FILE, $options[
'private'] )
508 if ( !empty( $options[
'ignoreRedirect'] ) ) {
511 $redir = $this->checkRedirect( $title );
512 if ( $redir && $title->getNamespace() ===
NS_FILE ) {
513 $img = $this->newFile( $redir );
517 $img->load( $flags );
518 if ( $img->exists() ) {
519 $img->redirectedFrom( $title->getDBkey() );
547 foreach ( $items as $item ) {
548 if ( is_array( $item ) ) {
549 $title = $item[
'title'];
551 unset( $options[
'title'] );
554 !empty( $options[
'private'] ) &&
555 !( $options[
'private'] instanceof
Authority )
557 $options[
'private'] = RequestContext::getMain()->getAuthority();
563 $file = $this->findFile( $title, $options );
565 $searchName = File::normalizeTitle( $title )->getDBkey();
566 if ( $flags & self::NAME_AND_TIME_ONLY ) {
567 $result[$searchName] = [
568 'title' => $file->getTitle()->getDBkey(),
569 'timestamp' => $file->getTimestamp()
572 $result[$searchName] = $file;
591 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
592 throw new InvalidArgumentException(
593 __METHOD__ .
' called with the `private` option set to something ' .
594 'other than an Authority object'
598 $time = $options[
'time'] ??
false;
599 # First try to find a matching current version of a file...
600 if ( !$this->fileFactoryKey ) {
603 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
604 if ( $img && $img->exists() ) {
607 # Now try to find a matching old version of a file...
608 if ( $time !==
false && $this->oldFileFactoryKey ) {
609 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
610 if ( $img && $img->exists() ) {
611 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
615 !empty( $options[
'private'] ) &&
616 $img->userCan( File::DELETED_FILE, $options[
'private'] )
647 foreach ( $hashes as $hash ) {
648 $files = $this->findBySha1( $hash );
649 if ( count( $files ) ) {
650 $result[$hash] = $files;
675 return $this->thumbScriptUrl;
684 return $this->thumbProxyUrl;
693 return $this->thumbProxySecret;
702 return $this->transformVia404;
712 return !$this->disableLocalTransform;
723 $this->initialCapital !=
724 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE )
726 $name = $title->getDBkey();
727 if ( $this->initialCapital ) {
728 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
731 $name = $title->getDBkey();
743 return $this->getZonePath(
'public' );
754 return self::getHashPathForLevel( $name, $this->hashLevels );
765 $parts = explode(
'!', $suffix, 2 );
766 $name = $parts[1] ?? $suffix;
767 return self::getHashPathForLevel( $name, $this->hashLevels );
776 if ( $levels == 0 ) {
779 $hash = md5( $name );
781 for ( $i = 1; $i <= $levels; $i++ ) {
782 $path .= substr( $hash, 0, $i ) .
'/';
795 return $this->hashLevels;
814 public function makeUrl( $query =
'', $entry =
'index' ) {
815 if ( isset( $this->scriptDirUrl ) ) {
816 return wfAppendQuery(
"{$this->scriptDirUrl}/{$entry}.php", $query );
836 if ( $this->descBaseUrl !==
null ) {
837 # "http://example.com/wiki/File:"
838 return $this->descBaseUrl . $encName;
840 if ( $this->articleUrl !==
null ) {
841 # "http://example.com/wiki/$1"
842 # We use "Image:" as the canonical namespace for
843 # compatibility across all MediaWiki versions.
844 return str_replace(
'$1',
845 "Image:$encName", $this->articleUrl );
847 if ( $this->scriptDirUrl !==
null ) {
848 # "http://example.com/w"
849 # We use "Image:" as the canonical namespace for
850 # compatibility across all MediaWiki versions,
851 # and just sort of hope index.php is right. ;)
852 return $this->makeUrl(
"title=Image:$encName" );
869 $query =
'action=render';
870 if ( $lang !==
null ) {
871 $query .=
'&uselang=' . urlencode( $lang );
873 if ( isset( $this->scriptDirUrl ) ) {
874 return $this->makeUrl(
879 $descUrl = $this->getDescriptionUrl( $name );
894 if ( isset( $this->scriptDirUrl ) ) {
897 return $this->makeUrl(
'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
920 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
921 $this->assertWritableRepo();
923 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
924 if ( $status->successCount == 0 ) {
925 $status->setOK(
false );
945 $this->assertWritableRepo();
947 if ( $flags & self::DELETE_SOURCE ) {
948 throw new InvalidArgumentException(
"DELETE_SOURCE not supported in " . __METHOD__ );
951 $status = $this->newGood();
952 $backend = $this->backend;
956 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
957 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
959 .
"( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
962 if ( $src instanceof
FSFile ) {
965 $src = $this->resolveToStoragePathIfVirtual( $src );
966 $op = FileBackend::isStoragePath( $src ) ?
'copy' :
'store';
969 $root = $this->getZonePath( $dstZone );
971 throw new RuntimeException(
"Invalid zone: $dstZone" );
973 if ( !$this->validateFilename( $dstRel ) ) {
974 throw new RuntimeException(
'Validation error in $dstRel' );
976 $dstPath =
"$root/$dstRel";
977 $dstDir = dirname( $dstPath );
979 if ( !$this->initDirectory( $dstDir )->isOK() ) {
980 return $this->newFatal(
'directorycreateerror', $dstDir );
988 'overwrite' => (bool)( $flags & self::OVERWRITE ),
989 'overwriteSame' => (bool)( $flags & self::OVERWRITE_SAME ),
994 $opts = [
'force' => true ];
995 if ( $flags & self::SKIP_LOCKING ) {
996 $opts[
'nonLocking'] =
true;
999 return $status->merge( $backend->doOperations( $operations, $opts ) );
1013 $this->assertWritableRepo();
1015 $status = $this->newGood();
1018 foreach ( $files as
$path ) {
1019 if ( is_array(
$path ) ) {
1021 [ $zone, $rel ] =
$path;
1022 $path = $this->getZonePath( $zone ) .
"/$rel";
1025 $path = $this->resolveToStoragePathIfVirtual(
$path );
1027 $operations[] = [
'op' =>
'delete',
'src' =>
$path ];
1030 $opts = [
'force' => true ];
1031 if ( $flags & self::SKIP_LOCKING ) {
1032 $opts[
'nonLocking'] =
true;
1035 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1056 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1074 $status = $this->newGood();
1076 foreach ( $triples as $triple ) {
1077 [ $src, $dst ] = $triple;
1078 if ( $src instanceof
FSFile ) {
1081 $src = $this->resolveToStoragePathIfVirtual( $src );
1082 $op = FileBackend::isStoragePath( $src ) ?
'copy' :
'store';
1084 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1086 if ( !isset( $triple[2] ) ) {
1088 } elseif ( is_string( $triple[2] ) ) {
1090 $headers = [
'Content-Disposition' => $triple[2] ];
1091 } elseif ( is_array( $triple[2] ) && isset( $triple[2][
'headers'] ) ) {
1092 $headers = $triple[2][
'headers'];
1101 'headers' => $headers
1103 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1106 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1118 return $this->quickPurgeBatch( [
$path ] );
1129 return $this->newGood()->merge(
1130 $this->backend->clean(
1131 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1145 $status = $this->newGood();
1147 foreach ( $paths as
$path ) {
1150 'src' => $this->resolveToStoragePathIfVirtual(
$path ),
1151 'ignoreMissingSource' => true
1154 $status->merge( $this->backend->doQuickOperations( $operations ) );
1170 $this->assertWritableRepo();
1172 $date = MWTimestamp::getInstance()->format(
'YmdHis' );
1173 $hashPath = $this->getHashPath( $originalName );
1174 $dstUrlRel = $hashPath . $date .
'!' . rawurlencode( $originalName );
1175 $virtualUrl = $this->getVirtualUrl(
'temp' ) .
'/' . $dstUrlRel;
1177 $result = $this->quickImport( $srcPath, $virtualUrl );
1178 $result->value = $virtualUrl;
1190 $this->assertWritableRepo();
1192 $temp = $this->getVirtualUrl(
'temp' );
1193 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1194 wfDebug( __METHOD__ .
": Invalid temp virtual URL" );
1199 return $this->quickPurge( $virtualUrl )->isOK();
1211 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1212 $this->assertWritableRepo();
1214 $status = $this->newGood();
1217 foreach ( $srcPaths as $srcPath ) {
1219 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1224 $params = [
'srcs' => $sources,
'dst' => $dstPath ];
1225 $status->merge( $this->backend->concatenate(
$params ) );
1226 if ( !$status->isOK() ) {
1231 if ( $flags & self::DELETE_SOURCE ) {
1232 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1236 $status->setResult(
true );
1265 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1267 $this->assertWritableRepo();
1269 $status = $this->publishBatch(
1270 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1271 if ( $status->successCount == 0 ) {
1272 $status->setOK(
false );
1274 $status->value = $status->value[0] ??
false;
1291 $this->assertWritableRepo();
1293 $backend = $this->backend;
1295 $this->initZones(
'public' );
1297 $status = $this->newGood( [] );
1300 $sourceFSFilesToDelete = [];
1302 foreach ( $ntuples as $ntuple ) {
1303 [ $src, $dstRel, $archiveRel ] = $ntuple;
1304 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1306 $options = $ntuple[3] ?? [];
1308 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1309 if ( !$this->validateFilename( $dstRel ) ) {
1310 throw new RuntimeException(
'Validation error in $dstRel' );
1312 if ( !$this->validateFilename( $archiveRel ) ) {
1313 throw new RuntimeException(
'Validation error in $archiveRel' );
1316 $publicRoot = $this->getZonePath(
'public' );
1317 $dstPath =
"$publicRoot/$dstRel";
1318 $archivePath =
"$publicRoot/$archiveRel";
1320 $dstDir = dirname( $dstPath );
1321 $archiveDir = dirname( $archivePath );
1323 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1324 return $this->newFatal(
'directorycreateerror', $dstDir );
1326 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1327 return $this->newFatal(
'directorycreateerror', $archiveDir );
1331 $headers = $options[
'headers'] ?? [];
1342 'dst' => $archivePath,
1343 'ignoreMissingSource' => true
1347 if ( FileBackend::isStoragePath( $srcPath ) ) {
1349 'op' => ( $flags & self::DELETE_SOURCE ) ?
'move' :
'copy',
1352 'overwrite' =>
true,
1353 'headers' => $headers
1360 'overwrite' =>
true,
1361 'headers' => $headers
1363 if ( $flags & self::DELETE_SOURCE ) {
1364 $sourceFSFilesToDelete[] = $srcPath;
1370 $status->merge( $backend->doOperations( $operations ) );
1372 foreach ( $ntuples as $i => $ntuple ) {
1373 [ , , $archiveRel ] = $ntuple;
1374 $archivePath = $this->getZonePath(
'public' ) .
"/$archiveRel";
1375 if ( $this->fileExists( $archivePath ) ) {
1376 $status->value[$i] =
'archived';
1378 $status->value[$i] =
'new';
1382 foreach ( $sourceFSFilesToDelete as $file ) {
1383 AtEase::suppressWarnings();
1385 AtEase::restoreWarnings();
1399 $path = $this->resolveToStoragePathIfVirtual( $dir );
1400 [ , $container, ] = FileBackend::splitStoragePath(
$path );
1403 if ( $this->isPrivate
1404 || $container === $this->zones[
'deleted'][
'container']
1405 || $container === $this->zones[
'temp'][
'container']
1407 # Take all available measures to prevent web accessibility of new deleted
1408 # directories, in case the user has not configured offline storage
1412 return $this->newGood()->merge( $this->backend->prepare(
$params ) );
1422 $this->assertWritableRepo();
1424 return $this->newGood()->merge(
1425 $this->backend->clean(
1426 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1438 $result = $this->fileExistsBatch( [ $file ] );
1451 $paths = array_map( [ $this,
'resolveToStoragePathIfVirtual' ], $files );
1452 $this->backend->preloadFileStat( [
'srcs' => $paths ] );
1455 foreach ( $paths as $key =>
$path ) {
1456 $result[$key] = $this->backend->fileExists( [
'src' =>
$path ] );
1472 public function delete( $srcRel, $archiveRel ) {
1473 $this->assertWritableRepo();
1475 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1495 $this->assertWritableRepo();
1498 $this->initZones( [
'public',
'deleted' ] );
1500 $status = $this->newGood();
1502 $backend = $this->backend;
1505 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1506 if ( !$this->validateFilename( $srcRel ) ) {
1507 throw new RuntimeException( __METHOD__ .
':Validation error in $srcRel' );
1508 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1509 throw new RuntimeException( __METHOD__ .
':Validation error in $archiveRel' );
1512 $publicRoot = $this->getZonePath(
'public' );
1513 $srcPath =
"{$publicRoot}/$srcRel";
1515 $deletedRoot = $this->getZonePath(
'deleted' );
1516 $archivePath =
"{$deletedRoot}/{$archiveRel}";
1517 $archiveDir = dirname( $archivePath );
1520 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1521 return $this->newFatal(
'directorycreateerror', $archiveDir );
1527 'dst' => $archivePath,
1530 'overwriteSame' =>
true
1537 $opts = [
'force' => true ];
1538 return $status->merge( $backend->doOperations( $operations, $opts ) );
1548 $this->assertWritableRepo();
1559 if ( strlen( $key ) < 31 ) {
1560 throw new InvalidArgumentException(
"Invalid storage key '$key'." );
1563 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1564 $path .= $key[$i] .
'/';
1578 if ( self::isVirtualUrl(
$path ) ) {
1579 return $this->resolveVirtualUrl(
$path );
1593 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1595 return $this->backend->getLocalCopy( [
'src' =>
$path ] );
1607 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1609 return $this->backend->getLocalReference( [
'src' =>
$path ] );
1624 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1626 return $this->backend->addShellboxInputFile( $command, $boxedName, [
'src' =>
$path ] );
1637 $fsFile = $this->getLocalReference( $virtualUrl );
1638 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1640 $props = $mwProps->getPropsFromPath( $fsFile->getPath(),
true );
1642 $props = $mwProps->newPlaceholderProps();
1655 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1657 return $this->backend->getFileTimestamp( [
'src' =>
$path ] );
1667 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1669 return $this->backend->getFileSize( [
'src' =>
$path ] );
1679 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1681 return $this->backend->getFileSha1Base36( [
'src' =>
$path ] );
1694 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1695 $params = [
'src' =>
$path,
'headers' => $headers,
'options' => $optHeaders ];
1698 ob_start(
null, 1_048_576 );
1699 ob_implicit_flush(
true );
1701 $status = $this->newGood()->merge( $this->backend->streamFile(
$params ) );
1705 if ( ob_get_status() ) {
1721 $this->enumFilesInStorage( $callback );
1732 $publicRoot = $this->getZonePath(
'public' );
1733 $numDirs = 1 << ( $this->hashLevels * 4 );
1736 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1737 $hexString = sprintf(
"%0{$this->hashLevels}x", $flatIndex );
1738 $path = $publicRoot;
1739 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1740 $path .=
'/' . substr( $hexString, 0, $hexPos + 1 );
1742 $iterator = $this->backend->getFileList( [
'dir' =>
$path ] );
1743 if ( $iterator ===
null ) {
1744 throw new RuntimeException( __METHOD__ .
': could not get file listing for ' .
$path );
1746 foreach ( $iterator as $name ) {
1748 call_user_func( $callback,
"{$path}/{$name}" );
1760 if ( strval( $filename ) ==
'' ) {
1764 return FileBackend::isPathTraversalFree( $filename );
1772 private function getErrorCleanupFunction() {
1773 switch ( $this->pathDisclosureProtection ) {
1776 $callback = [ $this,
'passThrough' ];
1779 $callback = [ $this,
'paranoidClean' ];
1812 $status = Status::newFatal( $message, ...$parameters );
1813 $status->cleanCallback = $this->getErrorCleanupFunction();
1825 $status = Status::newGood( $value );
1826 $status->cleanCallback = $this->getErrorCleanupFunction();
1859 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1861 if ( $this->isLocal() ) {
1866 return wfMessageFallback(
'shared-repo-name-' . $this->name,
'shared-repo' )->text();
1877 if ( strlen( $name ) > $this->abbrvThreshold ) {
1878 $ext = FileBackend::extensionFromPath( $name );
1879 $name = ( $ext ==
'' ) ?
'thumbnail' :
"thumbnail.$ext";
1891 return $this->getName() ==
'local';
1921 return $this->wanCache->makeKey(
1922 'filerepo-' . $kClassSuffix,
1938 'name' =>
"{$this->name}-temp",
1939 'backend' => $this->backend,
1944 'container' => $this->zones[
'temp'][
'container'],
1945 'directory' => $this->zones[
'temp'][
'directory']
1948 'container' => $this->zones[
'temp'][
'container'],
1949 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1951 : $this->zones[
'temp'][
'directory'] .
'/thumb'
1954 'container' => $this->zones[
'temp'][
'container'],
1955 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1957 : $this->zones[
'temp'][
'directory'] .
'/transcoded'
1960 'hashLevels' => $this->hashLevels,
1992 'name' => $this->getName(),
1993 'displayname' => $this->getDisplayName(),
1994 'rootUrl' => $this->getZoneUrl(
'public' ),
1995 'local' => $this->isLocal(),
1998 $optionalSettings = [
2006 'descriptionCacheExpiry',
2008 foreach ( $optionalSettings as $k ) {
2009 if ( isset( $this->$k ) ) {
2010 $ret[$k] = $this->$k;
2013 if ( isset( $this->favicon ) ) {
2015 $ret[
'favicon'] = MediaWikiServices::getInstance()->getUrlUtils()
2016 ->expand( $this->favicon );
2027 return $this->hasSha1Storage;
2035 return $this->supportsSha1URLs;
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
array $params
The job parameters.
Base class for file repositories.
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
int $hashLevels
The number of directory levels for hash-based division of files.
getTempRepo()
Get a temporary private FileRepo associated with this repo.
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table.
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
nameForThumb( $name)
Get the portion of the file that contains the origin file name.
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
findFiles(array $items, $flags=0)
Find many files at once.
newFatal( $message,... $parameters)
Create a new fatal error.
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
getZoneLocation( $zone)
The storage container and base path of a zone.
fileExists( $file)
Checks existence of a file.
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
assertWritableRepo()
Throw an exception if this repo is read-only by design.
getRootDirectory()
Get the public zone root storage directory of the repository.
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
newGood( $value=null)
Create a new good result.
getUploadStash(?UserIdentity $user=null)
Get an UploadStash associated with this repo.
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
getHashLevels()
Get the number of hash directory levels.
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
getName()
Get the name of this repository, as specified by $info['name]' to the constructor.
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
findFile( $title, $options=[])
Find an instance of the named file created at the specified time Returns false if the file does not e...
callable false $oldFileFactoryKey
Override these in the base class.
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
quickPurge( $path)
Purge a file from the repo.
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
passThrough( $param)
Path disclosure protection function.
static getHashPathForLevel( $name, $levels)
array $zones
Map of zones to config.
callable false $fileFactoryKey
Override these in the base class.
checkRedirect( $title)
Checks if there is a redirect named as $title.
getDisplayName()
Get the human-readable name of the repo.
getSharedCacheKey( $kClassSuffix,... $components)
Get a global, repository-qualified, WAN cache key.
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
bool $disableLocalTransform
Disable local image scaling.
storeBatch(array $triplets, $flags=0)
Store a batch of files.
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
canTransformLocally()
Returns true if the repository can transform files locally.
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
publish( $src, $dstRel, $archiveRel, $flags=0, array $options=[])
Copy or move a file either from a storage path, virtual URL, or file system path, into this repositor...
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
makeUrl( $query='', $entry='index')
Make an url to this repo.
findBySha1s(array $hashes)
Get an array of arrays or iterators of file objects for files that have the given SHA-1 content hashe...
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
null string $favicon
The URL to a favicon (optional, may be a server-local path URL).
fileExistsBatch(array $files)
Checks existence of an array of files.
int $descriptionCacheExpiry
paranoidClean( $param)
Path disclosure protection function.
initZones( $doZones=[])
Ensure that a single zone or list of zones is defined for usage.
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
isLocal()
Returns true if this the local file repository.
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
getDescriptionUrl( $name)
Get the URL of an image description page.
cleanDir( $dir)
Deletes a directory if empty.
addShellboxInputFile(BoxedCommand $command, string $boxedName, string $virtualUrl)
Add a file to a Shellbox command as an input file.
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
getNameFromTitle( $title)
Get the name of a file from its title.
invalidateImageRedirect( $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
getThumbProxySecret()
Get the secret key for the proxied thumb service.
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
string false $url
Public zone URL.
callable $fileFactory
Override these in the base class.
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
bool $isPrivate
Whether all zones should be private (e.g.
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
string $descBaseUrl
URL of image description pages, e.g.
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
newFile( $title, $time=false)
Create a new File object from the local repository.
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
quickCleanDir( $dir)
Deletes a directory if empty.
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
validateFilename( $filename)
Determine if a relative path is valid, i.e.
findFileFromKey( $sha1, $options=[])
Find an instance of the file with this key, created at the specified time Returns false if the file d...
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
string $thumbScriptUrl
URL of thumb.php.
backendSupportsUnicodePaths()
string false $thumbUrl
The base thumbnail URL.
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
getHashPath( $name)
Get a relative path including trailing slash, e.g.
callable false $oldFileFactory
Override these in the base class.
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
string $articleUrl
Equivalent to $wgArticlePath, e.g.
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
findBySha1( $hash)
Get an array or iterator of file objects for files that have a given SHA-1 content hash.
__construct(?array $info=null)
getBackend()
Get the file backend instance.
getInfo()
Return information about the repository.
getThumbScriptUrl()
Get the URL of thumb.php.
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
MimeMagic helper wrapper.
Group all the pieces relevant to the context of a request into one instance.
A class containing constants representing the names of configuration variables.
FileRepo for temporary files created by FileRepo::getTempRepo()
UploadStash is intended to accomplish a few things:
Interface for objects (potentially) representing an editable wiki page.