20use Wikimedia\AtEase\AtEase;
140 protected $fileFactory = [ UnregisteredLocalFile::class,
'newFromTitle' ];
177 || !array_key_exists(
'name', $info )
178 || !array_key_exists(
'backend', $info )
180 throw new InvalidArgumentException( __CLASS__ .
181 " requires an array of options having both 'name' and 'backend' keys.\n" );
185 $this->name = $info[
'name'];
187 $this->backend = $info[
'backend'];
190 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info[
'backend'] );
194 $optionalSettings = [
195 'descBaseUrl',
'scriptDirUrl',
'articleUrl',
'fetchDescription',
196 'thumbScriptUrl',
'pathDisclosureProtection',
'descriptionCacheExpiry',
197 'favicon',
'thumbProxyUrl',
'thumbProxySecret',
'disableLocalTransform'
199 foreach ( $optionalSettings as $var ) {
200 if ( isset( $info[$var] ) ) {
201 $this->$var = $info[$var];
207 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE );
208 $this->initialCapital = $info[
'initialCapital'] ?? $localCapitalLinks;
209 if ( $localCapitalLinks && !$this->initialCapital ) {
217 throw new InvalidArgumentException(
218 'File repos with initial capital false are not allowed on wikis where the File ' .
219 'namespace has initial capital true' );
222 $this->url = $info[
'url'] ??
false;
223 $defaultThumbUrl = $this->url ? $this->url .
'/thumb' :
false;
224 $this->thumbUrl = $info[
'thumbUrl'] ?? $defaultThumbUrl;
225 $this->hashLevels = $info[
'hashLevels'] ?? 2;
227 $this->transformVia404 = !empty( $info[
'transformVia404'] );
228 $this->abbrvThreshold = $info[
'abbrvThreshold'] ?? 255;
229 $this->isPrivate = !empty( $info[
'isPrivate'] );
231 $this->zones = $info[
'zones'] ?? [];
232 foreach ( [
'public',
'thumb',
'transcoded',
'temp',
'deleted' ] as $zone ) {
233 if ( !isset( $this->zones[$zone][
'container'] ) ) {
234 $this->zones[$zone][
'container'] =
"{$this->name}-{$zone}";
236 if ( !isset( $this->zones[$zone][
'directory'] ) ) {
237 $this->zones[$zone][
'directory'] =
'';
239 if ( !isset( $this->zones[$zone][
'urlsByExt'] ) ) {
240 $this->zones[$zone][
'urlsByExt'] = [];
246 $this->wanCache = $info[
'wanCache'] ?? WANObjectCache::newEmpty();
265 return $this->backend->getReadOnlyReason();
274 foreach ( (array)$doZones as $zone ) {
276 if ( $root ===
null ) {
277 throw new RuntimeException(
"No '$zone' zone defined in the {$this->name} repo." );
289 return str_starts_with(
$url,
'mwrepo://' );
301 $path =
'mwrepo://' . $this->name;
302 if ( $suffix !==
false ) {
303 $path .=
'/' . rawurlencode( $suffix );
317 if ( in_array( $zone, [
'public',
'thumb',
'transcoded' ] ) ) {
319 if ( $ext !==
null && isset( $this->zones[$zone][
'urlsByExt'][$ext] ) ) {
322 return $this->zones[$zone][
'urlsByExt'][$ext];
323 } elseif ( isset( $this->zones[$zone][
'url'] ) ) {
325 return $this->zones[$zone][
'url'];
335 return $this->thumbUrl;
337 return "{$this->url}/transcoded";
347 return (
bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
359 if ( !str_starts_with(
$url,
'mwrepo://' ) ) {
360 throw new InvalidArgumentException( __METHOD__ .
': unknown protocol' );
362 $bits = explode(
'/', substr(
$url, 9 ), 3 );
363 if ( count( $bits ) != 3 ) {
364 throw new InvalidArgumentException( __METHOD__ .
": invalid mwrepo URL: $url" );
366 [ $repo, $zone, $rel ] = $bits;
367 if ( $repo !== $this->name ) {
368 throw new InvalidArgumentException( __METHOD__ .
": fetching from a foreign repo is not supported" );
370 $base = $this->getZonePath( $zone );
372 throw new InvalidArgumentException( __METHOD__ .
": invalid zone: $zone" );
375 return $base .
'/' . rawurldecode( $rel );
385 if ( !isset( $this->zones[$zone] ) ) {
386 return [
null, null ];
389 return [ $this->zones[$zone][
'container'], $this->zones[$zone][
'directory'] ];
399 [ $container, $base ] = $this->getZoneLocation( $zone );
400 if ( $container ===
null || $base ===
null ) {
403 $backendName = $this->backend->getName();
408 return "mwstore://$backendName/{$container}{$base}";
422 public function newFile( $title, $time =
false ) {
423 $title = File::normalizeTitle( $title );
428 if ( $this->oldFileFactory ) {
429 return call_user_func( $this->oldFileFactory, $title, $this, $time );
434 return call_user_func( $this->fileFactory, $title, $this );
457 public function findFile( $title, $options = [] ) {
458 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
459 throw new InvalidArgumentException(
460 __METHOD__ .
' called with the `private` option set to something ' .
461 'other than an Authority object'
465 $title = File::normalizeTitle( $title );
469 if ( isset( $options[
'bypassCache'] ) ) {
470 $options[
'latest'] = $options[
'bypassCache'];
472 $time = $options[
'time'] ??
false;
473 $flags = !empty( $options[
'latest'] ) ? IDBAccessObject::READ_LATEST : 0;
474 # First try the current version of the file to see if it precedes the timestamp
475 $img = $this->newFile( $title );
479 $img->load( $flags );
480 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
483 # Now try an old version of the file
484 if ( $time !==
false ) {
485 $img = $this->newFile( $title, $time );
487 $img->load( $flags );
488 if ( $img->exists() ) {
489 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
493 !empty( $options[
'private'] ) &&
494 $img->userCan( File::DELETED_FILE, $options[
'private'] )
503 if ( !empty( $options[
'ignoreRedirect'] ) ) {
506 $redir = $this->checkRedirect( $title );
507 if ( $redir && $title->getNamespace() ===
NS_FILE ) {
508 $img = $this->newFile( $redir );
512 $img->load( $flags );
513 if ( $img->exists() ) {
514 $img->redirectedFrom( $title->getDBkey() );
542 foreach ( $items as $item ) {
543 if ( is_array( $item ) ) {
544 $title = $item[
'title'];
546 unset( $options[
'title'] );
549 !empty( $options[
'private'] ) &&
550 !( $options[
'private'] instanceof
Authority )
552 $options[
'private'] = RequestContext::getMain()->getAuthority();
558 $file = $this->findFile( $title, $options );
560 $searchName = File::normalizeTitle( $title )->getDBkey();
561 if ( $flags & self::NAME_AND_TIME_ONLY ) {
562 $result[$searchName] = [
563 'title' => $file->getTitle()->getDBkey(),
564 'timestamp' => $file->getTimestamp()
567 $result[$searchName] = $file;
586 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
587 throw new InvalidArgumentException(
588 __METHOD__ .
' called with the `private` option set to something ' .
589 'other than an Authority object'
593 $time = $options[
'time'] ??
false;
594 # First try to find a matching current version of a file...
595 if ( !$this->fileFactoryKey ) {
598 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
599 if ( $img && $img->exists() ) {
602 # Now try to find a matching old version of a file...
603 if ( $time !==
false && $this->oldFileFactoryKey ) {
604 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
605 if ( $img && $img->exists() ) {
606 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
610 !empty( $options[
'private'] ) &&
611 $img->userCan( File::DELETED_FILE, $options[
'private'] )
642 foreach ( $hashes as $hash ) {
643 $files = $this->findBySha1( $hash );
644 if ( count( $files ) ) {
645 $result[$hash] = $files;
670 return $this->thumbScriptUrl;
679 return $this->thumbProxyUrl;
688 return $this->thumbProxySecret;
697 return $this->transformVia404;
707 return !$this->disableLocalTransform;
718 $this->initialCapital !=
719 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE )
721 $name = $title->getDBkey();
722 if ( $this->initialCapital ) {
723 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
726 $name = $title->getDBkey();
738 return $this->getZonePath(
'public' );
749 return self::getHashPathForLevel( $name, $this->hashLevels );
760 $parts = explode(
'!', $suffix, 2 );
761 $name = $parts[1] ?? $suffix;
762 return self::getHashPathForLevel( $name, $this->hashLevels );
771 if ( $levels == 0 ) {
774 $hash = md5( $name );
776 for ( $i = 1; $i <= $levels; $i++ ) {
777 $path .= substr( $hash, 0, $i ) .
'/';
790 return $this->hashLevels;
809 public function makeUrl( $query =
'', $entry =
'index' ) {
810 if ( isset( $this->scriptDirUrl ) ) {
811 return wfAppendQuery(
"{$this->scriptDirUrl}/{$entry}.php", $query );
831 if ( $this->descBaseUrl !==
null ) {
832 # "http://example.com/wiki/File:"
833 return $this->descBaseUrl . $encName;
835 if ( $this->articleUrl !==
null ) {
836 # "http://example.com/wiki/$1"
837 # We use "Image:" as the canonical namespace for
838 # compatibility across all MediaWiki versions.
839 return str_replace(
'$1',
840 "Image:$encName", $this->articleUrl );
842 if ( $this->scriptDirUrl !==
null ) {
843 # "http://example.com/w"
844 # We use "Image:" as the canonical namespace for
845 # compatibility across all MediaWiki versions,
846 # and just sort of hope index.php is right. ;)
847 return $this->makeUrl(
"title=Image:$encName" );
864 $query =
'action=render';
865 if ( $lang !==
null ) {
866 $query .=
'&uselang=' . urlencode( $lang );
868 if ( isset( $this->scriptDirUrl ) ) {
869 return $this->makeUrl(
874 $descUrl = $this->getDescriptionUrl( $name );
889 if ( isset( $this->scriptDirUrl ) ) {
892 return $this->makeUrl(
'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
915 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
916 $this->assertWritableRepo();
918 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
919 if ( $status->successCount == 0 ) {
920 $status->setOK(
false );
940 $this->assertWritableRepo();
942 if ( $flags & self::DELETE_SOURCE ) {
943 throw new InvalidArgumentException(
"DELETE_SOURCE not supported in " . __METHOD__ );
946 $status = $this->newGood();
947 $backend = $this->backend;
951 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
952 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
954 .
"( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
957 if ( $src instanceof
FSFile ) {
960 $src = $this->resolveToStoragePathIfVirtual( $src );
961 $op = FileBackend::isStoragePath( $src ) ?
'copy' :
'store';
964 $root = $this->getZonePath( $dstZone );
966 throw new RuntimeException(
"Invalid zone: $dstZone" );
968 if ( !$this->validateFilename( $dstRel ) ) {
969 throw new RuntimeException(
'Validation error in $dstRel' );
971 $dstPath =
"$root/$dstRel";
972 $dstDir = dirname( $dstPath );
974 if ( !$this->initDirectory( $dstDir )->isOK() ) {
975 return $this->newFatal(
'directorycreateerror', $dstDir );
983 'overwrite' => (bool)( $flags & self::OVERWRITE ),
984 'overwriteSame' => (bool)( $flags & self::OVERWRITE_SAME ),
989 $opts = [
'force' => true ];
990 if ( $flags & self::SKIP_LOCKING ) {
991 $opts[
'nonLocking'] =
true;
994 return $status->merge( $backend->doOperations( $operations, $opts ) );
1008 $this->assertWritableRepo();
1010 $status = $this->newGood();
1013 foreach ( $files as
$path ) {
1014 if ( is_array(
$path ) ) {
1016 [ $zone, $rel ] =
$path;
1017 $path = $this->getZonePath( $zone ) .
"/$rel";
1020 $path = $this->resolveToStoragePathIfVirtual(
$path );
1022 $operations[] = [
'op' =>
'delete',
'src' =>
$path ];
1025 $opts = [
'force' => true ];
1026 if ( $flags & self::SKIP_LOCKING ) {
1027 $opts[
'nonLocking'] =
true;
1030 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1051 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1069 $status = $this->newGood();
1071 foreach ( $triples as $triple ) {
1072 [ $src, $dst ] = $triple;
1073 if ( $src instanceof
FSFile ) {
1076 $src = $this->resolveToStoragePathIfVirtual( $src );
1077 $op = FileBackend::isStoragePath( $src ) ?
'copy' :
'store';
1079 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1081 if ( !isset( $triple[2] ) ) {
1083 } elseif ( is_string( $triple[2] ) ) {
1085 $headers = [
'Content-Disposition' => $triple[2] ];
1086 } elseif ( is_array( $triple[2] ) && isset( $triple[2][
'headers'] ) ) {
1087 $headers = $triple[2][
'headers'];
1096 'headers' => $headers
1098 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1101 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1113 return $this->quickPurgeBatch( [
$path ] );
1124 return $this->newGood()->merge(
1125 $this->backend->clean(
1126 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1140 $status = $this->newGood();
1142 foreach ( $paths as
$path ) {
1145 'src' => $this->resolveToStoragePathIfVirtual(
$path ),
1146 'ignoreMissingSource' => true
1149 $status->merge( $this->backend->doQuickOperations( $operations ) );
1165 $this->assertWritableRepo();
1167 $date = MWTimestamp::getInstance()->format(
'YmdHis' );
1168 $hashPath = $this->getHashPath( $originalName );
1169 $dstUrlRel = $hashPath . $date .
'!' . rawurlencode( $originalName );
1170 $virtualUrl = $this->getVirtualUrl(
'temp' ) .
'/' . $dstUrlRel;
1172 $result = $this->quickImport( $srcPath, $virtualUrl );
1173 $result->value = $virtualUrl;
1185 $this->assertWritableRepo();
1187 $temp = $this->getVirtualUrl(
'temp' );
1188 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1189 wfDebug( __METHOD__ .
": Invalid temp virtual URL" );
1194 return $this->quickPurge( $virtualUrl )->isOK();
1206 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1207 $this->assertWritableRepo();
1209 $status = $this->newGood();
1212 foreach ( $srcPaths as $srcPath ) {
1214 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1219 $params = [
'srcs' => $sources,
'dst' => $dstPath ];
1220 $status->merge( $this->backend->concatenate(
$params ) );
1221 if ( !$status->isOK() ) {
1226 if ( $flags & self::DELETE_SOURCE ) {
1227 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1231 $status->setResult(
true );
1260 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1262 $this->assertWritableRepo();
1264 $status = $this->publishBatch(
1265 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1266 if ( $status->successCount == 0 ) {
1267 $status->setOK(
false );
1269 $status->value = $status->value[0] ??
false;
1286 $this->assertWritableRepo();
1288 $backend = $this->backend;
1290 $this->initZones(
'public' );
1292 $status = $this->newGood( [] );
1295 $sourceFSFilesToDelete = [];
1297 foreach ( $ntuples as $ntuple ) {
1298 [ $src, $dstRel, $archiveRel ] = $ntuple;
1299 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1301 $options = $ntuple[3] ?? [];
1303 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1304 if ( !$this->validateFilename( $dstRel ) ) {
1305 throw new RuntimeException(
'Validation error in $dstRel' );
1307 if ( !$this->validateFilename( $archiveRel ) ) {
1308 throw new RuntimeException(
'Validation error in $archiveRel' );
1311 $publicRoot = $this->getZonePath(
'public' );
1312 $dstPath =
"$publicRoot/$dstRel";
1313 $archivePath =
"$publicRoot/$archiveRel";
1315 $dstDir = dirname( $dstPath );
1316 $archiveDir = dirname( $archivePath );
1318 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1319 return $this->newFatal(
'directorycreateerror', $dstDir );
1321 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1322 return $this->newFatal(
'directorycreateerror', $archiveDir );
1326 $headers = $options[
'headers'] ?? [];
1337 'dst' => $archivePath,
1338 'ignoreMissingSource' => true
1342 if ( FileBackend::isStoragePath( $srcPath ) ) {
1344 'op' => ( $flags & self::DELETE_SOURCE ) ?
'move' :
'copy',
1347 'overwrite' =>
true,
1348 'headers' => $headers
1355 'overwrite' =>
true,
1356 'headers' => $headers
1358 if ( $flags & self::DELETE_SOURCE ) {
1359 $sourceFSFilesToDelete[] = $srcPath;
1365 $status->merge( $backend->doOperations( $operations ) );
1367 foreach ( $ntuples as $i => $ntuple ) {
1368 [ , , $archiveRel ] = $ntuple;
1369 $archivePath = $this->getZonePath(
'public' ) .
"/$archiveRel";
1370 if ( $this->fileExists( $archivePath ) ) {
1371 $status->value[$i] =
'archived';
1373 $status->value[$i] =
'new';
1377 foreach ( $sourceFSFilesToDelete as $file ) {
1378 AtEase::suppressWarnings();
1380 AtEase::restoreWarnings();
1394 $path = $this->resolveToStoragePathIfVirtual( $dir );
1395 [ , $container, ] = FileBackend::splitStoragePath(
$path );
1398 if ( $this->isPrivate
1399 || $container === $this->zones[
'deleted'][
'container']
1400 || $container === $this->zones[
'temp'][
'container']
1402 # Take all available measures to prevent web accessibility of new deleted
1403 # directories, in case the user has not configured offline storage
1407 return $this->newGood()->merge( $this->backend->prepare(
$params ) );
1417 $this->assertWritableRepo();
1419 return $this->newGood()->merge(
1420 $this->backend->clean(
1421 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1433 $result = $this->fileExistsBatch( [ $file ] );
1446 $paths = array_map( [ $this,
'resolveToStoragePathIfVirtual' ], $files );
1447 $this->backend->preloadFileStat( [
'srcs' => $paths ] );
1450 foreach ( $paths as $key =>
$path ) {
1451 $result[$key] = $this->backend->fileExists( [
'src' =>
$path ] );
1467 public function delete( $srcRel, $archiveRel ) {
1468 $this->assertWritableRepo();
1470 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1490 $this->assertWritableRepo();
1493 $this->initZones( [
'public',
'deleted' ] );
1495 $status = $this->newGood();
1497 $backend = $this->backend;
1500 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1501 if ( !$this->validateFilename( $srcRel ) ) {
1502 throw new RuntimeException( __METHOD__ .
':Validation error in $srcRel' );
1503 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1504 throw new RuntimeException( __METHOD__ .
':Validation error in $archiveRel' );
1507 $publicRoot = $this->getZonePath(
'public' );
1508 $srcPath =
"{$publicRoot}/$srcRel";
1510 $deletedRoot = $this->getZonePath(
'deleted' );
1511 $archivePath =
"{$deletedRoot}/{$archiveRel}";
1512 $archiveDir = dirname( $archivePath );
1515 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1516 return $this->newFatal(
'directorycreateerror', $archiveDir );
1522 'dst' => $archivePath,
1525 'overwriteSame' =>
true
1532 $opts = [
'force' => true ];
1533 return $status->merge( $backend->doOperations( $operations, $opts ) );
1543 $this->assertWritableRepo();
1554 if ( strlen( $key ) < 31 ) {
1555 throw new InvalidArgumentException(
"Invalid storage key '$key'." );
1558 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1559 $path .= $key[$i] .
'/';
1573 if ( self::isVirtualUrl(
$path ) ) {
1574 return $this->resolveVirtualUrl(
$path );
1588 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1590 return $this->backend->getLocalCopy( [
'src' =>
$path ] );
1602 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1604 return $this->backend->getLocalReference( [
'src' =>
$path ] );
1615 $fsFile = $this->getLocalReference( $virtualUrl );
1616 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1618 $props = $mwProps->getPropsFromPath( $fsFile->getPath(),
true );
1620 $props = $mwProps->newPlaceholderProps();
1633 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1635 return $this->backend->getFileTimestamp( [
'src' =>
$path ] );
1645 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1647 return $this->backend->getFileSize( [
'src' =>
$path ] );
1657 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1659 return $this->backend->getFileSha1Base36( [
'src' =>
$path ] );
1672 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1673 $params = [
'src' =>
$path,
'headers' => $headers,
'options' => $optHeaders ];
1676 ob_start(
null, 1_048_576 );
1677 ob_implicit_flush(
true );
1679 $status = $this->newGood()->merge( $this->backend->streamFile(
$params ) );
1683 if ( ob_get_status() ) {
1699 $this->enumFilesInStorage( $callback );
1710 $publicRoot = $this->getZonePath(
'public' );
1711 $numDirs = 1 << ( $this->hashLevels * 4 );
1714 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1715 $hexString = sprintf(
"%0{$this->hashLevels}x", $flatIndex );
1716 $path = $publicRoot;
1717 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1718 $path .=
'/' . substr( $hexString, 0, $hexPos + 1 );
1720 $iterator = $this->backend->getFileList( [
'dir' =>
$path ] );
1721 if ( $iterator ===
null ) {
1722 throw new RuntimeException( __METHOD__ .
': could not get file listing for ' .
$path );
1724 foreach ( $iterator as $name ) {
1726 call_user_func( $callback,
"{$path}/{$name}" );
1738 if ( strval( $filename ) ==
'' ) {
1742 return FileBackend::isPathTraversalFree( $filename );
1750 private function getErrorCleanupFunction() {
1751 switch ( $this->pathDisclosureProtection ) {
1754 $callback = [ $this,
'passThrough' ];
1757 $callback = [ $this,
'paranoidClean' ];
1790 $status = Status::newFatal( $message, ...$parameters );
1791 $status->cleanCallback = $this->getErrorCleanupFunction();
1803 $status = Status::newGood( $value );
1804 $status->cleanCallback = $this->getErrorCleanupFunction();
1837 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1839 if ( $this->isLocal() ) {
1844 return wfMessageFallback(
'shared-repo-name-' . $this->name,
'shared-repo' )->text();
1855 if ( strlen( $name ) > $this->abbrvThreshold ) {
1856 $ext = FileBackend::extensionFromPath( $name );
1857 $name = ( $ext ==
'' ) ?
'thumbnail' :
"thumbnail.$ext";
1869 return $this->getName() ==
'local';
1899 return $this->wanCache->makeKey(
1900 'filerepo-' . $kClassSuffix,
1916 'name' =>
"{$this->name}-temp",
1917 'backend' => $this->backend,
1922 'container' => $this->zones[
'temp'][
'container'],
1923 'directory' => $this->zones[
'temp'][
'directory']
1926 'container' => $this->zones[
'temp'][
'container'],
1927 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1929 : $this->zones[
'temp'][
'directory'] .
'/thumb'
1932 'container' => $this->zones[
'temp'][
'container'],
1933 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1935 : $this->zones[
'temp'][
'directory'] .
'/transcoded'
1938 'hashLevels' => $this->hashLevels,
1970 'name' => $this->getName(),
1971 'displayname' => $this->getDisplayName(),
1972 'rootUrl' => $this->getZoneUrl(
'public' ),
1973 'local' => $this->isLocal(),
1976 $optionalSettings = [
1984 'descriptionCacheExpiry',
1986 foreach ( $optionalSettings as $k ) {
1987 if ( isset( $this->$k ) ) {
1988 $ret[$k] = $this->$k;
1991 if ( isset( $this->favicon ) ) {
1993 $ret[
'favicon'] = MediaWikiServices::getInstance()->getUrlUtils()
1994 ->expand( $this->favicon );
2005 return $this->hasSha1Storage;
2013 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.
Class representing a non-directory file on the file system.
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.
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.
getUploadStash(UserIdentity $user=null)
Get an UploadStash associated with this repo.
getDescriptionUrl( $name)
Get the URL of an image description page.
cleanDir( $dir)
Deletes a directory if empty.
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()
__construct(array $info=null)
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.
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:
Multi-datacenter aware caching interface.
Interface for objects (potentially) representing an editable wiki page.