15use Wikimedia\AtEase\AtEase;
134 protected $fileFactory = [ UnregisteredLocalFile::class,
'newFromTitle' ];
172 || !array_key_exists(
'name', $info )
173 || !array_key_exists(
'backend', $info )
176 " requires an array of options having both 'name' and 'backend' keys.\n" );
180 $this->name = $info[
'name'];
182 $this->backend = $info[
'backend'];
185 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info[
'backend'] );
189 $optionalSettings = [
190 'descBaseUrl',
'scriptDirUrl',
'articleUrl',
'fetchDescription',
191 'thumbScriptUrl',
'pathDisclosureProtection',
'descriptionCacheExpiry',
192 'favicon',
'thumbProxyUrl',
'thumbProxySecret',
'disableLocalTransform'
194 foreach ( $optionalSettings as $var ) {
195 if ( isset( $info[$var] ) ) {
196 $this->$var = $info[$var];
202 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE );
203 $this->initialCapital = $info[
'initialCapital'] ?? $localCapitalLinks;
204 if ( $localCapitalLinks && !$this->initialCapital ) {
212 throw new InvalidArgumentException(
213 'File repos with initial capital false are not allowed on wikis where the File ' .
214 'namespace has initial capital true' );
217 $this->url = $info[
'url'] ??
false;
218 if ( isset( $info[
'thumbUrl'] ) ) {
219 $this->thumbUrl = $info[
'thumbUrl'];
221 $this->thumbUrl = $this->url ?
"{$this->url}/thumb" :
false;
223 $this->hashLevels = $info[
'hashLevels'] ?? 2;
225 $this->transformVia404 = !empty( $info[
'transformVia404'] );
226 $this->abbrvThreshold = $info[
'abbrvThreshold'] ?? 255;
227 $this->isPrivate = !empty( $info[
'isPrivate'] );
229 $this->zones = $info[
'zones'] ?? [];
230 foreach ( [
'public',
'thumb',
'transcoded',
'temp',
'deleted' ] as $zone ) {
231 if ( !isset( $this->zones[$zone][
'container'] ) ) {
232 $this->zones[$zone][
'container'] =
"{$this->name}-{$zone}";
234 if ( !isset( $this->zones[$zone][
'directory'] ) ) {
235 $this->zones[$zone][
'directory'] =
'';
237 if ( !isset( $this->zones[$zone][
'urlsByExt'] ) ) {
238 $this->zones[$zone][
'urlsByExt'] = [];
244 $this->wanCache = $info[
'wanCache'] ?? WANObjectCache::newEmpty();
263 return $this->backend->getReadOnlyReason();
273 foreach ( (array)$doZones as $zone ) {
275 if ( $root ===
null ) {
276 throw new MWException(
"No '$zone' zone defined in the {$this->name} repo." );
288 return substr( $url, 0, 9 ) ==
'mwrepo://';
300 $path =
'mwrepo://' . $this->name;
301 if ( $suffix !==
false ) {
302 $path .=
'/' . rawurlencode( $suffix );
316 if ( in_array( $zone, [
'public',
'thumb',
'transcoded' ] ) ) {
318 if (
$ext !==
null && isset( $this->zones[$zone][
'urlsByExt'][
$ext] ) ) {
321 return $this->zones[$zone][
'urlsByExt'][
$ext];
322 } elseif ( isset( $this->zones[$zone][
'url'] ) ) {
324 return $this->zones[$zone][
'url'];
334 return $this->thumbUrl;
336 return "{$this->url}/transcoded";
358 if ( substr( $url, 0, 9 ) !=
'mwrepo://' ) {
359 throw new MWException( __METHOD__ .
': unknown protocol' );
361 $bits = explode(
'/', substr( $url, 9 ), 3 );
362 if ( count( $bits ) != 3 ) {
363 throw new MWException( __METHOD__ .
": invalid mwrepo URL: $url" );
365 list( $repo, $zone, $rel ) = $bits;
366 if ( $repo !== $this->name ) {
367 throw new MWException( __METHOD__ .
": fetching from a foreign repo is not supported" );
369 $base = $this->getZonePath( $zone );
371 throw new MWException( __METHOD__ .
": invalid zone: $zone" );
374 return $base .
'/' . rawurldecode( $rel );
384 if ( !isset( $this->zones[$zone] ) ) {
385 return [
null, null ];
388 return [ $this->zones[$zone][
'container'], $this->zones[$zone][
'directory'] ];
398 list( $container,
$base ) = $this->getZoneLocation( $zone );
399 if ( $container ===
null ||
$base ===
null ) {
402 $backendName = $this->backend->getName();
407 return "mwstore://$backendName/{$container}{$base}";
427 if ( $this->oldFileFactory ) {
428 return call_user_func( $this->oldFileFactory,
$title, $this, $time );
433 return call_user_func( $this->fileFactory,
$title, $this );
457 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
458 throw new InvalidArgumentException(
459 __METHOD__ .
' called with the `private` option set to something ' .
460 'other than an Authority object'
468 if ( isset( $options[
'bypassCache'] ) ) {
469 $options[
'latest'] = $options[
'bypassCache'];
471 $time = $options[
'time'] ??
false;
472 $flags = !empty( $options[
'latest'] ) ? File::READ_LATEST : 0;
473 # First try the current version of the file to see if it precedes the timestamp
474 $img = $this->newFile(
$title );
478 $img->load( $flags );
479 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
482 # Now try an old version of the file
483 if ( $time !==
false ) {
484 $img = $this->newFile(
$title, $time );
486 $img->load( $flags );
487 if ( $img->exists() ) {
488 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
492 !empty( $options[
'private'] ) &&
493 $img->userCan( File::DELETED_FILE, $options[
'private'] )
502 if ( !empty( $options[
'ignoreRedirect'] ) ) {
505 $redir = $this->checkRedirect(
$title );
507 $img = $this->newFile( $redir );
511 $img->load( $flags );
512 if ( $img->exists() ) {
513 $img->redirectedFrom(
$title->getDBkey() );
541 foreach ( $items as $item ) {
542 if ( is_array( $item ) ) {
545 unset( $options[
'title'] );
548 !empty( $options[
'private'] ) &&
549 !( $options[
'private'] instanceof
Authority )
551 $options[
'private'] = RequestContext::getMain()->getAuthority();
559 $searchName = File::normalizeTitle(
$title )->getDBkey();
560 if ( $flags & self::NAME_AND_TIME_ONLY ) {
561 $result[$searchName] = [
562 'title' =>
$file->getTitle()->getDBkey(),
563 'timestamp' =>
$file->getTimestamp()
566 $result[$searchName] =
$file;
585 if ( !empty( $options[
'private'] ) && !( $options[
'private'] instanceof
Authority ) ) {
586 throw new InvalidArgumentException(
587 __METHOD__ .
' called with the `private` option set to something ' .
588 'other than an Authority object'
592 $time = $options[
'time'] ??
false;
593 # First try to find a matching current version of a file...
594 if ( !$this->fileFactoryKey ) {
597 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
598 if ( $img && $img->exists() ) {
601 # Now try to find a matching old version of a file...
602 if ( $time !==
false && $this->oldFileFactoryKey ) {
603 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
604 if ( $img && $img->exists() ) {
605 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
609 !empty( $options[
'private'] ) &&
610 $img->userCan( File::DELETED_FILE, $options[
'private'] )
642 $files = $this->findBySha1( $hash );
643 if ( count( $files ) ) {
644 $result[$hash] = $files;
669 return $this->thumbScriptUrl;
678 return $this->thumbProxyUrl;
687 return $this->thumbProxySecret;
696 return $this->transformVia404;
706 return !$this->disableLocalTransform;
717 $this->initialCapital !=
718 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized(
NS_FILE )
720 $name =
$title->getDBkey();
721 if ( $this->initialCapital ) {
722 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
725 $name =
$title->getDBkey();
737 return $this->getZonePath(
'public' );
748 return self::getHashPathForLevel( $name, $this->hashLevels );
759 $parts = explode(
'!', $suffix, 2 );
760 $name = $parts[1] ?? $suffix;
761 return self::getHashPathForLevel( $name, $this->hashLevels );
770 if ( $levels == 0 ) {
773 $hash = md5( $name );
775 for ( $i = 1; $i <= $levels; $i++ ) {
776 $path .= substr( $hash, 0, $i ) .
'/';
789 return $this->hashLevels;
808 public function makeUrl( $query =
'', $entry =
'index' ) {
809 if ( isset( $this->scriptDirUrl ) ) {
810 return wfAppendQuery(
"{$this->scriptDirUrl}/{$entry}.php", $query );
830 if ( $this->descBaseUrl !==
null ) {
831 # "http://example.com/wiki/File:"
832 return $this->descBaseUrl . $encName;
834 if ( $this->articleUrl !==
null ) {
835 # "http://example.com/wiki/$1"
836 # We use "Image:" as the canonical namespace for
837 # compatibility across all MediaWiki versions.
838 return str_replace(
'$1',
839 "Image:$encName", $this->articleUrl );
841 if ( $this->scriptDirUrl !==
null ) {
842 # "http://example.com/w"
843 # We use "Image:" as the canonical namespace for
844 # compatibility across all MediaWiki versions,
845 # and just sort of hope index.php is right. ;)
846 return $this->makeUrl(
"title=Image:$encName" );
863 $query =
'action=render';
864 if (
$lang !==
null ) {
865 $query .=
'&uselang=' . urlencode(
$lang );
867 if ( isset( $this->scriptDirUrl ) ) {
868 return $this->makeUrl(
873 $descUrl = $this->getDescriptionUrl( $name );
888 if ( isset( $this->scriptDirUrl ) ) {
891 return $this->makeUrl(
'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
914 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
915 $this->assertWritableRepo();
917 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
918 if ( $status->successCount == 0 ) {
919 $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 $triplet ) {
952 list( $src, $dstZone, $dstRel ) = $triplet;
953 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
955 .
"( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
958 if ( $src instanceof
FSFile ) {
961 $src = $this->resolveToStoragePathIfVirtual( $src );
965 $root = $this->getZonePath( $dstZone );
969 if ( !$this->validateFilename( $dstRel ) ) {
970 throw new MWException(
'Validation error in $dstRel' );
972 $dstPath =
"$root/$dstRel";
973 $dstDir = dirname( $dstPath );
975 if ( !$this->initDirectory( $dstDir )->isOK() ) {
976 return $this->newFatal(
'directorycreateerror', $dstDir );
984 'overwrite' => ( $flags & self::OVERWRITE ) ?
true :
false,
985 'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ?
true :
false,
990 $opts = [
'force' =>
true ];
991 if ( $flags & self::SKIP_LOCKING ) {
992 $opts[
'nonLocking'] =
true;
995 return $status->merge( $backend->doOperations( $operations, $opts ) );
1009 $this->assertWritableRepo();
1011 $status = $this->newGood();
1014 foreach ( $files as
$path ) {
1015 if ( is_array(
$path ) ) {
1017 list( $zone, $rel ) =
$path;
1018 $path = $this->getZonePath( $zone ) .
"/$rel";
1021 $path = $this->resolveToStoragePathIfVirtual(
$path );
1023 $operations[] = [
'op' =>
'delete',
'src' =>
$path ];
1026 $opts = [
'force' =>
true ];
1027 if ( $flags & self::SKIP_LOCKING ) {
1028 $opts[
'nonLocking'] =
true;
1031 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1052 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1070 $status = $this->newGood();
1072 foreach ( $triples as $triple ) {
1073 list( $src, $dst ) = $triple;
1074 if ( $src instanceof
FSFile ) {
1077 $src = $this->resolveToStoragePathIfVirtual( $src );
1080 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1082 if ( !isset( $triple[2] ) ) {
1084 } elseif ( is_string( $triple[2] ) ) {
1086 $headers = [
'Content-Disposition' => $triple[2] ];
1087 } elseif ( is_array( $triple[2] ) && isset( $triple[2][
'headers'] ) ) {
1088 $headers = $triple[2][
'headers'];
1097 'headers' => $headers
1099 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1102 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1114 return $this->quickPurgeBatch( [
$path ] );
1125 return $this->newGood()->merge(
1126 $this->backend->clean(
1127 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1141 $status = $this->newGood();
1143 foreach ( $paths as
$path ) {
1146 'src' => $this->resolveToStoragePathIfVirtual(
$path ),
1147 'ignoreMissingSource' =>
true
1150 $status->merge( $this->backend->doQuickOperations( $operations ) );
1166 $this->assertWritableRepo();
1168 $date = MWTimestamp::getInstance()->format(
'YmdHis' );
1169 $hashPath = $this->getHashPath( $originalName );
1170 $dstUrlRel = $hashPath . $date .
'!' . rawurlencode( $originalName );
1171 $virtualUrl = $this->getVirtualUrl(
'temp' ) .
'/' . $dstUrlRel;
1173 $result = $this->quickImport( $srcPath, $virtualUrl );
1174 $result->value = $virtualUrl;
1186 $this->assertWritableRepo();
1188 $temp = $this->getVirtualUrl(
'temp' );
1189 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1190 wfDebug( __METHOD__ .
": Invalid temp virtual URL" );
1195 return $this->quickPurge( $virtualUrl )->isOK();
1207 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1208 $this->assertWritableRepo();
1210 $status = $this->newGood();
1213 foreach ( $srcPaths as $srcPath ) {
1215 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1220 $params = [
'srcs' => $sources,
'dst' => $dstPath ];
1221 $status->merge( $this->backend->concatenate( $params ) );
1222 if ( !$status->isOK() ) {
1227 if ( $flags & self::DELETE_SOURCE ) {
1228 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1232 $status->setResult(
true );
1261 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1263 $this->assertWritableRepo();
1265 $status = $this->publishBatch(
1266 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1267 if ( $status->successCount == 0 ) {
1268 $status->setOK(
false );
1270 $status->value = $status->value[0] ??
false;
1288 $this->assertWritableRepo();
1290 $backend = $this->backend;
1292 $this->initZones(
'public' );
1294 $status = $this->newGood( [] );
1297 $sourceFSFilesToDelete = [];
1299 foreach ( $ntuples as $ntuple ) {
1300 list( $src, $dstRel, $archiveRel ) = $ntuple;
1301 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1303 $options = $ntuple[3] ?? [];
1305 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1306 if ( !$this->validateFilename( $dstRel ) ) {
1307 throw new MWException(
'Validation error in $dstRel' );
1309 if ( !$this->validateFilename( $archiveRel ) ) {
1310 throw new MWException(
'Validation error in $archiveRel' );
1313 $publicRoot = $this->getZonePath(
'public' );
1314 $dstPath =
"$publicRoot/$dstRel";
1315 $archivePath =
"$publicRoot/$archiveRel";
1317 $dstDir = dirname( $dstPath );
1318 $archiveDir = dirname( $archivePath );
1320 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1321 return $this->newFatal(
'directorycreateerror', $dstDir );
1323 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1324 return $this->newFatal(
'directorycreateerror', $archiveDir );
1328 $headers = $options[
'headers'] ?? [];
1339 'dst' => $archivePath,
1340 'ignoreMissingSource' =>
true
1346 'op' => ( $flags & self::DELETE_SOURCE ) ?
'move' :
'copy',
1349 'overwrite' =>
true,
1350 'headers' => $headers
1357 'overwrite' =>
true,
1358 'headers' => $headers
1360 if ( $flags & self::DELETE_SOURCE ) {
1361 $sourceFSFilesToDelete[] = $srcPath;
1367 $status->merge( $backend->doOperations( $operations ) );
1369 foreach ( $ntuples as $i => $ntuple ) {
1370 list( , , $archiveRel ) = $ntuple;
1371 $archivePath = $this->getZonePath(
'public' ) .
"/$archiveRel";
1372 if ( $this->fileExists( $archivePath ) ) {
1373 $status->value[$i] =
'archived';
1375 $status->value[$i] =
'new';
1379 foreach ( $sourceFSFilesToDelete as
$file ) {
1380 AtEase::suppressWarnings();
1382 AtEase::restoreWarnings();
1396 $path = $this->resolveToStoragePathIfVirtual( $dir );
1399 $params = [
'dir' =>
$path ];
1400 if ( $this->isPrivate
1401 || $container === $this->zones[
'deleted'][
'container']
1402 || $container === $this->zones[
'temp'][
'container']
1404 # Take all available measures to prevent web accessibility of new deleted
1405 # directories, in case the user has not configured offline storage
1406 $params = [
'noAccess' =>
true,
'noListing' =>
true ] + $params;
1409 return $this->newGood()->merge( $this->backend->prepare( $params ) );
1419 $this->assertWritableRepo();
1421 return $this->newGood()->merge(
1422 $this->backend->clean(
1423 [
'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1435 $result = $this->fileExistsBatch( [
$file ] );
1448 $paths = array_map( [ $this,
'resolveToStoragePathIfVirtual' ], $files );
1449 $this->backend->preloadFileStat( [
'srcs' => $paths ] );
1452 foreach ( $files as $key =>
$file ) {
1453 $path = $this->resolveToStoragePathIfVirtual(
$file );
1454 $result[$key] = $this->backend->fileExists( [
'src' =>
$path ] );
1470 public function delete( $srcRel, $archiveRel ) {
1471 $this->assertWritableRepo();
1473 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1494 $this->assertWritableRepo();
1497 $this->initZones( [
'public',
'deleted' ] );
1499 $status = $this->newGood();
1501 $backend = $this->backend;
1504 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1505 if ( !$this->validateFilename( $srcRel ) ) {
1506 throw new MWException( __METHOD__ .
':Validation error in $srcRel' );
1507 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1508 throw new MWException( __METHOD__ .
':Validation error in $archiveRel' );
1511 $publicRoot = $this->getZonePath(
'public' );
1512 $srcPath =
"{$publicRoot}/$srcRel";
1514 $deletedRoot = $this->getZonePath(
'deleted' );
1515 $archivePath =
"{$deletedRoot}/{$archiveRel}";
1516 $archiveDir = dirname( $archivePath );
1519 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1520 return $this->newFatal(
'directorycreateerror', $archiveDir );
1526 'dst' => $archivePath,
1529 'overwriteSame' =>
true
1536 $opts = [
'force' =>
true ];
1537 return $status->merge( $backend->doOperations( $operations, $opts ) );
1547 $this->assertWritableRepo();
1559 if ( strlen( $key ) < 31 ) {
1560 throw new MWException(
"Invalid storage key '$key'." );
1563 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1564 $path .= $key[$i] .
'/';
1579 if ( self::isVirtualUrl(
$path ) ) {
1580 return $this->resolveVirtualUrl(
$path );
1594 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1596 return $this->backend->getLocalCopy( [
'src' =>
$path ] );
1608 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1610 return $this->backend->getLocalReference( [
'src' =>
$path ] );
1621 $fsFile = $this->getLocalReference( $virtualUrl );
1622 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1624 $props = $mwProps->getPropsFromPath( $fsFile->getPath(),
true );
1626 $props = $mwProps->newPlaceholderProps();
1639 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1641 return $this->backend->getFileTimestamp( [
'src' =>
$path ] );
1651 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1653 return $this->backend->getFileSize( [
'src' =>
$path ] );
1663 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1665 return $this->backend->getFileSha1Base36( [
'src' =>
$path ] );
1678 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1679 $params = [
'src' =>
$path,
'headers' => $headers,
'options' => $optHeaders ];
1682 ob_start(
null, 1048576 );
1683 ob_implicit_flush(
true );
1685 $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1689 if ( ob_get_status() ) {
1705 $this->enumFilesInStorage( $callback );
1716 $publicRoot = $this->getZonePath(
'public' );
1717 $numDirs = 1 << ( $this->hashLevels * 4 );
1720 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1721 $hexString = sprintf(
"%0{$this->hashLevels}x", $flatIndex );
1722 $path = $publicRoot;
1723 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1724 $path .=
'/' . substr( $hexString, 0, $hexPos + 1 );
1726 $iterator = $this->backend->getFileList( [
'dir' =>
$path ] );
1727 if ( $iterator ===
null ) {
1728 throw new MWException( __METHOD__ .
': could not get file listing for ' .
$path );
1730 foreach ( $iterator as $name ) {
1732 call_user_func( $callback,
"{$path}/{$name}" );
1744 if ( strval( $filename ) ==
'' ) {
1757 switch ( $this->pathDisclosureProtection ) {
1760 $callback = [ $this,
'passThrough' ];
1763 $callback = [ $this,
'paranoidClean' ];
1796 $status = Status::newFatal( $message, ...$parameters );
1797 $status->cleanCallback = $this->getErrorCleanupFunction();
1809 $status = Status::newGood( $value );
1810 $status->cleanCallback = $this->getErrorCleanupFunction();
1843 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get(
'Sitename' );
1845 if ( $this->isLocal() ) {
1850 return wfMessageFallback(
'shared-repo-name-' . $this->name,
'shared-repo' )->text();
1861 if ( strlen( $name ) > $this->abbrvThreshold ) {
1863 $name = (
$ext ==
'' ) ?
'thumbnail' :
"thumbnail.$ext";
1875 return $this->getName() ==
'local';
1905 return $this->wanCache->makeKey(
1906 'filerepo-' . $kClassSuffix,
1922 'name' =>
"{$this->name}-temp",
1923 'backend' => $this->backend,
1928 'container' => $this->zones[
'temp'][
'container'],
1929 'directory' => $this->zones[
'temp'][
'directory']
1932 'container' => $this->zones[
'temp'][
'container'],
1933 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1935 : $this->zones[
'temp'][
'directory'] .
'/thumb'
1938 'container' => $this->zones[
'temp'][
'container'],
1939 'directory' => $this->zones[
'temp'][
'directory'] ==
''
1941 : $this->zones[
'temp'][
'directory'] .
'/transcoded'
1944 'hashLevels' => $this->hashLevels,
1977 'name' => $this->getName(),
1978 'displayname' => $this->getDisplayName(),
1979 'rootUrl' => $this->getZoneUrl(
'public' ),
1980 'local' => $this->isLocal(),
1983 $optionalSettings = [
1991 'descriptionCacheExpiry',
1993 foreach ( $optionalSettings as $k ) {
1994 if ( isset( $this->$k ) ) {
1995 $ret[$k] = $this->$k;
1998 if ( isset( $this->favicon ) ) {
2011 return $this->hasSha1Storage;
2019 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,...
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
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...
Class representing a non-directory file on the file system.
Base class for all file backend classes (including multi-write backends).
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
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.
string $thumbUrl
The base thumbnail URL.
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)
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.
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
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.
FileRepo for temporary files created via FileRepo::getTempRepo()
UploadStash is intended to accomplish a few things:
Multi-datacenter aware caching interface.
Interface for objects (potentially) representing an editable wiki page.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext
if(!isset( $args[0])) $lang