MediaWiki master
FileRepo.php
Go to the documentation of this file.
1<?php
20use Shellbox\Command\BoxedCommand;
21use Wikimedia\AtEase\AtEase;
27
57class FileRepo {
58 public const DELETE_SOURCE = 1;
59 public const OVERWRITE = 2;
60 public const OVERWRITE_SAME = 4;
61 public const SKIP_LOCKING = 8;
62
63 public const NAME_AND_TIME_ONLY = 1;
64
69
72
74 protected $hasSha1Storage = false;
75
77 protected $supportsSha1URLs = false;
78
80 protected $backend;
81
83 protected $zones = [];
84
86 protected $thumbScriptUrl;
87
92
96 protected $descBaseUrl;
97
101 protected $scriptDirUrl;
102
104 protected $articleUrl;
105
112
118 protected $pathDisclosureProtection = 'simple';
119
121 protected $url;
122
124 protected $thumbUrl;
125
127 protected $hashLevels;
128
131
137
139 protected $favicon = null;
140
142 protected $isPrivate;
143
145 protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
147 protected $oldFileFactory = false;
149 protected $fileFactoryKey = false;
151 protected $oldFileFactoryKey = false;
152
156 protected $thumbProxyUrl;
159
161 protected $disableLocalTransform = false;
162
164 protected $wanCache;
165
171 public $name;
172
178 public function __construct( ?array $info = null ) {
179 // Verify required settings presence
180 if (
181 $info === null
182 || !array_key_exists( 'name', $info )
183 || !array_key_exists( 'backend', $info )
184 ) {
185 throw new InvalidArgumentException( __CLASS__ .
186 " requires an array of options having both 'name' and 'backend' keys.\n" );
187 }
188
189 // Required settings
190 $this->name = $info['name'];
191 if ( $info['backend'] instanceof FileBackend ) {
192 $this->backend = $info['backend']; // useful for testing
193 } else {
194 $this->backend =
195 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
196 }
197
198 // Optional settings that can have no value
199 $optionalSettings = [
200 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
201 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
202 'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
203 ];
204 foreach ( $optionalSettings as $var ) {
205 if ( isset( $info[$var] ) ) {
206 $this->$var = $info[$var];
207 }
208 }
209
210 // Optional settings that have a default
211 $localCapitalLinks =
212 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
213 $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
214 if ( $localCapitalLinks && !$this->initialCapital ) {
215 // If the local wiki's file namespace requires an initial capital, but a foreign file
216 // repo doesn't, complications will result. Linker code will want to auto-capitalize the
217 // first letter of links to files, but those links might actually point to files on
218 // foreign wikis with initial-lowercase names. This combination is not likely to be
219 // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
220 // to include a foreign file repo with initialCapital false, set your local file
221 // namespace to not be capitalized either.
222 throw new InvalidArgumentException(
223 'File repos with initial capital false are not allowed on wikis where the File ' .
224 'namespace has initial capital true' );
225 }
226
227 $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
228 $defaultThumbUrl = $this->url ? $this->url . '/thumb' : false;
229 $this->thumbUrl = $info['thumbUrl'] ?? $defaultThumbUrl;
230 $this->hashLevels = $info['hashLevels'] ?? 2;
231 $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
232 $this->transformVia404 = !empty( $info['transformVia404'] );
233 $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
234 $this->isPrivate = !empty( $info['isPrivate'] );
235 // Give defaults for the basic zones...
236 $this->zones = $info['zones'] ?? [];
237 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
238 if ( !isset( $this->zones[$zone]['container'] ) ) {
239 $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
240 }
241 if ( !isset( $this->zones[$zone]['directory'] ) ) {
242 $this->zones[$zone]['directory'] = '';
243 }
244 if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
245 $this->zones[$zone]['urlsByExt'] = [];
246 }
247 }
248
249 $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
250
251 $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
252 }
253
259 public function getBackend() {
260 return $this->backend;
261 }
262
269 public function getReadOnlyReason() {
270 return $this->backend->getReadOnlyReason();
271 }
272
278 protected function initZones( $doZones = [] ): void {
279 foreach ( (array)$doZones as $zone ) {
280 $root = $this->getZonePath( $zone );
281 if ( $root === null ) {
282 throw new RuntimeException( "No '$zone' zone defined in the {$this->name} repo." );
283 }
284 }
285 }
286
293 public static function isVirtualUrl( $url ) {
294 return str_starts_with( $url, 'mwrepo://' );
295 }
296
305 public function getVirtualUrl( $suffix = false ) {
306 $path = 'mwrepo://' . $this->name;
307 if ( $suffix !== false ) {
308 $path .= '/' . rawurlencode( $suffix );
309 }
310
311 return $path;
312 }
313
321 public function getZoneUrl( $zone, $ext = null ) {
322 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
323 // standard public zones
324 if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
325 // custom URL for extension/zone
326 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
327 return $this->zones[$zone]['urlsByExt'][$ext];
328 } elseif ( isset( $this->zones[$zone]['url'] ) ) {
329 // custom URL for zone
330 return $this->zones[$zone]['url'];
331 }
332 }
333 switch ( $zone ) {
334 case 'public':
335 return $this->url;
336 case 'temp':
337 case 'deleted':
338 return false; // no public URL
339 case 'thumb':
340 return $this->thumbUrl;
341 case 'transcoded':
342 return "{$this->url}/transcoded";
343 default:
344 return false;
345 }
346 }
347
351 public function backendSupportsUnicodePaths() {
352 return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
353 }
354
363 public function resolveVirtualUrl( $url ) {
364 if ( !str_starts_with( $url, 'mwrepo://' ) ) {
365 throw new InvalidArgumentException( __METHOD__ . ': unknown protocol' );
366 }
367 $bits = explode( '/', substr( $url, 9 ), 3 );
368 if ( count( $bits ) != 3 ) {
369 throw new InvalidArgumentException( __METHOD__ . ": invalid mwrepo URL: $url" );
370 }
371 [ $repo, $zone, $rel ] = $bits;
372 if ( $repo !== $this->name ) {
373 throw new InvalidArgumentException( __METHOD__ . ": fetching from a foreign repo is not supported" );
374 }
375 $base = $this->getZonePath( $zone );
376 if ( !$base ) {
377 throw new InvalidArgumentException( __METHOD__ . ": invalid zone: $zone" );
378 }
379
380 return $base . '/' . rawurldecode( $rel );
381 }
382
389 protected function getZoneLocation( $zone ) {
390 if ( !isset( $this->zones[$zone] ) ) {
391 return [ null, null ]; // bogus
392 }
393
394 return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
395 }
396
403 public function getZonePath( $zone ) {
404 [ $container, $base ] = $this->getZoneLocation( $zone );
405 if ( $container === null || $base === null ) {
406 return null;
407 }
408 $backendName = $this->backend->getName();
409 if ( $base != '' ) { // may not be set
410 $base = "/{$base}";
411 }
412
413 return "mwstore://$backendName/{$container}{$base}";
414 }
415
427 public function newFile( $title, $time = false ) {
428 $title = File::normalizeTitle( $title );
429 if ( !$title ) {
430 return null;
431 }
432 if ( $time ) {
433 if ( $this->oldFileFactory ) {
434 return call_user_func( $this->oldFileFactory, $title, $this, $time );
435 } else {
436 return null;
437 }
438 } else {
439 return call_user_func( $this->fileFactory, $title, $this );
440 }
441 }
442
462 public function findFile( $title, $options = [] ) {
463 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
464 throw new InvalidArgumentException(
465 __METHOD__ . ' called with the `private` option set to something ' .
466 'other than an Authority object'
467 );
468 }
469
470 $title = File::normalizeTitle( $title );
471 if ( !$title ) {
472 return false;
473 }
474 if ( isset( $options['bypassCache'] ) ) {
475 $options['latest'] = $options['bypassCache']; // b/c
476 }
477 $time = $options['time'] ?? false;
478 $flags = !empty( $options['latest'] ) ? IDBAccessObject::READ_LATEST : 0;
479 # First try the current version of the file to see if it precedes the timestamp
480 $img = $this->newFile( $title );
481 if ( !$img ) {
482 return false;
483 }
484 $img->load( $flags );
485 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
486 return $img;
487 }
488 # Now try an old version of the file
489 if ( $time !== false ) {
490 $img = $this->newFile( $title, $time );
491 if ( $img ) {
492 $img->load( $flags );
493 if ( $img->exists() ) {
494 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
495 return $img; // always OK
496 } elseif (
497 // If its not empty, its an Authority object
498 !empty( $options['private'] ) &&
499 $img->userCan( File::DELETED_FILE, $options['private'] )
500 ) {
501 return $img;
502 }
503 }
504 }
505 }
506
507 # Now try redirects
508 if ( !empty( $options['ignoreRedirect'] ) ) {
509 return false;
510 }
511 $redir = $this->checkRedirect( $title );
512 if ( $redir && $title->getNamespace() === NS_FILE ) {
513 $img = $this->newFile( $redir );
514 if ( !$img ) {
515 return false;
516 }
517 $img->load( $flags );
518 if ( $img->exists() ) {
519 $img->redirectedFrom( $title->getDBkey() );
520
521 return $img;
522 }
523 }
524
525 return false;
526 }
527
545 public function findFiles( array $items, $flags = 0 ) {
546 $result = [];
547 foreach ( $items as $item ) {
548 if ( is_array( $item ) ) {
549 $title = $item['title'];
550 $options = $item;
551 unset( $options['title'] );
552
553 if (
554 !empty( $options['private'] ) &&
555 !( $options['private'] instanceof Authority )
556 ) {
557 $options['private'] = RequestContext::getMain()->getAuthority();
558 }
559 } else {
560 $title = $item;
561 $options = [];
562 }
563 $file = $this->findFile( $title, $options );
564 if ( $file ) {
565 $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
566 if ( $flags & self::NAME_AND_TIME_ONLY ) {
567 $result[$searchName] = [
568 'title' => $file->getTitle()->getDBkey(),
569 'timestamp' => $file->getTimestamp()
570 ];
571 } else {
572 $result[$searchName] = $file;
573 }
574 }
575 }
576
577 return $result;
578 }
579
590 public function findFileFromKey( $sha1, $options = [] ) {
591 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
592 throw new InvalidArgumentException(
593 __METHOD__ . ' called with the `private` option set to something ' .
594 'other than an Authority object'
595 );
596 }
597
598 $time = $options['time'] ?? false;
599 # First try to find a matching current version of a file...
600 if ( !$this->fileFactoryKey ) {
601 return false; // find-by-sha1 not supported
602 }
603 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
604 if ( $img && $img->exists() ) {
605 return $img;
606 }
607 # Now try to find a matching old version of a file...
608 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
609 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
610 if ( $img && $img->exists() ) {
611 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
612 return $img; // always OK
613 } elseif (
614 // If its not empty, its an Authority object
615 !empty( $options['private'] ) &&
616 $img->userCan( File::DELETED_FILE, $options['private'] )
617 ) {
618 return $img;
619 }
620 }
621 }
622
623 return false;
624 }
625
634 public function findBySha1( $hash ) {
635 return [];
636 }
637
645 public function findBySha1s( array $hashes ) {
646 $result = [];
647 foreach ( $hashes as $hash ) {
648 $files = $this->findBySha1( $hash );
649 if ( count( $files ) ) {
650 $result[$hash] = $files;
651 }
652 }
653
654 return $result;
655 }
656
665 public function findFilesByPrefix( $prefix, $limit ) {
666 return [];
667 }
668
674 public function getThumbScriptUrl() {
675 return $this->thumbScriptUrl;
676 }
677
683 public function getThumbProxyUrl() {
684 return $this->thumbProxyUrl;
685 }
686
692 public function getThumbProxySecret() {
693 return $this->thumbProxySecret;
694 }
695
701 public function canTransformVia404() {
702 return $this->transformVia404;
703 }
704
711 public function canTransformLocally() {
712 return !$this->disableLocalTransform;
713 }
714
721 public function getNameFromTitle( $title ) {
722 if (
723 $this->initialCapital !=
724 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
725 ) {
726 $name = $title->getDBkey();
727 if ( $this->initialCapital ) {
728 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
729 }
730 } else {
731 $name = $title->getDBkey();
732 }
733
734 return $name;
735 }
736
742 public function getRootDirectory() {
743 return $this->getZonePath( 'public' );
744 }
745
753 public function getHashPath( $name ) {
754 return self::getHashPathForLevel( $name, $this->hashLevels );
755 }
756
764 public function getTempHashPath( $suffix ) {
765 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
766 $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
767 return self::getHashPathForLevel( $name, $this->hashLevels );
768 }
769
775 protected static function getHashPathForLevel( $name, $levels ) {
776 if ( $levels == 0 ) {
777 return '';
778 } else {
779 $hash = md5( $name );
780 $path = '';
781 for ( $i = 1; $i <= $levels; $i++ ) {
782 $path .= substr( $hash, 0, $i ) . '/';
783 }
784
785 return $path;
786 }
787 }
788
794 public function getHashLevels() {
795 return $this->hashLevels;
796 }
797
803 public function getName() {
804 return $this->name;
805 }
806
814 public function makeUrl( $query = '', $entry = 'index' ) {
815 if ( isset( $this->scriptDirUrl ) ) {
816 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
817 }
818
819 return false;
820 }
821
834 public function getDescriptionUrl( $name ) {
835 $encName = wfUrlencode( $name );
836 if ( $this->descBaseUrl !== null ) {
837 # "http://example.com/wiki/File:"
838 return $this->descBaseUrl . $encName;
839 }
840 if ( $this->articleUrl !== null ) {
841 # "http://example.com/wiki/$1"
842 # We use "Image:" as the canonical namespace for
843 # compatibility across all MediaWiki versions.
844 return str_replace( '$1',
845 "Image:$encName", $this->articleUrl );
846 }
847 if ( $this->scriptDirUrl !== null ) {
848 # "http://example.com/w"
849 # We use "Image:" as the canonical namespace for
850 # compatibility across all MediaWiki versions,
851 # and just sort of hope index.php is right. ;)
852 return $this->makeUrl( "title=Image:$encName" );
853 }
854
855 return false;
856 }
857
868 public function getDescriptionRenderUrl( $name, $lang = null ) {
869 $query = 'action=render';
870 if ( $lang !== null ) {
871 $query .= '&uselang=' . urlencode( $lang );
872 }
873 if ( isset( $this->scriptDirUrl ) ) {
874 return $this->makeUrl(
875 'title=' .
876 wfUrlencode( 'Image:' . $name ) .
877 "&$query" );
878 } else {
879 $descUrl = $this->getDescriptionUrl( $name );
880 if ( $descUrl ) {
881 return wfAppendQuery( $descUrl, $query );
882 } else {
883 return false;
884 }
885 }
886 }
887
893 public function getDescriptionStylesheetUrl() {
894 if ( isset( $this->scriptDirUrl ) ) {
895 // Must match canonical query parameter order for optimum caching
896 // See HTMLCacheUpdater::getUrls
897 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
898 }
899
900 return false;
901 }
902
920 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
921 $this->assertWritableRepo(); // fail out if read-only
922
923 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
924 if ( $status->successCount == 0 ) {
925 $status->setOK( false );
926 }
927
928 return $status;
929 }
930
944 public function storeBatch( array $triplets, $flags = 0 ) {
945 $this->assertWritableRepo(); // fail out if read-only
946
947 if ( $flags & self::DELETE_SOURCE ) {
948 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
949 }
950
951 $status = $this->newGood();
952 $backend = $this->backend; // convenience
953
954 $operations = [];
955 // Validate each triplet and get the store operation...
956 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
957 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
958 wfDebug( __METHOD__
959 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
960 );
961 // Resolve source path
962 if ( $src instanceof FSFile ) {
963 $op = 'store';
964 } else {
965 $src = $this->resolveToStoragePathIfVirtual( $src );
966 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
967 }
968 // Resolve destination path
969 $root = $this->getZonePath( $dstZone );
970 if ( !$root ) {
971 throw new RuntimeException( "Invalid zone: $dstZone" );
972 }
973 if ( !$this->validateFilename( $dstRel ) ) {
974 throw new RuntimeException( 'Validation error in $dstRel' );
975 }
976 $dstPath = "$root/$dstRel";
977 $dstDir = dirname( $dstPath );
978 // Create destination directories for this triplet
979 if ( !$this->initDirectory( $dstDir )->isOK() ) {
980 return $this->newFatal( 'directorycreateerror', $dstDir );
981 }
982
983 // Copy the source file to the destination
984 $operations[] = [
985 'op' => $op,
986 'src' => $src, // storage path (copy) or local file path (store)
987 'dst' => $dstPath,
988 'overwrite' => (bool)( $flags & self::OVERWRITE ),
989 'overwriteSame' => (bool)( $flags & self::OVERWRITE_SAME ),
990 ];
991 }
992
993 // Execute the store operation for each triplet
994 $opts = [ 'force' => true ];
995 if ( $flags & self::SKIP_LOCKING ) {
996 $opts['nonLocking'] = true;
997 }
998
999 return $status->merge( $backend->doOperations( $operations, $opts ) );
1000 }
1001
1012 public function cleanupBatch( array $files, $flags = 0 ) {
1013 $this->assertWritableRepo(); // fail out if read-only
1014
1015 $status = $this->newGood();
1016
1017 $operations = [];
1018 foreach ( $files as $path ) {
1019 if ( is_array( $path ) ) {
1020 // This is a pair, extract it
1021 [ $zone, $rel ] = $path;
1022 $path = $this->getZonePath( $zone ) . "/$rel";
1023 } else {
1024 // Resolve source to a storage path if virtual
1025 $path = $this->resolveToStoragePathIfVirtual( $path );
1026 }
1027 $operations[] = [ 'op' => 'delete', 'src' => $path ];
1028 }
1029 // Actually delete files from storage...
1030 $opts = [ 'force' => true ];
1031 if ( $flags & self::SKIP_LOCKING ) {
1032 $opts['nonLocking'] = true;
1033 }
1034
1035 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1036 }
1037
1055 final public function quickImport( $src, $dst, $options = null ) {
1056 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1057 }
1058
1073 public function quickImportBatch( array $triples ) {
1074 $status = $this->newGood();
1075 $operations = [];
1076 foreach ( $triples as $triple ) {
1077 [ $src, $dst ] = $triple;
1078 if ( $src instanceof FSFile ) {
1079 $op = 'store';
1080 } else {
1081 $src = $this->resolveToStoragePathIfVirtual( $src );
1082 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1083 }
1084 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1085
1086 if ( !isset( $triple[2] ) ) {
1087 $headers = [];
1088 } elseif ( is_string( $triple[2] ) ) {
1089 // back-compat
1090 $headers = [ 'Content-Disposition' => $triple[2] ];
1091 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1092 $headers = $triple[2]['headers'];
1093 } else {
1094 $headers = [];
1095 }
1096
1097 $operations[] = [
1098 'op' => $op,
1099 'src' => $src, // storage path (copy) or local path/FSFile (store)
1100 'dst' => $dst,
1101 'headers' => $headers
1102 ];
1103 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1104 }
1105
1106 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1107 }
1108
1117 final public function quickPurge( $path ) {
1118 return $this->quickPurgeBatch( [ $path ] );
1119 }
1120
1128 public function quickCleanDir( $dir ) {
1129 return $this->newGood()->merge(
1130 $this->backend->clean(
1131 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1132 )
1133 );
1134 }
1135
1144 public function quickPurgeBatch( array $paths ) {
1145 $status = $this->newGood();
1146 $operations = [];
1147 foreach ( $paths as $path ) {
1148 $operations[] = [
1149 'op' => 'delete',
1150 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1151 'ignoreMissingSource' => true
1152 ];
1153 }
1154 $status->merge( $this->backend->doQuickOperations( $operations ) );
1155
1156 return $status;
1157 }
1158
1169 public function storeTemp( $originalName, $srcPath ) {
1170 $this->assertWritableRepo(); // fail out if read-only
1171
1172 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1173 $hashPath = $this->getHashPath( $originalName );
1174 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1175 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1176
1177 $result = $this->quickImport( $srcPath, $virtualUrl );
1178 $result->value = $virtualUrl;
1179
1180 return $result;
1181 }
1182
1189 public function freeTemp( $virtualUrl ) {
1190 $this->assertWritableRepo(); // fail out if read-only
1191
1192 $temp = $this->getVirtualUrl( 'temp' );
1193 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1194 wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1195
1196 return false;
1197 }
1198
1199 return $this->quickPurge( $virtualUrl )->isOK();
1200 }
1201
1211 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1212 $this->assertWritableRepo(); // fail out if read-only
1213
1214 $status = $this->newGood();
1215
1216 $sources = [];
1217 foreach ( $srcPaths as $srcPath ) {
1218 // Resolve source to a storage path if virtual
1219 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1220 $sources[] = $source; // chunk to merge
1221 }
1222
1223 // Concatenate the chunks into one FS file
1224 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1225 $status->merge( $this->backend->concatenate( $params ) );
1226 if ( !$status->isOK() ) {
1227 return $status;
1228 }
1229
1230 // Delete the sources if required
1231 if ( $flags & self::DELETE_SOURCE ) {
1232 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1233 }
1234
1235 // Make sure status is OK, despite any quickPurgeBatch() fatals
1236 $status->setResult( true );
1237
1238 return $status;
1239 }
1240
1264 public function publish(
1265 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1266 ) {
1267 $this->assertWritableRepo(); // fail out if read-only
1268
1269 $status = $this->publishBatch(
1270 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1271 if ( $status->successCount == 0 ) {
1272 $status->setOK( false );
1273 }
1274 $status->value = $status->value[0] ?? false;
1275
1276 return $status;
1277 }
1278
1290 public function publishBatch( array $ntuples, $flags = 0 ) {
1291 $this->assertWritableRepo(); // fail out if read-only
1292
1293 $backend = $this->backend; // convenience
1294 // Try creating directories
1295 $this->initZones( 'public' );
1296
1297 $status = $this->newGood( [] );
1298
1299 $operations = [];
1300 $sourceFSFilesToDelete = []; // cleanup for disk source files
1301 // Validate each triplet and get the store operation...
1302 foreach ( $ntuples as $ntuple ) {
1303 [ $src, $dstRel, $archiveRel ] = $ntuple;
1304 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1305
1306 $options = $ntuple[3] ?? [];
1307 // Resolve source to a storage path if virtual
1308 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1309 if ( !$this->validateFilename( $dstRel ) ) {
1310 throw new RuntimeException( 'Validation error in $dstRel' );
1311 }
1312 if ( !$this->validateFilename( $archiveRel ) ) {
1313 throw new RuntimeException( 'Validation error in $archiveRel' );
1314 }
1315
1316 $publicRoot = $this->getZonePath( 'public' );
1317 $dstPath = "$publicRoot/$dstRel";
1318 $archivePath = "$publicRoot/$archiveRel";
1319
1320 $dstDir = dirname( $dstPath );
1321 $archiveDir = dirname( $archivePath );
1322 // Abort immediately on directory creation errors since they're likely to be repetitive
1323 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1324 return $this->newFatal( 'directorycreateerror', $dstDir );
1325 }
1326 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1327 return $this->newFatal( 'directorycreateerror', $archiveDir );
1328 }
1329
1330 // Set any desired headers to be use in GET/HEAD responses
1331 $headers = $options['headers'] ?? [];
1332
1333 // Archive destination file if it exists.
1334 // This will check if the archive file also exists and fail if does.
1335 // This is a check to avoid data loss. On Windows and Linux,
1336 // copy() will overwrite, so the existence check is vulnerable to
1337 // race conditions unless a functioning LockManager is used.
1338 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1339 $operations[] = [
1340 'op' => 'copy',
1341 'src' => $dstPath,
1342 'dst' => $archivePath,
1343 'ignoreMissingSource' => true
1344 ];
1345
1346 // Copy (or move) the source file to the destination
1347 if ( FileBackend::isStoragePath( $srcPath ) ) {
1348 $operations[] = [
1349 'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1350 'src' => $srcPath,
1351 'dst' => $dstPath,
1352 'overwrite' => true, // replace current
1353 'headers' => $headers
1354 ];
1355 } else {
1356 $operations[] = [
1357 'op' => 'store',
1358 'src' => $src, // storage path (copy) or local path/FSFile (store)
1359 'dst' => $dstPath,
1360 'overwrite' => true, // replace current
1361 'headers' => $headers
1362 ];
1363 if ( $flags & self::DELETE_SOURCE ) {
1364 $sourceFSFilesToDelete[] = $srcPath;
1365 }
1366 }
1367 }
1368
1369 // Execute the operations for each triplet
1370 $status->merge( $backend->doOperations( $operations ) );
1371 // Find out which files were archived...
1372 foreach ( $ntuples as $i => $ntuple ) {
1373 [ , , $archiveRel ] = $ntuple;
1374 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1375 if ( $this->fileExists( $archivePath ) ) {
1376 $status->value[$i] = 'archived';
1377 } else {
1378 $status->value[$i] = 'new';
1379 }
1380 }
1381 // Cleanup for disk source files...
1382 foreach ( $sourceFSFilesToDelete as $file ) {
1383 AtEase::suppressWarnings();
1384 unlink( $file ); // FS cleanup
1385 AtEase::restoreWarnings();
1386 }
1387
1388 return $status;
1389 }
1390
1398 protected function initDirectory( $dir ) {
1399 $path = $this->resolveToStoragePathIfVirtual( $dir );
1400 [ , $container, ] = FileBackend::splitStoragePath( $path );
1401
1402 $params = [ 'dir' => $path ];
1403 if ( $this->isPrivate
1404 || $container === $this->zones['deleted']['container']
1405 || $container === $this->zones['temp']['container']
1406 ) {
1407 # Take all available measures to prevent web accessibility of new deleted
1408 # directories, in case the user has not configured offline storage
1409 $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1410 }
1411
1412 return $this->newGood()->merge( $this->backend->prepare( $params ) );
1413 }
1414
1421 public function cleanDir( $dir ) {
1422 $this->assertWritableRepo(); // fail out if read-only
1423
1424 return $this->newGood()->merge(
1425 $this->backend->clean(
1426 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1427 )
1428 );
1429 }
1430
1437 public function fileExists( $file ) {
1438 $result = $this->fileExistsBatch( [ $file ] );
1439
1440 return $result[0];
1441 }
1442
1450 public function fileExistsBatch( array $files ) {
1451 $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1452 $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1453
1454 $result = [];
1455 foreach ( $paths as $key => $path ) {
1456 $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1457 }
1458
1459 return $result;
1460 }
1461
1472 public function delete( $srcRel, $archiveRel ) {
1473 $this->assertWritableRepo(); // fail out if read-only
1474
1475 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1476 }
1477
1494 public function deleteBatch( array $sourceDestPairs ) {
1495 $this->assertWritableRepo(); // fail out if read-only
1496
1497 // Try creating directories
1498 $this->initZones( [ 'public', 'deleted' ] );
1499
1500 $status = $this->newGood();
1501
1502 $backend = $this->backend; // convenience
1503 $operations = [];
1504 // Validate filenames and create archive directories
1505 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1506 if ( !$this->validateFilename( $srcRel ) ) {
1507 throw new RuntimeException( __METHOD__ . ':Validation error in $srcRel' );
1508 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1509 throw new RuntimeException( __METHOD__ . ':Validation error in $archiveRel' );
1510 }
1511
1512 $publicRoot = $this->getZonePath( 'public' );
1513 $srcPath = "{$publicRoot}/$srcRel";
1514
1515 $deletedRoot = $this->getZonePath( 'deleted' );
1516 $archivePath = "{$deletedRoot}/{$archiveRel}";
1517 $archiveDir = dirname( $archivePath ); // does not touch FS
1518
1519 // Create destination directories
1520 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1521 return $this->newFatal( 'directorycreateerror', $archiveDir );
1522 }
1523
1524 $operations[] = [
1525 'op' => 'move',
1526 'src' => $srcPath,
1527 'dst' => $archivePath,
1528 // We may have 2+ identical files being deleted,
1529 // all of which will map to the same destination file
1530 'overwriteSame' => true // also see T33792
1531 ];
1532 }
1533
1534 // Move the files by execute the operations for each pair.
1535 // We're now committed to returning an OK result, which will
1536 // lead to the files being moved in the DB also.
1537 $opts = [ 'force' => true ];
1538 return $status->merge( $backend->doOperations( $operations, $opts ) );
1539 }
1540
1547 public function cleanupDeletedBatch( array $storageKeys ) {
1548 $this->assertWritableRepo();
1549 }
1550
1558 public function getDeletedHashPath( $key ) {
1559 if ( strlen( $key ) < 31 ) {
1560 throw new InvalidArgumentException( "Invalid storage key '$key'." );
1561 }
1562 $path = '';
1563 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1564 $path .= $key[$i] . '/';
1565 }
1566
1567 return $path;
1568 }
1569
1577 protected function resolveToStoragePathIfVirtual( $path ) {
1578 if ( self::isVirtualUrl( $path ) ) {
1579 return $this->resolveVirtualUrl( $path );
1580 }
1581
1582 return $path;
1583 }
1584
1592 public function getLocalCopy( $virtualUrl ) {
1593 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1594
1595 return $this->backend->getLocalCopy( [ 'src' => $path ] );
1596 }
1597
1606 public function getLocalReference( $virtualUrl ) {
1607 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1608
1609 return $this->backend->getLocalReference( [ 'src' => $path ] );
1610 }
1611
1621 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1622 string $virtualUrl
1623 ) {
1624 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1625
1626 return $this->backend->addShellboxInputFile( $command, $boxedName, [ 'src' => $path ] );
1627 }
1628
1636 public function getFileProps( $virtualUrl ) {
1637 $fsFile = $this->getLocalReference( $virtualUrl );
1638 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1639 if ( $fsFile ) {
1640 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1641 } else {
1642 $props = $mwProps->newPlaceholderProps();
1643 }
1644
1645 return $props;
1646 }
1647
1654 public function getFileTimestamp( $virtualUrl ) {
1655 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1656
1657 return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1658 }
1659
1666 public function getFileSize( $virtualUrl ) {
1667 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1668
1669 return $this->backend->getFileSize( [ 'src' => $path ] );
1670 }
1671
1678 public function getFileSha1( $virtualUrl ) {
1679 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1680
1681 return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1682 }
1683
1693 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1694 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1695 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1696
1697 // T172851: HHVM does not flush the output properly, causing OOM
1698 ob_start( null, 1_048_576 );
1699 ob_implicit_flush( true );
1700
1701 $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1702
1703 // T186565: Close the buffer, unless it has already been closed
1704 // in HTTPFileStreamer::resetOutputBuffers().
1705 if ( ob_get_status() ) {
1706 ob_end_flush();
1707 }
1708
1709 return $status;
1710 }
1711
1720 public function enumFiles( $callback ) {
1721 $this->enumFilesInStorage( $callback );
1722 }
1723
1731 protected function enumFilesInStorage( $callback ) {
1732 $publicRoot = $this->getZonePath( 'public' );
1733 $numDirs = 1 << ( $this->hashLevels * 4 );
1734 // Use a priori assumptions about directory structure
1735 // to reduce the tree height of the scanning process.
1736 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1737 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1738 $path = $publicRoot;
1739 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1740 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1741 }
1742 $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1743 if ( $iterator === null ) {
1744 throw new RuntimeException( __METHOD__ . ': could not get file listing for ' . $path );
1745 }
1746 foreach ( $iterator as $name ) {
1747 // Each item returned is a public file
1748 call_user_func( $callback, "{$path}/{$name}" );
1749 }
1750 }
1751 }
1752
1759 public function validateFilename( $filename ) {
1760 if ( strval( $filename ) == '' ) {
1761 return false;
1762 }
1763
1764 return FileBackend::isPathTraversalFree( $filename );
1765 }
1766
1772 private function getErrorCleanupFunction() {
1773 switch ( $this->pathDisclosureProtection ) {
1774 case 'none':
1775 case 'simple': // b/c
1776 $callback = [ $this, 'passThrough' ];
1777 break;
1778 default: // 'paranoid'
1779 $callback = [ $this, 'paranoidClean' ];
1780 }
1781 return $callback;
1782 }
1783
1790 public function paranoidClean( $param ) {
1791 return '[hidden]';
1792 }
1793
1800 public function passThrough( $param ) {
1801 return $param;
1802 }
1803
1811 public function newFatal( $message, ...$parameters ) {
1812 $status = Status::newFatal( $message, ...$parameters );
1813 $status->cleanCallback = $this->getErrorCleanupFunction();
1814
1815 return $status;
1816 }
1817
1824 public function newGood( $value = null ) {
1825 $status = Status::newGood( $value );
1826 $status->cleanCallback = $this->getErrorCleanupFunction();
1827
1828 return $status;
1829 }
1830
1839 public function checkRedirect( $title ) {
1840 return false;
1841 }
1842
1850 public function invalidateImageRedirect( $title ) {
1851 }
1852
1858 public function getDisplayName() {
1859 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1860
1861 if ( $this->isLocal() ) {
1862 return $sitename;
1863 }
1864
1865 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1866 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1867 }
1868
1876 public function nameForThumb( $name ) {
1877 if ( strlen( $name ) > $this->abbrvThreshold ) {
1878 $ext = FileBackend::extensionFromPath( $name );
1879 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1880 }
1881
1882 return $name;
1883 }
1884
1890 public function isLocal() {
1891 return $this->getName() == 'local';
1892 }
1893
1905 public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1906 return false;
1907 }
1908
1920 public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1921 return $this->wanCache->makeKey(
1922 'filerepo-' . $kClassSuffix,
1923 $this->getName(),
1924 ...$components
1925 );
1926 }
1927
1936 public function getTempRepo() {
1937 return new TempFileRepo( [
1938 'name' => "{$this->name}-temp",
1939 'backend' => $this->backend,
1940 'zones' => [
1941 'public' => [
1942 // Same place storeTemp() uses in the base repo, though
1943 // the path hashing is mismatched, which is annoying.
1944 'container' => $this->zones['temp']['container'],
1945 'directory' => $this->zones['temp']['directory']
1946 ],
1947 'thumb' => [
1948 'container' => $this->zones['temp']['container'],
1949 'directory' => $this->zones['temp']['directory'] == ''
1950 ? 'thumb'
1951 : $this->zones['temp']['directory'] . '/thumb'
1952 ],
1953 'transcoded' => [
1954 'container' => $this->zones['temp']['container'],
1955 'directory' => $this->zones['temp']['directory'] == ''
1956 ? 'transcoded'
1957 : $this->zones['temp']['directory'] . '/transcoded'
1958 ]
1959 ],
1960 'hashLevels' => $this->hashLevels, // performance
1961 'isPrivate' => true // all in temp zone
1962 ] );
1963 }
1964
1971 public function getUploadStash( ?UserIdentity $user = null ) {
1972 return new UploadStash( $this, $user );
1973 }
1974
1981 protected function assertWritableRepo() {
1982 }
1983
1990 public function getInfo() {
1991 $ret = [
1992 'name' => $this->getName(),
1993 'displayname' => $this->getDisplayName(),
1994 'rootUrl' => $this->getZoneUrl( 'public' ),
1995 'local' => $this->isLocal(),
1996 ];
1997
1998 $optionalSettings = [
1999 'url',
2000 'thumbUrl',
2001 'initialCapital',
2002 'descBaseUrl',
2003 'scriptDirUrl',
2004 'articleUrl',
2005 'fetchDescription',
2006 'descriptionCacheExpiry',
2007 ];
2008 foreach ( $optionalSettings as $k ) {
2009 if ( isset( $this->$k ) ) {
2010 $ret[$k] = $this->$k;
2011 }
2012 }
2013 if ( isset( $this->favicon ) ) {
2014 // Expand any local path to full URL to improve API usability (T77093).
2015 $ret['favicon'] = MediaWikiServices::getInstance()->getUrlUtils()
2016 ->expand( $this->favicon );
2017 }
2018
2019 return $ret;
2020 }
2021
2026 public function hasSha1Storage() {
2027 return $this->hasSha1Storage;
2028 }
2029
2034 public function supportsSha1URLs() {
2035 return $this->supportsSha1URLs;
2036 }
2037}
const NS_FILE
Definition Defines.php:71
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
array $params
The job parameters.
Base class for file repositories.
Definition FileRepo.php:57
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition FileRepo.php:118
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:764
int $hashLevels
The number of directory levels for hash-based division of files.
Definition FileRepo.php:127
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.
const OVERWRITE_SAME
Definition FileRepo.php:60
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition FileRepo.php:363
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.
Definition FileRepo.php:545
newFatal( $message,... $parameters)
Create a new fatal error.
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition FileRepo.php:683
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition FileRepo.php:389
fileExists( $file)
Checks existence of a file.
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
bool $supportsSha1URLs
Definition FileRepo.php:77
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.
Definition FileRepo.php:742
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
newGood( $value=null)
Create a new good result.
getUploadStash(?UserIdentity $user=null)
Get an UploadStash associated with this repo.
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition FileRepo.php:665
getHashLevels()
Get the number of hash directory levels.
Definition FileRepo.php:794
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition FileRepo.php:158
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.
Definition FileRepo.php:803
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition FileRepo.php:920
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:462
callable false $oldFileFactoryKey
Override these in the base class.
Definition FileRepo.php:151
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition FileRepo.php:305
const NAME_AND_TIME_ONLY
Definition FileRepo.php:63
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)
Definition FileRepo.php:775
array $zones
Map of zones to config.
Definition FileRepo.php:83
callable false $fileFactoryKey
Override these in the base class.
Definition FileRepo.php:149
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.
Definition FileRepo.php:161
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition FileRepo.php:944
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
canTransformLocally()
Returns true if the repository can transform files locally.
Definition FileRepo.php:711
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.
Definition FileRepo.php:136
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:814
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:645
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition FileRepo.php:156
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
FileBackend $backend
Definition FileRepo.php:80
null string $favicon
The URL to a favicon (optional, may be a server-local path URL).
Definition FileRepo.php:139
fileExistsBatch(array $files)
Checks existence of an array of files.
int $descriptionCacheExpiry
Definition FileRepo.php:71
paranoidClean( $param)
Path disclosure protection function.
WANObjectCache $wanCache
Definition FileRepo.php:164
const SKIP_LOCKING
Definition FileRepo.php:61
initZones( $doZones=[])
Ensure that a single zone or list of zones is defined for usage.
Definition FileRepo.php:278
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
const OVERWRITE
Definition FileRepo.php:59
isLocal()
Returns true if this the local file repository.
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition FileRepo.php:403
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition FileRepo.php:834
cleanDir( $dir)
Deletes a directory if empty.
addShellboxInputFile(BoxedCommand $command, string $boxedName, string $virtualUrl)
Add a file to a Shellbox command as an input file.
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
bool $hasSha1Storage
Definition FileRepo.php:74
const DELETE_SOURCE
Definition FileRepo.php:58
getNameFromTitle( $title)
Get the name of a file from its title.
Definition FileRepo.php:721
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.
Definition FileRepo.php:692
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition FileRepo.php:68
string false $url
Public zone URL.
Definition FileRepo.php:121
callable $fileFactory
Override these in the base class.
Definition FileRepo.php:145
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:293
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition FileRepo.php:893
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition FileRepo.php:91
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.
Definition FileRepo.php:142
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition FileRepo.php:101
string $descBaseUrl
URL of image description pages, e.g.
Definition FileRepo.php:96
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition FileRepo.php:321
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition FileRepo.php:269
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition FileRepo.php:427
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.
Definition FileRepo.php:701
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...
Definition FileRepo.php:590
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition FileRepo.php:130
string $thumbScriptUrl
URL of thumb.php.
Definition FileRepo.php:86
backendSupportsUnicodePaths()
Definition FileRepo.php:351
string $name
Definition FileRepo.php:171
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:124
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition FileRepo.php:111
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.
Definition FileRepo.php:753
callable false $oldFileFactory
Override these in the base class.
Definition FileRepo.php:147
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition FileRepo.php:104
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition FileRepo.php:868
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.
Definition FileRepo.php:634
__construct(?array $info=null)
Definition FileRepo.php:178
getBackend()
Get the file backend instance.
Definition FileRepo.php:259
getInfo()
Return information about the repository.
getThumbScriptUrl()
Get the URL of thumb.php.
Definition FileRepo.php:674
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.
Service locator for MediaWiki core services.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
Represents a title within MediaWiki.
Definition Title.php:78
Library for creating and parsing MW-style timestamps.
FileRepo for temporary files created by FileRepo::getTempRepo()
UploadStash is intended to accomplish a few things:
Class representing a non-directory file on the file system.
Definition FSFile.php:34
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).
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:37
Interface for objects representing user identity.
Interface for database access objects.
$source