MediaWiki master
FileRepo.php
Go to the documentation of this file.
1<?php
10namespace MediaWiki\FileRepo;
11
12use InvalidArgumentException;
13use LogicException;
27use MWFileProps;
28use RuntimeException;
29use Shellbox\Command\BoxedCommand;
30use StatusValue;
31use UploadStash;
32use Wikimedia\AtEase\AtEase;
38
54class FileRepo {
55 public const DELETE_SOURCE = 1;
56 public const OVERWRITE = 2;
57 public const OVERWRITE_SAME = 4;
58 public const SKIP_LOCKING = 8;
59
60 public const NAME_AND_TIME_ONLY = 1;
61
66
69
71 protected $hasSha1Storage = false;
72
74 protected $supportsSha1URLs = false;
75
77 protected $backend;
78
80 protected $zones = [];
81
83 protected $thumbScriptUrl;
84
89
93 protected $descBaseUrl;
94
98 protected $scriptDirUrl;
99
101 protected $articleUrl;
102
109
115 protected $pathDisclosureProtection = 'simple';
116
118 protected $url;
119
121 protected $thumbUrl;
122
124 protected $hashLevels;
125
128
134
136 protected $favicon = null;
137
139 protected $isPrivate;
140
142 protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
144 protected $oldFileFactory = false;
146 protected $fileFactoryKey = false;
148 protected $oldFileFactoryKey = false;
149
153 protected $thumbProxyUrl;
156
158 protected $disableLocalTransform = false;
159
161 protected $wanCache;
162
168 public $name;
169
175 public function __construct( ?array $info = null ) {
176 // Verify required settings presence
177 if (
178 $info === null
179 || !array_key_exists( 'name', $info )
180 || !array_key_exists( 'backend', $info )
181 ) {
182 throw new InvalidArgumentException( __CLASS__ .
183 " requires an array of options having both 'name' and 'backend' keys.\n" );
184 }
185
186 // Required settings
187 $this->name = $info['name'];
188 if ( $info['backend'] instanceof FileBackend ) {
189 $this->backend = $info['backend']; // useful for testing
190 } else {
191 $this->backend =
192 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
193 }
194
195 // Optional settings that can have no value
196 $optionalSettings = [
197 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
198 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
199 'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
200 ];
201 foreach ( $optionalSettings as $var ) {
202 if ( isset( $info[$var] ) ) {
203 $this->$var = $info[$var];
204 }
205 }
206
207 // Optional settings that have a default
208 $localCapitalLinks =
209 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
210 $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
211 if ( $localCapitalLinks && !$this->initialCapital ) {
212 // If the local wiki's file namespace requires an initial capital, but a foreign file
213 // repo doesn't, complications will result. Linker code will want to auto-capitalize the
214 // first letter of links to files, but those links might actually point to files on
215 // foreign wikis with initial-lowercase names. This combination is not likely to be
216 // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
217 // to include a foreign file repo with initialCapital false, set your local file
218 // namespace to not be capitalized either.
219 throw new InvalidArgumentException(
220 'File repos with initial capital false are not allowed on wikis where the File ' .
221 'namespace has initial capital true' );
222 }
223
224 $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
225 $defaultThumbUrl = $this->url ? $this->url . '/thumb' : false;
226 $this->thumbUrl = $info['thumbUrl'] ?? $defaultThumbUrl;
227 $this->hashLevels = $info['hashLevels'] ?? 2;
228 $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
229 $this->transformVia404 = !empty( $info['transformVia404'] );
230 $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
231 $this->isPrivate = !empty( $info['isPrivate'] );
232 // Give defaults for the basic zones...
233 $this->zones = $info['zones'] ?? [];
234 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
235 if ( !isset( $this->zones[$zone]['container'] ) ) {
236 $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
237 }
238 if ( !isset( $this->zones[$zone]['directory'] ) ) {
239 $this->zones[$zone]['directory'] = '';
240 }
241 if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
242 $this->zones[$zone]['urlsByExt'] = [];
243 }
244 }
245
246 $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
247
248 $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
249 }
250
256 public function getBackend() {
257 return $this->backend;
258 }
259
266 public function getReadOnlyReason() {
267 return $this->backend->getReadOnlyReason();
268 }
269
275 protected function initZones( $doZones = [] ): void {
276 foreach ( (array)$doZones as $zone ) {
277 $root = $this->getZonePath( $zone );
278 if ( $root === null ) {
279 throw new RuntimeException( "No '$zone' zone defined in the {$this->name} repo." );
280 }
281 }
282 }
283
290 public static function isVirtualUrl( $url ) {
291 return str_starts_with( $url, 'mwrepo://' );
292 }
293
302 public function getVirtualUrl( $suffix = false ) {
303 $path = 'mwrepo://' . $this->name;
304 if ( $suffix !== false ) {
305 $path .= '/' . rawurlencode( $suffix );
306 }
307
308 return $path;
309 }
310
318 public function getZoneUrl( $zone, $ext = null ) {
319 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
320 // standard public zones
321 if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
322 // custom URL for extension/zone
323 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
324 return $this->zones[$zone]['urlsByExt'][$ext];
325 } elseif ( isset( $this->zones[$zone]['url'] ) ) {
326 // custom URL for zone
327 return $this->zones[$zone]['url'];
328 }
329 }
330 switch ( $zone ) {
331 case 'public':
332 return $this->url;
333 case 'temp':
334 case 'deleted':
335 return false; // no public URL
336 case 'thumb':
337 return $this->thumbUrl;
338 case 'transcoded':
339 return "{$this->url}/transcoded";
340 default:
341 return false;
342 }
343 }
344
348 public function backendSupportsUnicodePaths() {
349 return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
350 }
351
360 public function resolveVirtualUrl( $url ) {
361 if ( !str_starts_with( $url, 'mwrepo://' ) ) {
362 throw new InvalidArgumentException( __METHOD__ . ': unknown protocol' );
363 }
364 $bits = explode( '/', substr( $url, 9 ), 3 );
365 if ( count( $bits ) != 3 ) {
366 throw new InvalidArgumentException( __METHOD__ . ": invalid mwrepo URL: $url" );
367 }
368 [ $repo, $zone, $rel ] = $bits;
369 if ( $repo !== $this->name ) {
370 throw new InvalidArgumentException( __METHOD__ . ": fetching from a foreign repo is not supported" );
371 }
372 $base = $this->getZonePath( $zone );
373 if ( !$base ) {
374 throw new InvalidArgumentException( __METHOD__ . ": invalid zone: $zone" );
375 }
376
377 return $base . '/' . rawurldecode( $rel );
378 }
379
386 protected function getZoneLocation( $zone ) {
387 if ( !isset( $this->zones[$zone] ) ) {
388 return [ null, null ]; // bogus
389 }
390
391 return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
392 }
393
400 public function getZonePath( $zone ) {
401 [ $container, $base ] = $this->getZoneLocation( $zone );
402 if ( $container === null || $base === null ) {
403 return null;
404 }
405 $backendName = $this->backend->getName();
406 if ( $base != '' ) { // may not be set
407 $base = "/{$base}";
408 }
409
410 return "mwstore://$backendName/{$container}{$base}";
411 }
412
424 public function newFile( $title, $time = false ) {
425 $title = File::normalizeTitle( $title );
426 if ( !$title ) {
427 return null;
428 }
429 if ( $time ) {
430 if ( $this->oldFileFactory ) {
431 return ( $this->oldFileFactory )( $title, $this, $time );
432 } else {
433 return null;
434 }
435 } else {
436 return ( $this->fileFactory )( $title, $this );
437 }
438 }
439
459 public function findFile( $title, $options = [] ) {
460 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
461 throw new InvalidArgumentException(
462 __METHOD__ . ' called with the `private` option set to something ' .
463 'other than an Authority object'
464 );
465 }
466
467 $title = File::normalizeTitle( $title );
468 if ( !$title ) {
469 return false;
470 }
471 if ( isset( $options['bypassCache'] ) ) {
472 $options['latest'] = $options['bypassCache']; // b/c
473 }
474 $time = $options['time'] ?? false;
475 $flags = !empty( $options['latest'] ) ? IDBAccessObject::READ_LATEST : 0;
476 # First try the current version of the file to see if it precedes the timestamp
477 $img = $this->newFile( $title );
478 if ( !$img ) {
479 return false;
480 }
481 $img->load( $flags );
482 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
483 return $img;
484 }
485 # Now try an old version of the file
486 if ( $time !== false ) {
487 $img = $this->newFile( $title, $time );
488 if ( $img ) {
489 $img->load( $flags );
490 if ( $img->exists() ) {
491 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
492 return $img; // always OK
493 } elseif (
494 // If its not empty, its an Authority object
495 !empty( $options['private'] ) &&
496 $img->userCan( File::DELETED_FILE, $options['private'] )
497 ) {
498 return $img;
499 }
500 }
501 }
502 }
503
504 # Now try redirects
505 if ( !empty( $options['ignoreRedirect'] ) ) {
506 return false;
507 }
508 $redir = $this->checkRedirect( $title );
509 if ( $redir && $title->getNamespace() === NS_FILE ) {
510 $img = $this->newFile( $redir );
511 if ( !$img ) {
512 return false;
513 }
514 $img->load( $flags );
515 if ( $img->exists() ) {
516 $img->redirectedFrom( $title->getDBkey() );
517
518 return $img;
519 }
520 }
521
522 return false;
523 }
524
542 public function findFiles( array $items, $flags = 0 ) {
543 $result = [];
544 foreach ( $items as $item ) {
545 if ( is_array( $item ) ) {
546 $title = $item['title'];
547 $options = $item;
548 unset( $options['title'] );
549
550 if (
551 !empty( $options['private'] ) &&
552 !( $options['private'] instanceof Authority )
553 ) {
554 $options['private'] = RequestContext::getMain()->getAuthority();
555 }
556 } else {
557 $title = $item;
558 $options = [];
559 }
560 $file = $this->findFile( $title, $options );
561 if ( $file ) {
562 $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
563 if ( $flags & self::NAME_AND_TIME_ONLY ) {
564 $result[$searchName] = [
565 'title' => $file->getTitle()->getDBkey(),
566 'timestamp' => $file->getTimestamp()
567 ];
568 } else {
569 $result[$searchName] = $file;
570 }
571 }
572 }
573
574 return $result;
575 }
576
587 public function findFileFromKey( $sha1, $options = [] ) {
588 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
589 throw new InvalidArgumentException(
590 __METHOD__ . ' called with the `private` option set to something ' .
591 'other than an Authority object'
592 );
593 }
594
595 $time = $options['time'] ?? false;
596 # First try to find a matching current version of a file...
597 if ( !$this->fileFactoryKey ) {
598 return false; // find-by-sha1 not supported
599 }
600 $img = ( $this->fileFactoryKey )( $sha1, $this, $time );
601 if ( $img && $img->exists() ) {
602 return $img;
603 }
604 # Now try to find a matching old version of a file...
605 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
606 $img = ( $this->oldFileFactoryKey )( $sha1, $this, $time );
607 if ( $img && $img->exists() ) {
608 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
609 return $img; // always OK
610 } elseif (
611 // If its not empty, its an Authority object
612 !empty( $options['private'] ) &&
613 $img->userCan( File::DELETED_FILE, $options['private'] )
614 ) {
615 return $img;
616 }
617 }
618 }
619
620 return false;
621 }
622
631 public function findBySha1( $hash ) {
632 return [];
633 }
634
642 public function findBySha1s( array $hashes ) {
643 $result = [];
644 foreach ( $hashes as $hash ) {
645 $files = $this->findBySha1( $hash );
646 if ( count( $files ) ) {
647 $result[$hash] = $files;
648 }
649 }
650
651 return $result;
652 }
653
662 public function findFilesByPrefix( $prefix, $limit ) {
663 return [];
664 }
665
671 public function getThumbScriptUrl() {
672 return $this->thumbScriptUrl;
673 }
674
680 public function getThumbProxyUrl() {
681 return $this->thumbProxyUrl;
682 }
683
689 public function getThumbProxySecret() {
690 return $this->thumbProxySecret;
691 }
692
698 public function canTransformVia404() {
699 return $this->transformVia404;
700 }
701
708 public function canTransformLocally() {
709 return !$this->disableLocalTransform;
710 }
711
718 public function getNameFromTitle( $title ) {
719 if (
720 $this->initialCapital !=
721 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
722 ) {
723 $name = $title->getDBkey();
724 if ( $this->initialCapital ) {
725 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
726 }
727 } else {
728 $name = $title->getDBkey();
729 }
730
731 return $name;
732 }
733
739 public function getRootDirectory() {
740 return $this->getZonePath( 'public' );
741 }
742
750 public function getHashPath( $name ) {
751 return self::getHashPathForLevel( $name, $this->hashLevels );
752 }
753
761 public function getTempHashPath( $suffix ) {
762 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
763 $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
764 return self::getHashPathForLevel( $name, $this->hashLevels );
765 }
766
772 protected static function getHashPathForLevel( $name, $levels ) {
773 if ( $levels == 0 ) {
774 return '';
775 } else {
776 $hash = md5( $name );
777 $path = '';
778 for ( $i = 1; $i <= $levels; $i++ ) {
779 $path .= substr( $hash, 0, $i ) . '/';
780 }
781
782 return $path;
783 }
784 }
785
791 public function getHashLevels() {
792 return $this->hashLevels;
793 }
794
800 public function getName() {
801 return $this->name;
802 }
803
811 public function makeUrl( $query = '', $entry = 'index' ) {
812 if ( $this->scriptDirUrl !== null ) {
813 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
814 }
815
816 return false;
817 }
818
831 public function getDescriptionUrl( $name ) {
832 $encName = wfUrlencode( $name );
833 if ( $this->descBaseUrl !== null ) {
834 # "http://example.com/wiki/File:"
835 return $this->descBaseUrl . $encName;
836 }
837 if ( $this->articleUrl !== null ) {
838 # "http://example.com/wiki/$1"
839 # We use "Image:" as the canonical namespace for
840 # compatibility across all MediaWiki versions.
841 return str_replace( '$1',
842 "Image:$encName", $this->articleUrl );
843 }
844 if ( $this->scriptDirUrl !== null ) {
845 # "http://example.com/w"
846 # We use "Image:" as the canonical namespace for
847 # compatibility across all MediaWiki versions,
848 # and just sort of hope index.php is right. ;)
849 return $this->makeUrl( "title=Image:$encName" );
850 }
851
852 return false;
853 }
854
865 public function getDescriptionRenderUrl( $name, $lang = null ) {
866 $query = 'action=render';
867 if ( $lang !== null ) {
868 $query .= '&uselang=' . urlencode( $lang );
869 }
870 if ( $this->scriptDirUrl !== null ) {
871 return $this->makeUrl(
872 'title=' .
873 wfUrlencode( 'Image:' . $name ) .
874 "&$query" );
875 } else {
876 $descUrl = $this->getDescriptionUrl( $name );
877 if ( $descUrl ) {
878 return wfAppendQuery( $descUrl, $query );
879 } else {
880 return false;
881 }
882 }
883 }
884
890 public function getDescriptionStylesheetUrl() {
891 if ( $this->scriptDirUrl !== null ) {
892 // Must match canonical query parameter order for optimum caching
893 // See HTMLCacheUpdater::getUrls
894 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
895 }
896
897 return false;
898 }
899
917 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
918 $this->assertWritableRepo(); // fail out if read-only
919
920 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
921 if ( $status->successCount == 0 ) {
922 $status->setOK( false );
923 }
924
925 return $status;
926 }
927
941 public function storeBatch( array $triplets, $flags = 0 ) {
942 $this->assertWritableRepo(); // fail out if read-only
943
944 if ( $flags & self::DELETE_SOURCE ) {
945 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
946 }
947
948 $status = $this->newGood();
949 $backend = $this->backend; // convenience
950
951 $operations = [];
952 // Validate each triplet and get the store operation...
953 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
954 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
955 wfDebug( __METHOD__
956 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
957 );
958 // Resolve source path
959 if ( $src instanceof FSFile ) {
960 $op = 'store';
961 } else {
962 $src = $this->resolveToStoragePathIfVirtual( $src );
963 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
964 }
965 // Resolve destination path
966 $root = $this->getZonePath( $dstZone );
967 if ( !$root ) {
968 throw new RuntimeException( "Invalid zone: $dstZone" );
969 }
970 if ( !$this->validateFilename( $dstRel ) ) {
971 throw new RuntimeException( 'Validation error in $dstRel' );
972 }
973 $dstPath = "$root/$dstRel";
974 $dstDir = dirname( $dstPath );
975 // Create destination directories for this triplet
976 if ( !$this->initDirectory( $dstDir )->isOK() ) {
977 return $this->newFatal( 'directorycreateerror', $dstDir );
978 }
979
980 // Copy the source file to the destination
981 $operations[] = [
982 'op' => $op,
983 'src' => $src, // storage path (copy) or local file path (store)
984 'dst' => $dstPath,
985 'overwrite' => (bool)( $flags & self::OVERWRITE ),
986 'overwriteSame' => (bool)( $flags & self::OVERWRITE_SAME ),
987 ];
988 }
989
990 // Execute the store operation for each triplet
991 $opts = [ 'force' => true ];
992 if ( $flags & self::SKIP_LOCKING ) {
993 $opts['nonLocking'] = true;
994 }
995
996 return $status->merge( $backend->doOperations( $operations, $opts ) );
997 }
998
1009 public function cleanupBatch( array $files, $flags = 0 ) {
1010 $this->assertWritableRepo(); // fail out if read-only
1011
1012 $status = $this->newGood();
1013
1014 $operations = [];
1015 foreach ( $files as $path ) {
1016 if ( is_array( $path ) ) {
1017 // This is a pair, extract it
1018 [ $zone, $rel ] = $path;
1019 $path = $this->getZonePath( $zone ) . "/$rel";
1020 } else {
1021 // Resolve source to a storage path if virtual
1022 $path = $this->resolveToStoragePathIfVirtual( $path );
1023 }
1024 $operations[] = [ 'op' => 'delete', 'src' => $path ];
1025 }
1026 // Actually delete files from storage...
1027 $opts = [ 'force' => true ];
1028 if ( $flags & self::SKIP_LOCKING ) {
1029 $opts['nonLocking'] = true;
1030 }
1031
1032 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1033 }
1034
1052 final public function quickImport( $src, $dst, $options = null ) {
1053 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1054 }
1055
1070 public function quickImportBatch( array $triples ) {
1071 $status = $this->newGood();
1072 $operations = [];
1073 foreach ( $triples as $triple ) {
1074 [ $src, $dst ] = $triple;
1075 if ( $src instanceof FSFile ) {
1076 $op = 'store';
1077 } else {
1078 $src = $this->resolveToStoragePathIfVirtual( $src );
1079 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1080 }
1081 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1082
1083 if ( !isset( $triple[2] ) ) {
1084 $headers = [];
1085 } elseif ( is_string( $triple[2] ) ) {
1086 // back-compat
1087 $headers = [ 'Content-Disposition' => $triple[2] ];
1088 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1089 $headers = $triple[2]['headers'];
1090 } else {
1091 $headers = [];
1092 }
1093
1094 $operations[] = [
1095 'op' => $op,
1096 'src' => $src, // storage path (copy) or local path/FSFile (store)
1097 'dst' => $dst,
1098 'headers' => $headers
1099 ];
1100 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1101 }
1102
1103 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1104 }
1105
1114 final public function quickPurge( $path ) {
1115 return $this->quickPurgeBatch( [ $path ] );
1116 }
1117
1125 public function quickCleanDir( $dir ) {
1126 return $this->newGood()->merge(
1127 $this->backend->clean(
1128 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1129 )
1130 );
1131 }
1132
1141 public function quickPurgeBatch( array $paths ) {
1142 $status = $this->newGood();
1143 $operations = [];
1144 foreach ( $paths as $path ) {
1145 $operations[] = [
1146 'op' => 'delete',
1147 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1148 'ignoreMissingSource' => true
1149 ];
1150 }
1151 $status->merge( $this->backend->doQuickOperations( $operations ) );
1152
1153 return $status;
1154 }
1155
1166 public function storeTemp( $originalName, $srcPath ) {
1167 $this->assertWritableRepo(); // fail out if read-only
1168
1169 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1170 $hashPath = $this->getHashPath( $originalName );
1171 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1172 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1173
1174 $result = $this->quickImport( $srcPath, $virtualUrl );
1175 $result->value = $virtualUrl;
1176
1177 return $result;
1178 }
1179
1186 public function freeTemp( $virtualUrl ) {
1187 $this->assertWritableRepo(); // fail out if read-only
1188
1189 $temp = $this->getVirtualUrl( 'temp' );
1190 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1191 wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1192
1193 return false;
1194 }
1195
1196 return $this->quickPurge( $virtualUrl )->isOK();
1197 }
1198
1208 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1209 $this->assertWritableRepo(); // fail out if read-only
1210
1211 $status = $this->newGood();
1212
1213 $sources = [];
1214 foreach ( $srcPaths as $srcPath ) {
1215 // Resolve source to a storage path if virtual
1216 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1217 $sources[] = $source; // chunk to merge
1218 }
1219
1220 // Concatenate the chunks into one FS file
1221 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1222 $status->merge( $this->backend->concatenate( $params ) );
1223 if ( !$status->isOK() ) {
1224 return $status;
1225 }
1226
1227 // Delete the sources if required
1228 if ( $flags & self::DELETE_SOURCE ) {
1229 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1230 }
1231
1232 // Make sure status is OK, despite any quickPurgeBatch() fatals
1233 $status->setResult( true );
1234
1235 return $status;
1236 }
1237
1261 public function publish(
1262 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1263 ) {
1264 $this->assertWritableRepo(); // fail out if read-only
1265
1266 $status = $this->publishBatch(
1267 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1268 if ( $status->successCount == 0 ) {
1269 $status->setOK( false );
1270 }
1271 $status->value = $status->value[0] ?? false;
1272
1273 return $status;
1274 }
1275
1287 public function publishBatch( array $ntuples, $flags = 0 ) {
1288 $this->assertWritableRepo(); // fail out if read-only
1289
1290 $backend = $this->backend; // convenience
1291 // Try creating directories
1292 $this->initZones( 'public' );
1293
1294 $status = $this->newGood( [] );
1295
1296 $operations = [];
1297 $sourceFSFilesToDelete = []; // cleanup for disk source files
1298 // Validate each triplet and get the store operation...
1299 foreach ( $ntuples as $ntuple ) {
1300 [ $src, $dstRel, $archiveRel ] = $ntuple;
1301 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1302
1303 $options = $ntuple[3] ?? [];
1304 // Resolve source to a storage path if virtual
1305 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1306 if ( !$this->validateFilename( $dstRel ) ) {
1307 throw new RuntimeException( 'Validation error in $dstRel' );
1308 }
1309 if ( !$this->validateFilename( $archiveRel ) ) {
1310 throw new RuntimeException( 'Validation error in $archiveRel' );
1311 }
1312
1313 $publicRoot = $this->getZonePath( 'public' );
1314 $dstPath = "$publicRoot/$dstRel";
1315 $archivePath = "$publicRoot/$archiveRel";
1316
1317 $dstDir = dirname( $dstPath );
1318 $archiveDir = dirname( $archivePath );
1319 // Abort immediately on directory creation errors since they're likely to be repetitive
1320 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1321 return $this->newFatal( 'directorycreateerror', $dstDir );
1322 }
1323 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1324 return $this->newFatal( 'directorycreateerror', $archiveDir );
1325 }
1326
1327 // Set any desired headers to be use in GET/HEAD responses
1328 $headers = $options['headers'] ?? [];
1329
1330 // Archive destination file if it exists.
1331 // This will check if the archive file also exists and fail if does.
1332 // This is a check to avoid data loss. On Windows and Linux,
1333 // copy() will overwrite, so the existence check is vulnerable to
1334 // race conditions unless a functioning LockManager is used.
1335 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1336 $operations[] = [
1337 'op' => 'copy',
1338 'src' => $dstPath,
1339 'dst' => $archivePath,
1340 'ignoreMissingSource' => true
1341 ];
1342
1343 // Copy (or move) the source file to the destination
1344 if ( FileBackend::isStoragePath( $srcPath ) ) {
1345 $operations[] = [
1346 'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1347 'src' => $srcPath,
1348 'dst' => $dstPath,
1349 'overwrite' => true, // replace current
1350 'headers' => $headers
1351 ];
1352 } else {
1353 $operations[] = [
1354 'op' => 'store',
1355 'src' => $src, // storage path (copy) or local path/FSFile (store)
1356 'dst' => $dstPath,
1357 'overwrite' => true, // replace current
1358 'headers' => $headers
1359 ];
1360 if ( $flags & self::DELETE_SOURCE ) {
1361 $sourceFSFilesToDelete[] = $srcPath;
1362 }
1363 }
1364 }
1365
1366 // Execute the operations for each triplet
1367 $status->merge( $backend->doOperations( $operations ) );
1368 // Find out which files were archived...
1369 foreach ( $ntuples as $i => $ntuple ) {
1370 [ , , $archiveRel ] = $ntuple;
1371 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1372 if ( $this->fileExists( $archivePath ) ) {
1373 $status->value[$i] = 'archived';
1374 } else {
1375 $status->value[$i] = 'new';
1376 }
1377 }
1378 // Cleanup for disk source files...
1379 foreach ( $sourceFSFilesToDelete as $file ) {
1380 AtEase::suppressWarnings();
1381 unlink( $file ); // FS cleanup
1382 AtEase::restoreWarnings();
1383 }
1384
1385 return $status;
1386 }
1387
1395 protected function initDirectory( $dir ) {
1396 $path = $this->resolveToStoragePathIfVirtual( $dir );
1397 [ , $container, ] = FileBackend::splitStoragePath( $path );
1398
1399 $params = [ 'dir' => $path ];
1400 if ( $this->isPrivate
1401 || $container === $this->zones['deleted']['container']
1402 || $container === $this->zones['temp']['container']
1403 ) {
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;
1407 }
1408
1409 return $this->newGood()->merge( $this->backend->prepare( $params ) );
1410 }
1411
1418 public function cleanDir( $dir ) {
1419 $this->assertWritableRepo(); // fail out if read-only
1420
1421 return $this->newGood()->merge(
1422 $this->backend->clean(
1423 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1424 )
1425 );
1426 }
1427
1434 public function fileExists( $file ) {
1435 $result = $this->fileExistsBatch( [ $file ] );
1436
1437 return $result[0];
1438 }
1439
1447 public function fileExistsBatch( array $files ) {
1448 $paths = array_map( $this->resolveToStoragePathIfVirtual( ... ), $files );
1449 $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1450
1451 $result = [];
1452 foreach ( $paths as $key => $path ) {
1453 $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1454 }
1455
1456 return $result;
1457 }
1458
1469 public function delete( $srcRel, $archiveRel ) {
1470 $this->assertWritableRepo(); // fail out if read-only
1471
1472 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1473 }
1474
1491 public function deleteBatch( array $sourceDestPairs ) {
1492 $this->assertWritableRepo(); // fail out if read-only
1493
1494 // Try creating directories
1495 $this->initZones( [ 'public', 'deleted' ] );
1496
1497 $status = $this->newGood();
1498
1499 $backend = $this->backend; // convenience
1500 $operations = [];
1501 // Validate filenames and create archive directories
1502 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1503 if ( !$this->validateFilename( $srcRel ) ) {
1504 throw new RuntimeException( __METHOD__ . ':Validation error in $srcRel' );
1505 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1506 throw new RuntimeException( __METHOD__ . ':Validation error in $archiveRel' );
1507 }
1508
1509 $publicRoot = $this->getZonePath( 'public' );
1510 $srcPath = "{$publicRoot}/$srcRel";
1511
1512 $deletedRoot = $this->getZonePath( 'deleted' );
1513 $archivePath = "{$deletedRoot}/{$archiveRel}";
1514 $archiveDir = dirname( $archivePath ); // does not touch FS
1515
1516 // Create destination directories
1517 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1518 return $this->newFatal( 'directorycreateerror', $archiveDir );
1519 }
1520
1521 $operations[] = [
1522 'op' => 'move',
1523 'src' => $srcPath,
1524 'dst' => $archivePath,
1525 // We may have 2+ identical files being deleted,
1526 // all of which will map to the same destination file
1527 'overwriteSame' => true // also see T33792
1528 ];
1529 }
1530
1531 // Move the files by execute the operations for each pair.
1532 // We're now committed to returning an OK result, which will
1533 // lead to the files being moved in the DB also.
1534 $opts = [ 'force' => true ];
1535 return $status->merge( $backend->doOperations( $operations, $opts ) );
1536 }
1537
1544 public function cleanupDeletedBatch( array $storageKeys ) {
1545 $this->assertWritableRepo();
1546 }
1547
1555 public function getDeletedHashPath( $key ) {
1556 if ( strlen( $key ) < 31 ) {
1557 throw new InvalidArgumentException( "Invalid storage key '$key'." );
1558 }
1559 $path = '';
1560 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1561 $path .= $key[$i] . '/';
1562 }
1563
1564 return $path;
1565 }
1566
1574 protected function resolveToStoragePathIfVirtual( $path ) {
1575 if ( self::isVirtualUrl( $path ) ) {
1576 return $this->resolveVirtualUrl( $path );
1577 }
1578
1579 return $path;
1580 }
1581
1589 public function getLocalCopy( $virtualUrl ) {
1590 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1591
1592 return $this->backend->getLocalCopy( [ 'src' => $path ] );
1593 }
1594
1603 public function getLocalReference( $virtualUrl ) {
1604 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1605
1606 return $this->backend->getLocalReference( [ 'src' => $path ] );
1607 }
1608
1618 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1619 string $virtualUrl
1620 ) {
1621 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1622
1623 return $this->backend->addShellboxInputFile( $command, $boxedName, [ 'src' => $path ] );
1624 }
1625
1633 public function getFileProps( $virtualUrl ) {
1634 $fsFile = $this->getLocalReference( $virtualUrl );
1635 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1636 if ( $fsFile ) {
1637 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1638 } else {
1639 $props = $mwProps->newPlaceholderProps();
1640 }
1641
1642 return $props;
1643 }
1644
1651 public function getFileTimestamp( $virtualUrl ) {
1652 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1653
1654 return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1655 }
1656
1663 public function getFileSize( $virtualUrl ) {
1664 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1665
1666 return $this->backend->getFileSize( [ 'src' => $path ] );
1667 }
1668
1675 public function getFileSha1( $virtualUrl ) {
1676 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1677
1678 return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1679 }
1680
1690 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1691 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1692 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1693
1694 // T172851: HHVM does not flush the output properly, causing OOM
1695 ob_start( null, 1_048_576 );
1696 ob_implicit_flush( true );
1697
1698 $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1699
1700 // T186565: Close the buffer, unless it has already been closed
1701 // in HTTPFileStreamer::resetOutputBuffers().
1702 if ( ob_get_status() ) {
1703 ob_end_flush();
1704 }
1705
1706 return $status;
1707 }
1708
1717 public function enumFiles( $callback ) {
1718 $this->enumFilesInStorage( $callback );
1719 }
1720
1728 protected function enumFilesInStorage( $callback ) {
1729 $publicRoot = $this->getZonePath( 'public' );
1730 $numDirs = 1 << ( $this->hashLevels * 4 );
1731 // Use a priori assumptions about directory structure
1732 // to reduce the tree height of the scanning process.
1733 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1734 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1735 $path = $publicRoot;
1736 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1737 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1738 }
1739 $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1740 if ( $iterator === null ) {
1741 throw new RuntimeException( __METHOD__ . ': could not get file listing for ' . $path );
1742 }
1743 foreach ( $iterator as $name ) {
1744 // Each item returned is a public file
1745 $callback( "{$path}/{$name}" );
1746 }
1747 }
1748 }
1749
1756 public function validateFilename( $filename ) {
1757 if ( strval( $filename ) == '' ) {
1758 return false;
1759 }
1760
1761 return FileBackend::isPathTraversalFree( $filename );
1762 }
1763
1769 private function getErrorCleanupFunction() {
1770 switch ( $this->pathDisclosureProtection ) {
1771 case 'none':
1772 case 'simple': // b/c
1773 $callback = $this->passThrough( ... );
1774 break;
1775 default: // 'paranoid'
1776 $callback = $this->paranoidClean( ... );
1777 }
1778 return $callback;
1779 }
1780
1787 public function paranoidClean( $param ) {
1788 return '[hidden]';
1789 }
1790
1797 public function passThrough( $param ) {
1798 return $param;
1799 }
1800
1808 public function newFatal( $message, ...$parameters ) {
1809 $status = Status::newFatal( $message, ...$parameters );
1810 $status->cleanCallback = $this->getErrorCleanupFunction();
1811
1812 return $status;
1813 }
1814
1821 public function newGood( $value = null ) {
1822 $status = Status::newGood( $value );
1823 $status->cleanCallback = $this->getErrorCleanupFunction();
1824
1825 return $status;
1826 }
1827
1836 public function checkRedirect( $title ) {
1837 return false;
1838 }
1839
1847 public function invalidateImageRedirect( $title ) {
1848 }
1849
1855 public function getDisplayName() {
1856 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1857
1858 if ( $this->isLocal() ) {
1859 return $sitename;
1860 }
1861
1862 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1863 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1864 }
1865
1873 public function nameForThumb( $name ) {
1874 if ( strlen( $name ) > $this->abbrvThreshold ) {
1875 $ext = FileBackend::extensionFromPath( $name );
1876 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1877 }
1878
1879 return $name;
1880 }
1881
1887 public function isLocal() {
1888 return $this->getName() == 'local';
1889 }
1890
1902 public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1903 return false;
1904 }
1905
1917 public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1918 return $this->wanCache->makeKey(
1919 'filerepo-' . $kClassSuffix,
1920 $this->getName(),
1921 ...$components
1922 );
1923 }
1924
1933 public function getTempRepo() {
1934 return new TempFileRepo( [
1935 'name' => "{$this->name}-temp",
1936 'backend' => $this->backend,
1937 'zones' => [
1938 'public' => [
1939 // Same place storeTemp() uses in the base repo, though
1940 // the path hashing is mismatched, which is annoying.
1941 'container' => $this->zones['temp']['container'],
1942 'directory' => $this->zones['temp']['directory']
1943 ],
1944 'thumb' => [
1945 'container' => $this->zones['temp']['container'],
1946 'directory' => $this->zones['temp']['directory'] == ''
1947 ? 'thumb'
1948 : $this->zones['temp']['directory'] . '/thumb'
1949 ],
1950 'transcoded' => [
1951 'container' => $this->zones['temp']['container'],
1952 'directory' => $this->zones['temp']['directory'] == ''
1953 ? 'transcoded'
1954 : $this->zones['temp']['directory'] . '/transcoded'
1955 ]
1956 ],
1957 'hashLevels' => $this->hashLevels, // performance
1958 'isPrivate' => true // all in temp zone
1959 ] );
1960 }
1961
1968 public function getUploadStash( ?UserIdentity $user = null ) {
1969 return new UploadStash( $this, $user );
1970 }
1971
1978 protected function assertWritableRepo() {
1979 }
1980
1987 public function getInfo() {
1988 $ret = [
1989 'name' => $this->getName(),
1990 'displayname' => $this->getDisplayName(),
1991 'rootUrl' => $this->getZoneUrl( 'public' ),
1992 'local' => $this->isLocal(),
1993 ];
1994
1995 $optionalSettings = [
1996 'url',
1997 'thumbUrl',
1998 'initialCapital',
1999 'descBaseUrl',
2000 'scriptDirUrl',
2001 'articleUrl',
2002 'fetchDescription',
2003 'descriptionCacheExpiry',
2004 ];
2005 foreach ( $optionalSettings as $k ) {
2006 if ( $this->$k !== null ) {
2007 $ret[$k] = $this->$k;
2008 }
2009 }
2010 if ( $this->favicon !== null ) {
2011 // Expand any local path to full URL to improve API usability (T77093).
2012 $ret['favicon'] = MediaWikiServices::getInstance()->getUrlUtils()
2013 ->expand( $this->favicon );
2014 }
2015
2016 return $ret;
2017 }
2018
2023 public function hasSha1Storage() {
2024 return $this->hasSha1Storage;
2025 }
2026
2031 public function supportsSha1URLs() {
2032 return $this->supportsSha1URLs;
2033 }
2034}
2035
2037class_alias( FileRepo::class, 'FileRepo' );
const NS_FILE
Definition Defines.php:57
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...
MimeMagic helper wrapper.
Group all the pieces relevant to the context of a request into one instance.
Base class for file repositories.
Definition FileRepo.php:54
addShellboxInputFile(BoxedCommand $command, string $boxedName, string $virtualUrl)
Add a file to a Shellbox command as an input file.
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
static getHashPathForLevel( $name, $levels)
Definition FileRepo.php:772
findFile( $title, $options=[])
Find an instance of the named file created at the specified time Returns false if the file does not e...
Definition FileRepo.php:459
quickPurge( $path)
Purge a file from the repo.
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition FileRepo.php:890
fileExistsBatch(array $files)
Checks existence of an array of files.
initZones( $doZones=[])
Ensure that a single zone or list of zones is defined for usage.
Definition FileRepo.php:275
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition FileRepo.php:831
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
string null $descBaseUrl
URL of image description pages, e.g.
Definition FileRepo.php:93
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
findBySha1( $hash)
Get an array or iterator of file objects for files that have a given SHA-1 content hash.
Definition FileRepo.php:631
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition FileRepo.php:108
getNameFromTitle( $title)
Get the name of a file from its title.
Definition FileRepo.php:718
invalidateImageRedirect( $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition FileRepo.php:386
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:290
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition FileRepo.php:917
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition FileRepo.php:360
int $hashLevels
The number of directory levels for hash-based division of files.
Definition FileRepo.php:124
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
passThrough( $param)
Path disclosure protection function.
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition FileRepo.php:88
cleanDir( $dir)
Deletes a directory if empty.
bool $isPrivate
Whether all zones should be private (e.g.
Definition FileRepo.php:139
canTransformLocally()
Returns true if the repository can transform files locally.
Definition FileRepo.php:708
checkRedirect( $title)
Checks if there is a redirect named as $title.
newGood( $value=null)
Create a new good result.
findBySha1s(array $hashes)
Get an array of arrays or iterators of file objects for files that have the given SHA-1 content hashe...
Definition FileRepo.php:642
string false $url
Public zone URL.
Definition FileRepo.php:118
findFiles(array $items, $flags=0)
Find many files at once.
Definition FileRepo.php:542
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition FileRepo.php:115
null string $favicon
The URL to a favicon (optional, may be a server-local path URL).
Definition FileRepo.php:136
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
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...
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:761
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
getName()
Get the name of this repository, as specified by $info['name]' to the constructor.
Definition FileRepo.php:800
getInfo()
Return information about the repository.
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition FileRepo.php:424
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition FileRepo.php:865
assertWritableRepo()
Throw an exception if this repo is read-only by design.
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition FileRepo.php:155
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table.
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition FileRepo.php:302
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition FileRepo.php:739
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
Definition FileRepo.php:698
getUploadStash(?UserIdentity $user=null)
Get an UploadStash associated with this repo.
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition FileRepo.php:680
fileExists( $file)
Checks existence of a file.
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
getBackend()
Get the file backend instance.
Definition FileRepo.php:256
array $zones
Map of zones to config.
Definition FileRepo.php:80
__construct(?array $info=null)
Definition FileRepo.php:175
getThumbScriptUrl()
Get the URL of thumb.php.
Definition FileRepo.php:671
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition FileRepo.php:662
getTempRepo()
Get a temporary private FileRepo associated with this repo.
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
string null $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition FileRepo.php:98
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition FileRepo.php:153
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
callable false $oldFileFactoryKey
Override these in the base class.
Definition FileRepo.php:148
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
nameForThumb( $name)
Get the portion of the file that contains the origin file name.
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition FileRepo.php:400
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:121
string $thumbScriptUrl
URL of thumb.php.
Definition FileRepo.php:83
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition FileRepo.php:127
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:750
string null $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition FileRepo.php:101
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition FileRepo.php:689
newFatal( $message,... $parameters)
Create a new fatal error.
getDisplayName()
Get the human-readable name of the repo.
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
callable false $oldFileFactory
Override these in the base class.
Definition FileRepo.php:144
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition FileRepo.php:65
findFileFromKey( $sha1, $options=[])
Find an instance of the file with this key, created at the specified time Returns false if the file d...
Definition FileRepo.php:587
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
callable false $fileFactoryKey
Override these in the base class.
Definition FileRepo.php:146
callable $fileFactory
Override these in the base class.
Definition FileRepo.php:142
isLocal()
Returns true if this the local file repository.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition FileRepo.php:266
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition FileRepo.php:318
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition FileRepo.php:941
getHashLevels()
Get the number of hash directory levels.
Definition FileRepo.php:791
bool $disableLocalTransform
Disable local image scaling.
Definition FileRepo.php:158
getSharedCacheKey( $kClassSuffix,... $components)
Get a global, repository-qualified, WAN cache key.
quickCleanDir( $dir)
Deletes a directory if empty.
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
paranoidClean( $param)
Path disclosure protection function.
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:811
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
Definition FileRepo.php:133
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
Local file in the wiki's own database.
Definition LocalFile.php:79
File without associated database record.
FileRepo for temporary files created by FileRepo::getTempRepo()
A class containing constants representing the names of configuration variables.
const Sitename
Name constant for the Sitename setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
Represents a title within MediaWiki.
Definition Title.php:69
Library for creating and parsing MW-style timestamps.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
UploadStash is intended to accomplish a few things:
Class representing a non-directory file on the file system.
Definition FSFile.php:20
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Base class for all file backend classes (including multi-write backends).
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Multi-datacenter aware caching interface.
Represents the target of a wiki link.
Interface for objects (potentially) representing an editable wiki page.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:23
Interface for objects representing user identity.
Interface for database access objects.
$source