MediaWiki master
FileRepo.php
Go to the documentation of this file.
1<?php
20use Wikimedia\AtEase\AtEase;
22
52class FileRepo {
53 public const DELETE_SOURCE = 1;
54 public const OVERWRITE = 2;
55 public const OVERWRITE_SAME = 4;
56 public const SKIP_LOCKING = 8;
57
58 public const NAME_AND_TIME_ONLY = 1;
59
64
67
69 protected $hasSha1Storage = false;
70
72 protected $supportsSha1URLs = false;
73
75 protected $backend;
76
78 protected $zones = [];
79
81 protected $thumbScriptUrl;
82
87
91 protected $descBaseUrl;
92
96 protected $scriptDirUrl;
97
99 protected $articleUrl;
100
107
113 protected $pathDisclosureProtection = 'simple';
114
116 protected $url;
117
119 protected $thumbUrl;
120
122 protected $hashLevels;
123
126
132
134 protected $favicon = null;
135
137 protected $isPrivate;
138
140 protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
142 protected $oldFileFactory = false;
144 protected $fileFactoryKey = false;
146 protected $oldFileFactoryKey = false;
147
151 protected $thumbProxyUrl;
154
156 protected $disableLocalTransform = false;
157
159 protected $wanCache;
160
166 public $name;
167
173 public function __construct( array $info = null ) {
174 // Verify required settings presence
175 if (
176 $info === null
177 || !array_key_exists( 'name', $info )
178 || !array_key_exists( 'backend', $info )
179 ) {
180 throw new InvalidArgumentException( __CLASS__ .
181 " requires an array of options having both 'name' and 'backend' keys.\n" );
182 }
183
184 // Required settings
185 $this->name = $info['name'];
186 if ( $info['backend'] instanceof FileBackend ) {
187 $this->backend = $info['backend']; // useful for testing
188 } else {
189 $this->backend =
190 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
191 }
192
193 // Optional settings that can have no value
194 $optionalSettings = [
195 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
196 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
197 'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
198 ];
199 foreach ( $optionalSettings as $var ) {
200 if ( isset( $info[$var] ) ) {
201 $this->$var = $info[$var];
202 }
203 }
204
205 // Optional settings that have a default
206 $localCapitalLinks =
207 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
208 $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
209 if ( $localCapitalLinks && !$this->initialCapital ) {
210 // If the local wiki's file namespace requires an initial capital, but a foreign file
211 // repo doesn't, complications will result. Linker code will want to auto-capitalize the
212 // first letter of links to files, but those links might actually point to files on
213 // foreign wikis with initial-lowercase names. This combination is not likely to be
214 // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
215 // to include a foreign file repo with initialCapital false, set your local file
216 // namespace to not be capitalized either.
217 throw new InvalidArgumentException(
218 'File repos with initial capital false are not allowed on wikis where the File ' .
219 'namespace has initial capital true' );
220 }
221
222 $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
223 $defaultThumbUrl = $this->url ? $this->url . '/thumb' : false;
224 $this->thumbUrl = $info['thumbUrl'] ?? $defaultThumbUrl;
225 $this->hashLevels = $info['hashLevels'] ?? 2;
226 $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
227 $this->transformVia404 = !empty( $info['transformVia404'] );
228 $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
229 $this->isPrivate = !empty( $info['isPrivate'] );
230 // Give defaults for the basic zones...
231 $this->zones = $info['zones'] ?? [];
232 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
233 if ( !isset( $this->zones[$zone]['container'] ) ) {
234 $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
235 }
236 if ( !isset( $this->zones[$zone]['directory'] ) ) {
237 $this->zones[$zone]['directory'] = '';
238 }
239 if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
240 $this->zones[$zone]['urlsByExt'] = [];
241 }
242 }
243
244 $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
245
246 $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
247 }
248
254 public function getBackend() {
255 return $this->backend;
256 }
257
264 public function getReadOnlyReason() {
265 return $this->backend->getReadOnlyReason();
266 }
267
273 protected function initZones( $doZones = [] ): void {
274 foreach ( (array)$doZones as $zone ) {
275 $root = $this->getZonePath( $zone );
276 if ( $root === null ) {
277 throw new RuntimeException( "No '$zone' zone defined in the {$this->name} repo." );
278 }
279 }
280 }
281
288 public static function isVirtualUrl( $url ) {
289 return str_starts_with( $url, 'mwrepo://' );
290 }
291
300 public function getVirtualUrl( $suffix = false ) {
301 $path = 'mwrepo://' . $this->name;
302 if ( $suffix !== false ) {
303 $path .= '/' . rawurlencode( $suffix );
304 }
305
306 return $path;
307 }
308
316 public function getZoneUrl( $zone, $ext = null ) {
317 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
318 // standard public zones
319 if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
320 // custom URL for extension/zone
321 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
322 return $this->zones[$zone]['urlsByExt'][$ext];
323 } elseif ( isset( $this->zones[$zone]['url'] ) ) {
324 // custom URL for zone
325 return $this->zones[$zone]['url'];
326 }
327 }
328 switch ( $zone ) {
329 case 'public':
330 return $this->url;
331 case 'temp':
332 case 'deleted':
333 return false; // no public URL
334 case 'thumb':
335 return $this->thumbUrl;
336 case 'transcoded':
337 return "{$this->url}/transcoded";
338 default:
339 return false;
340 }
341 }
342
346 public function backendSupportsUnicodePaths() {
347 return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
348 }
349
358 public function resolveVirtualUrl( $url ) {
359 if ( !str_starts_with( $url, 'mwrepo://' ) ) {
360 throw new InvalidArgumentException( __METHOD__ . ': unknown protocol' );
361 }
362 $bits = explode( '/', substr( $url, 9 ), 3 );
363 if ( count( $bits ) != 3 ) {
364 throw new InvalidArgumentException( __METHOD__ . ": invalid mwrepo URL: $url" );
365 }
366 [ $repo, $zone, $rel ] = $bits;
367 if ( $repo !== $this->name ) {
368 throw new InvalidArgumentException( __METHOD__ . ": fetching from a foreign repo is not supported" );
369 }
370 $base = $this->getZonePath( $zone );
371 if ( !$base ) {
372 throw new InvalidArgumentException( __METHOD__ . ": invalid zone: $zone" );
373 }
374
375 return $base . '/' . rawurldecode( $rel );
376 }
377
384 protected function getZoneLocation( $zone ) {
385 if ( !isset( $this->zones[$zone] ) ) {
386 return [ null, null ]; // bogus
387 }
388
389 return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
390 }
391
398 public function getZonePath( $zone ) {
399 [ $container, $base ] = $this->getZoneLocation( $zone );
400 if ( $container === null || $base === null ) {
401 return null;
402 }
403 $backendName = $this->backend->getName();
404 if ( $base != '' ) { // may not be set
405 $base = "/{$base}";
406 }
407
408 return "mwstore://$backendName/{$container}{$base}";
409 }
410
422 public function newFile( $title, $time = false ) {
423 $title = File::normalizeTitle( $title );
424 if ( !$title ) {
425 return null;
426 }
427 if ( $time ) {
428 if ( $this->oldFileFactory ) {
429 return call_user_func( $this->oldFileFactory, $title, $this, $time );
430 } else {
431 return null;
432 }
433 } else {
434 return call_user_func( $this->fileFactory, $title, $this );
435 }
436 }
437
457 public function findFile( $title, $options = [] ) {
458 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
459 throw new InvalidArgumentException(
460 __METHOD__ . ' called with the `private` option set to something ' .
461 'other than an Authority object'
462 );
463 }
464
465 $title = File::normalizeTitle( $title );
466 if ( !$title ) {
467 return false;
468 }
469 if ( isset( $options['bypassCache'] ) ) {
470 $options['latest'] = $options['bypassCache']; // b/c
471 }
472 $time = $options['time'] ?? false;
473 $flags = !empty( $options['latest'] ) ? IDBAccessObject::READ_LATEST : 0;
474 # First try the current version of the file to see if it precedes the timestamp
475 $img = $this->newFile( $title );
476 if ( !$img ) {
477 return false;
478 }
479 $img->load( $flags );
480 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
481 return $img;
482 }
483 # Now try an old version of the file
484 if ( $time !== false ) {
485 $img = $this->newFile( $title, $time );
486 if ( $img ) {
487 $img->load( $flags );
488 if ( $img->exists() ) {
489 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
490 return $img; // always OK
491 } elseif (
492 // If its not empty, its an Authority object
493 !empty( $options['private'] ) &&
494 $img->userCan( File::DELETED_FILE, $options['private'] )
495 ) {
496 return $img;
497 }
498 }
499 }
500 }
501
502 # Now try redirects
503 if ( !empty( $options['ignoreRedirect'] ) ) {
504 return false;
505 }
506 $redir = $this->checkRedirect( $title );
507 if ( $redir && $title->getNamespace() === NS_FILE ) {
508 $img = $this->newFile( $redir );
509 if ( !$img ) {
510 return false;
511 }
512 $img->load( $flags );
513 if ( $img->exists() ) {
514 $img->redirectedFrom( $title->getDBkey() );
515
516 return $img;
517 }
518 }
519
520 return false;
521 }
522
540 public function findFiles( array $items, $flags = 0 ) {
541 $result = [];
542 foreach ( $items as $item ) {
543 if ( is_array( $item ) ) {
544 $title = $item['title'];
545 $options = $item;
546 unset( $options['title'] );
547
548 if (
549 !empty( $options['private'] ) &&
550 !( $options['private'] instanceof Authority )
551 ) {
552 $options['private'] = RequestContext::getMain()->getAuthority();
553 }
554 } else {
555 $title = $item;
556 $options = [];
557 }
558 $file = $this->findFile( $title, $options );
559 if ( $file ) {
560 $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
561 if ( $flags & self::NAME_AND_TIME_ONLY ) {
562 $result[$searchName] = [
563 'title' => $file->getTitle()->getDBkey(),
564 'timestamp' => $file->getTimestamp()
565 ];
566 } else {
567 $result[$searchName] = $file;
568 }
569 }
570 }
571
572 return $result;
573 }
574
585 public function findFileFromKey( $sha1, $options = [] ) {
586 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
587 throw new InvalidArgumentException(
588 __METHOD__ . ' called with the `private` option set to something ' .
589 'other than an Authority object'
590 );
591 }
592
593 $time = $options['time'] ?? false;
594 # First try to find a matching current version of a file...
595 if ( !$this->fileFactoryKey ) {
596 return false; // find-by-sha1 not supported
597 }
598 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
599 if ( $img && $img->exists() ) {
600 return $img;
601 }
602 # Now try to find a matching old version of a file...
603 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
604 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
605 if ( $img && $img->exists() ) {
606 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
607 return $img; // always OK
608 } elseif (
609 // If its not empty, its an Authority object
610 !empty( $options['private'] ) &&
611 $img->userCan( File::DELETED_FILE, $options['private'] )
612 ) {
613 return $img;
614 }
615 }
616 }
617
618 return false;
619 }
620
629 public function findBySha1( $hash ) {
630 return [];
631 }
632
640 public function findBySha1s( array $hashes ) {
641 $result = [];
642 foreach ( $hashes as $hash ) {
643 $files = $this->findBySha1( $hash );
644 if ( count( $files ) ) {
645 $result[$hash] = $files;
646 }
647 }
648
649 return $result;
650 }
651
660 public function findFilesByPrefix( $prefix, $limit ) {
661 return [];
662 }
663
669 public function getThumbScriptUrl() {
670 return $this->thumbScriptUrl;
671 }
672
678 public function getThumbProxyUrl() {
679 return $this->thumbProxyUrl;
680 }
681
687 public function getThumbProxySecret() {
688 return $this->thumbProxySecret;
689 }
690
696 public function canTransformVia404() {
697 return $this->transformVia404;
698 }
699
706 public function canTransformLocally() {
707 return !$this->disableLocalTransform;
708 }
709
716 public function getNameFromTitle( $title ) {
717 if (
718 $this->initialCapital !=
719 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
720 ) {
721 $name = $title->getDBkey();
722 if ( $this->initialCapital ) {
723 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
724 }
725 } else {
726 $name = $title->getDBkey();
727 }
728
729 return $name;
730 }
731
737 public function getRootDirectory() {
738 return $this->getZonePath( 'public' );
739 }
740
748 public function getHashPath( $name ) {
749 return self::getHashPathForLevel( $name, $this->hashLevels );
750 }
751
759 public function getTempHashPath( $suffix ) {
760 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
761 $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
762 return self::getHashPathForLevel( $name, $this->hashLevels );
763 }
764
770 protected static function getHashPathForLevel( $name, $levels ) {
771 if ( $levels == 0 ) {
772 return '';
773 } else {
774 $hash = md5( $name );
775 $path = '';
776 for ( $i = 1; $i <= $levels; $i++ ) {
777 $path .= substr( $hash, 0, $i ) . '/';
778 }
779
780 return $path;
781 }
782 }
783
789 public function getHashLevels() {
790 return $this->hashLevels;
791 }
792
798 public function getName() {
799 return $this->name;
800 }
801
809 public function makeUrl( $query = '', $entry = 'index' ) {
810 if ( isset( $this->scriptDirUrl ) ) {
811 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
812 }
813
814 return false;
815 }
816
829 public function getDescriptionUrl( $name ) {
830 $encName = wfUrlencode( $name );
831 if ( $this->descBaseUrl !== null ) {
832 # "http://example.com/wiki/File:"
833 return $this->descBaseUrl . $encName;
834 }
835 if ( $this->articleUrl !== null ) {
836 # "http://example.com/wiki/$1"
837 # We use "Image:" as the canonical namespace for
838 # compatibility across all MediaWiki versions.
839 return str_replace( '$1',
840 "Image:$encName", $this->articleUrl );
841 }
842 if ( $this->scriptDirUrl !== null ) {
843 # "http://example.com/w"
844 # We use "Image:" as the canonical namespace for
845 # compatibility across all MediaWiki versions,
846 # and just sort of hope index.php is right. ;)
847 return $this->makeUrl( "title=Image:$encName" );
848 }
849
850 return false;
851 }
852
863 public function getDescriptionRenderUrl( $name, $lang = null ) {
864 $query = 'action=render';
865 if ( $lang !== null ) {
866 $query .= '&uselang=' . urlencode( $lang );
867 }
868 if ( isset( $this->scriptDirUrl ) ) {
869 return $this->makeUrl(
870 'title=' .
871 wfUrlencode( 'Image:' . $name ) .
872 "&$query" );
873 } else {
874 $descUrl = $this->getDescriptionUrl( $name );
875 if ( $descUrl ) {
876 return wfAppendQuery( $descUrl, $query );
877 } else {
878 return false;
879 }
880 }
881 }
882
888 public function getDescriptionStylesheetUrl() {
889 if ( isset( $this->scriptDirUrl ) ) {
890 // Must match canonical query parameter order for optimum caching
891 // See HTMLCacheUpdater::getUrls
892 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
893 }
894
895 return false;
896 }
897
915 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
916 $this->assertWritableRepo(); // fail out if read-only
917
918 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
919 if ( $status->successCount == 0 ) {
920 $status->setOK( false );
921 }
922
923 return $status;
924 }
925
939 public function storeBatch( array $triplets, $flags = 0 ) {
940 $this->assertWritableRepo(); // fail out if read-only
941
942 if ( $flags & self::DELETE_SOURCE ) {
943 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
944 }
945
946 $status = $this->newGood();
947 $backend = $this->backend; // convenience
948
949 $operations = [];
950 // Validate each triplet and get the store operation...
951 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
952 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
953 wfDebug( __METHOD__
954 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
955 );
956 // Resolve source path
957 if ( $src instanceof FSFile ) {
958 $op = 'store';
959 } else {
960 $src = $this->resolveToStoragePathIfVirtual( $src );
961 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
962 }
963 // Resolve destination path
964 $root = $this->getZonePath( $dstZone );
965 if ( !$root ) {
966 throw new RuntimeException( "Invalid zone: $dstZone" );
967 }
968 if ( !$this->validateFilename( $dstRel ) ) {
969 throw new RuntimeException( 'Validation error in $dstRel' );
970 }
971 $dstPath = "$root/$dstRel";
972 $dstDir = dirname( $dstPath );
973 // Create destination directories for this triplet
974 if ( !$this->initDirectory( $dstDir )->isOK() ) {
975 return $this->newFatal( 'directorycreateerror', $dstDir );
976 }
977
978 // Copy the source file to the destination
979 $operations[] = [
980 'op' => $op,
981 'src' => $src, // storage path (copy) or local file path (store)
982 'dst' => $dstPath,
983 'overwrite' => (bool)( $flags & self::OVERWRITE ),
984 'overwriteSame' => (bool)( $flags & self::OVERWRITE_SAME ),
985 ];
986 }
987
988 // Execute the store operation for each triplet
989 $opts = [ 'force' => true ];
990 if ( $flags & self::SKIP_LOCKING ) {
991 $opts['nonLocking'] = true;
992 }
993
994 return $status->merge( $backend->doOperations( $operations, $opts ) );
995 }
996
1007 public function cleanupBatch( array $files, $flags = 0 ) {
1008 $this->assertWritableRepo(); // fail out if read-only
1009
1010 $status = $this->newGood();
1011
1012 $operations = [];
1013 foreach ( $files as $path ) {
1014 if ( is_array( $path ) ) {
1015 // This is a pair, extract it
1016 [ $zone, $rel ] = $path;
1017 $path = $this->getZonePath( $zone ) . "/$rel";
1018 } else {
1019 // Resolve source to a storage path if virtual
1020 $path = $this->resolveToStoragePathIfVirtual( $path );
1021 }
1022 $operations[] = [ 'op' => 'delete', 'src' => $path ];
1023 }
1024 // Actually delete files from storage...
1025 $opts = [ 'force' => true ];
1026 if ( $flags & self::SKIP_LOCKING ) {
1027 $opts['nonLocking'] = true;
1028 }
1029
1030 return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1031 }
1032
1050 final public function quickImport( $src, $dst, $options = null ) {
1051 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1052 }
1053
1068 public function quickImportBatch( array $triples ) {
1069 $status = $this->newGood();
1070 $operations = [];
1071 foreach ( $triples as $triple ) {
1072 [ $src, $dst ] = $triple;
1073 if ( $src instanceof FSFile ) {
1074 $op = 'store';
1075 } else {
1076 $src = $this->resolveToStoragePathIfVirtual( $src );
1077 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1078 }
1079 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1080
1081 if ( !isset( $triple[2] ) ) {
1082 $headers = [];
1083 } elseif ( is_string( $triple[2] ) ) {
1084 // back-compat
1085 $headers = [ 'Content-Disposition' => $triple[2] ];
1086 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1087 $headers = $triple[2]['headers'];
1088 } else {
1089 $headers = [];
1090 }
1091
1092 $operations[] = [
1093 'op' => $op,
1094 'src' => $src, // storage path (copy) or local path/FSFile (store)
1095 'dst' => $dst,
1096 'headers' => $headers
1097 ];
1098 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1099 }
1100
1101 return $status->merge( $this->backend->doQuickOperations( $operations ) );
1102 }
1103
1112 final public function quickPurge( $path ) {
1113 return $this->quickPurgeBatch( [ $path ] );
1114 }
1115
1123 public function quickCleanDir( $dir ) {
1124 return $this->newGood()->merge(
1125 $this->backend->clean(
1126 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1127 )
1128 );
1129 }
1130
1139 public function quickPurgeBatch( array $paths ) {
1140 $status = $this->newGood();
1141 $operations = [];
1142 foreach ( $paths as $path ) {
1143 $operations[] = [
1144 'op' => 'delete',
1145 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1146 'ignoreMissingSource' => true
1147 ];
1148 }
1149 $status->merge( $this->backend->doQuickOperations( $operations ) );
1150
1151 return $status;
1152 }
1153
1164 public function storeTemp( $originalName, $srcPath ) {
1165 $this->assertWritableRepo(); // fail out if read-only
1166
1167 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1168 $hashPath = $this->getHashPath( $originalName );
1169 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1170 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1171
1172 $result = $this->quickImport( $srcPath, $virtualUrl );
1173 $result->value = $virtualUrl;
1174
1175 return $result;
1176 }
1177
1184 public function freeTemp( $virtualUrl ) {
1185 $this->assertWritableRepo(); // fail out if read-only
1186
1187 $temp = $this->getVirtualUrl( 'temp' );
1188 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1189 wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1190
1191 return false;
1192 }
1193
1194 return $this->quickPurge( $virtualUrl )->isOK();
1195 }
1196
1206 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1207 $this->assertWritableRepo(); // fail out if read-only
1208
1209 $status = $this->newGood();
1210
1211 $sources = [];
1212 foreach ( $srcPaths as $srcPath ) {
1213 // Resolve source to a storage path if virtual
1214 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1215 $sources[] = $source; // chunk to merge
1216 }
1217
1218 // Concatenate the chunks into one FS file
1219 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1220 $status->merge( $this->backend->concatenate( $params ) );
1221 if ( !$status->isOK() ) {
1222 return $status;
1223 }
1224
1225 // Delete the sources if required
1226 if ( $flags & self::DELETE_SOURCE ) {
1227 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1228 }
1229
1230 // Make sure status is OK, despite any quickPurgeBatch() fatals
1231 $status->setResult( true );
1232
1233 return $status;
1234 }
1235
1259 public function publish(
1260 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1261 ) {
1262 $this->assertWritableRepo(); // fail out if read-only
1263
1264 $status = $this->publishBatch(
1265 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1266 if ( $status->successCount == 0 ) {
1267 $status->setOK( false );
1268 }
1269 $status->value = $status->value[0] ?? false;
1270
1271 return $status;
1272 }
1273
1285 public function publishBatch( array $ntuples, $flags = 0 ) {
1286 $this->assertWritableRepo(); // fail out if read-only
1287
1288 $backend = $this->backend; // convenience
1289 // Try creating directories
1290 $this->initZones( 'public' );
1291
1292 $status = $this->newGood( [] );
1293
1294 $operations = [];
1295 $sourceFSFilesToDelete = []; // cleanup for disk source files
1296 // Validate each triplet and get the store operation...
1297 foreach ( $ntuples as $ntuple ) {
1298 [ $src, $dstRel, $archiveRel ] = $ntuple;
1299 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1300
1301 $options = $ntuple[3] ?? [];
1302 // Resolve source to a storage path if virtual
1303 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1304 if ( !$this->validateFilename( $dstRel ) ) {
1305 throw new RuntimeException( 'Validation error in $dstRel' );
1306 }
1307 if ( !$this->validateFilename( $archiveRel ) ) {
1308 throw new RuntimeException( 'Validation error in $archiveRel' );
1309 }
1310
1311 $publicRoot = $this->getZonePath( 'public' );
1312 $dstPath = "$publicRoot/$dstRel";
1313 $archivePath = "$publicRoot/$archiveRel";
1314
1315 $dstDir = dirname( $dstPath );
1316 $archiveDir = dirname( $archivePath );
1317 // Abort immediately on directory creation errors since they're likely to be repetitive
1318 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1319 return $this->newFatal( 'directorycreateerror', $dstDir );
1320 }
1321 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1322 return $this->newFatal( 'directorycreateerror', $archiveDir );
1323 }
1324
1325 // Set any desired headers to be use in GET/HEAD responses
1326 $headers = $options['headers'] ?? [];
1327
1328 // Archive destination file if it exists.
1329 // This will check if the archive file also exists and fail if does.
1330 // This is a check to avoid data loss. On Windows and Linux,
1331 // copy() will overwrite, so the existence check is vulnerable to
1332 // race conditions unless a functioning LockManager is used.
1333 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1334 $operations[] = [
1335 'op' => 'copy',
1336 'src' => $dstPath,
1337 'dst' => $archivePath,
1338 'ignoreMissingSource' => true
1339 ];
1340
1341 // Copy (or move) the source file to the destination
1342 if ( FileBackend::isStoragePath( $srcPath ) ) {
1343 $operations[] = [
1344 'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1345 'src' => $srcPath,
1346 'dst' => $dstPath,
1347 'overwrite' => true, // replace current
1348 'headers' => $headers
1349 ];
1350 } else {
1351 $operations[] = [
1352 'op' => 'store',
1353 'src' => $src, // storage path (copy) or local path/FSFile (store)
1354 'dst' => $dstPath,
1355 'overwrite' => true, // replace current
1356 'headers' => $headers
1357 ];
1358 if ( $flags & self::DELETE_SOURCE ) {
1359 $sourceFSFilesToDelete[] = $srcPath;
1360 }
1361 }
1362 }
1363
1364 // Execute the operations for each triplet
1365 $status->merge( $backend->doOperations( $operations ) );
1366 // Find out which files were archived...
1367 foreach ( $ntuples as $i => $ntuple ) {
1368 [ , , $archiveRel ] = $ntuple;
1369 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1370 if ( $this->fileExists( $archivePath ) ) {
1371 $status->value[$i] = 'archived';
1372 } else {
1373 $status->value[$i] = 'new';
1374 }
1375 }
1376 // Cleanup for disk source files...
1377 foreach ( $sourceFSFilesToDelete as $file ) {
1378 AtEase::suppressWarnings();
1379 unlink( $file ); // FS cleanup
1380 AtEase::restoreWarnings();
1381 }
1382
1383 return $status;
1384 }
1385
1393 protected function initDirectory( $dir ) {
1394 $path = $this->resolveToStoragePathIfVirtual( $dir );
1395 [ , $container, ] = FileBackend::splitStoragePath( $path );
1396
1397 $params = [ 'dir' => $path ];
1398 if ( $this->isPrivate
1399 || $container === $this->zones['deleted']['container']
1400 || $container === $this->zones['temp']['container']
1401 ) {
1402 # Take all available measures to prevent web accessibility of new deleted
1403 # directories, in case the user has not configured offline storage
1404 $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1405 }
1406
1407 return $this->newGood()->merge( $this->backend->prepare( $params ) );
1408 }
1409
1416 public function cleanDir( $dir ) {
1417 $this->assertWritableRepo(); // fail out if read-only
1418
1419 return $this->newGood()->merge(
1420 $this->backend->clean(
1421 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1422 )
1423 );
1424 }
1425
1432 public function fileExists( $file ) {
1433 $result = $this->fileExistsBatch( [ $file ] );
1434
1435 return $result[0];
1436 }
1437
1445 public function fileExistsBatch( array $files ) {
1446 $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1447 $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1448
1449 $result = [];
1450 foreach ( $paths as $key => $path ) {
1451 $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1452 }
1453
1454 return $result;
1455 }
1456
1467 public function delete( $srcRel, $archiveRel ) {
1468 $this->assertWritableRepo(); // fail out if read-only
1469
1470 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1471 }
1472
1489 public function deleteBatch( array $sourceDestPairs ) {
1490 $this->assertWritableRepo(); // fail out if read-only
1491
1492 // Try creating directories
1493 $this->initZones( [ 'public', 'deleted' ] );
1494
1495 $status = $this->newGood();
1496
1497 $backend = $this->backend; // convenience
1498 $operations = [];
1499 // Validate filenames and create archive directories
1500 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1501 if ( !$this->validateFilename( $srcRel ) ) {
1502 throw new RuntimeException( __METHOD__ . ':Validation error in $srcRel' );
1503 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1504 throw new RuntimeException( __METHOD__ . ':Validation error in $archiveRel' );
1505 }
1506
1507 $publicRoot = $this->getZonePath( 'public' );
1508 $srcPath = "{$publicRoot}/$srcRel";
1509
1510 $deletedRoot = $this->getZonePath( 'deleted' );
1511 $archivePath = "{$deletedRoot}/{$archiveRel}";
1512 $archiveDir = dirname( $archivePath ); // does not touch FS
1513
1514 // Create destination directories
1515 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1516 return $this->newFatal( 'directorycreateerror', $archiveDir );
1517 }
1518
1519 $operations[] = [
1520 'op' => 'move',
1521 'src' => $srcPath,
1522 'dst' => $archivePath,
1523 // We may have 2+ identical files being deleted,
1524 // all of which will map to the same destination file
1525 'overwriteSame' => true // also see T33792
1526 ];
1527 }
1528
1529 // Move the files by execute the operations for each pair.
1530 // We're now committed to returning an OK result, which will
1531 // lead to the files being moved in the DB also.
1532 $opts = [ 'force' => true ];
1533 return $status->merge( $backend->doOperations( $operations, $opts ) );
1534 }
1535
1542 public function cleanupDeletedBatch( array $storageKeys ) {
1543 $this->assertWritableRepo();
1544 }
1545
1553 public function getDeletedHashPath( $key ) {
1554 if ( strlen( $key ) < 31 ) {
1555 throw new InvalidArgumentException( "Invalid storage key '$key'." );
1556 }
1557 $path = '';
1558 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1559 $path .= $key[$i] . '/';
1560 }
1561
1562 return $path;
1563 }
1564
1572 protected function resolveToStoragePathIfVirtual( $path ) {
1573 if ( self::isVirtualUrl( $path ) ) {
1574 return $this->resolveVirtualUrl( $path );
1575 }
1576
1577 return $path;
1578 }
1579
1587 public function getLocalCopy( $virtualUrl ) {
1588 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1589
1590 return $this->backend->getLocalCopy( [ 'src' => $path ] );
1591 }
1592
1601 public function getLocalReference( $virtualUrl ) {
1602 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1603
1604 return $this->backend->getLocalReference( [ 'src' => $path ] );
1605 }
1606
1614 public function getFileProps( $virtualUrl ) {
1615 $fsFile = $this->getLocalReference( $virtualUrl );
1616 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1617 if ( $fsFile ) {
1618 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1619 } else {
1620 $props = $mwProps->newPlaceholderProps();
1621 }
1622
1623 return $props;
1624 }
1625
1632 public function getFileTimestamp( $virtualUrl ) {
1633 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1634
1635 return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1636 }
1637
1644 public function getFileSize( $virtualUrl ) {
1645 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1646
1647 return $this->backend->getFileSize( [ 'src' => $path ] );
1648 }
1649
1656 public function getFileSha1( $virtualUrl ) {
1657 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1658
1659 return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1660 }
1661
1671 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1672 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1673 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1674
1675 // T172851: HHVM does not flush the output properly, causing OOM
1676 ob_start( null, 1_048_576 );
1677 ob_implicit_flush( true );
1678
1679 $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1680
1681 // T186565: Close the buffer, unless it has already been closed
1682 // in HTTPFileStreamer::resetOutputBuffers().
1683 if ( ob_get_status() ) {
1684 ob_end_flush();
1685 }
1686
1687 return $status;
1688 }
1689
1698 public function enumFiles( $callback ) {
1699 $this->enumFilesInStorage( $callback );
1700 }
1701
1709 protected function enumFilesInStorage( $callback ) {
1710 $publicRoot = $this->getZonePath( 'public' );
1711 $numDirs = 1 << ( $this->hashLevels * 4 );
1712 // Use a priori assumptions about directory structure
1713 // to reduce the tree height of the scanning process.
1714 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1715 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1716 $path = $publicRoot;
1717 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1718 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1719 }
1720 $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1721 if ( $iterator === null ) {
1722 throw new RuntimeException( __METHOD__ . ': could not get file listing for ' . $path );
1723 }
1724 foreach ( $iterator as $name ) {
1725 // Each item returned is a public file
1726 call_user_func( $callback, "{$path}/{$name}" );
1727 }
1728 }
1729 }
1730
1737 public function validateFilename( $filename ) {
1738 if ( strval( $filename ) == '' ) {
1739 return false;
1740 }
1741
1742 return FileBackend::isPathTraversalFree( $filename );
1743 }
1744
1750 private function getErrorCleanupFunction() {
1751 switch ( $this->pathDisclosureProtection ) {
1752 case 'none':
1753 case 'simple': // b/c
1754 $callback = [ $this, 'passThrough' ];
1755 break;
1756 default: // 'paranoid'
1757 $callback = [ $this, 'paranoidClean' ];
1758 }
1759 return $callback;
1760 }
1761
1768 public function paranoidClean( $param ) {
1769 return '[hidden]';
1770 }
1771
1778 public function passThrough( $param ) {
1779 return $param;
1780 }
1781
1789 public function newFatal( $message, ...$parameters ) {
1790 $status = Status::newFatal( $message, ...$parameters );
1791 $status->cleanCallback = $this->getErrorCleanupFunction();
1792
1793 return $status;
1794 }
1795
1802 public function newGood( $value = null ) {
1803 $status = Status::newGood( $value );
1804 $status->cleanCallback = $this->getErrorCleanupFunction();
1805
1806 return $status;
1807 }
1808
1817 public function checkRedirect( $title ) {
1818 return false;
1819 }
1820
1828 public function invalidateImageRedirect( $title ) {
1829 }
1830
1836 public function getDisplayName() {
1837 $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1838
1839 if ( $this->isLocal() ) {
1840 return $sitename;
1841 }
1842
1843 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1844 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1845 }
1846
1854 public function nameForThumb( $name ) {
1855 if ( strlen( $name ) > $this->abbrvThreshold ) {
1856 $ext = FileBackend::extensionFromPath( $name );
1857 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1858 }
1859
1860 return $name;
1861 }
1862
1868 public function isLocal() {
1869 return $this->getName() == 'local';
1870 }
1871
1883 public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1884 return false;
1885 }
1886
1898 public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1899 return $this->wanCache->makeKey(
1900 'filerepo-' . $kClassSuffix,
1901 $this->getName(),
1902 ...$components
1903 );
1904 }
1905
1914 public function getTempRepo() {
1915 return new TempFileRepo( [
1916 'name' => "{$this->name}-temp",
1917 'backend' => $this->backend,
1918 'zones' => [
1919 'public' => [
1920 // Same place storeTemp() uses in the base repo, though
1921 // the path hashing is mismatched, which is annoying.
1922 'container' => $this->zones['temp']['container'],
1923 'directory' => $this->zones['temp']['directory']
1924 ],
1925 'thumb' => [
1926 'container' => $this->zones['temp']['container'],
1927 'directory' => $this->zones['temp']['directory'] == ''
1928 ? 'thumb'
1929 : $this->zones['temp']['directory'] . '/thumb'
1930 ],
1931 'transcoded' => [
1932 'container' => $this->zones['temp']['container'],
1933 'directory' => $this->zones['temp']['directory'] == ''
1934 ? 'transcoded'
1935 : $this->zones['temp']['directory'] . '/transcoded'
1936 ]
1937 ],
1938 'hashLevels' => $this->hashLevels, // performance
1939 'isPrivate' => true // all in temp zone
1940 ] );
1941 }
1942
1949 public function getUploadStash( UserIdentity $user = null ) {
1950 return new UploadStash( $this, $user );
1951 }
1952
1959 protected function assertWritableRepo() {
1960 }
1961
1968 public function getInfo() {
1969 $ret = [
1970 'name' => $this->getName(),
1971 'displayname' => $this->getDisplayName(),
1972 'rootUrl' => $this->getZoneUrl( 'public' ),
1973 'local' => $this->isLocal(),
1974 ];
1975
1976 $optionalSettings = [
1977 'url',
1978 'thumbUrl',
1979 'initialCapital',
1980 'descBaseUrl',
1981 'scriptDirUrl',
1982 'articleUrl',
1983 'fetchDescription',
1984 'descriptionCacheExpiry',
1985 ];
1986 foreach ( $optionalSettings as $k ) {
1987 if ( isset( $this->$k ) ) {
1988 $ret[$k] = $this->$k;
1989 }
1990 }
1991 if ( isset( $this->favicon ) ) {
1992 // Expand any local path to full URL to improve API usability (T77093).
1993 $ret['favicon'] = MediaWikiServices::getInstance()->getUrlUtils()
1994 ->expand( $this->favicon );
1995 }
1996
1997 return $ret;
1998 }
1999
2004 public function hasSha1Storage() {
2005 return $this->hasSha1Storage;
2006 }
2007
2012 public function supportsSha1URLs() {
2013 return $this->supportsSha1URLs;
2014 }
2015}
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.
Class representing a non-directory file on the file system.
Definition FSFile.php:32
Base class for file repositories.
Definition FileRepo.php:52
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition FileRepo.php:113
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:759
int $hashLevels
The number of directory levels for hash-based division of files.
Definition FileRepo.php:122
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:55
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition FileRepo.php:358
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:540
newFatal( $message,... $parameters)
Create a new fatal error.
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition FileRepo.php:678
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition FileRepo.php:384
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:72
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:737
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
newGood( $value=null)
Create a new good result.
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition FileRepo.php:660
getHashLevels()
Get the number of hash directory levels.
Definition FileRepo.php:789
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition FileRepo.php:153
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:798
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition FileRepo.php:915
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:457
callable false $oldFileFactoryKey
Override these in the base class.
Definition FileRepo.php:146
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition FileRepo.php:300
const NAME_AND_TIME_ONLY
Definition FileRepo.php:58
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:770
array $zones
Map of zones to config.
Definition FileRepo.php:78
callable false $fileFactoryKey
Override these in the base class.
Definition FileRepo.php:144
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:156
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition FileRepo.php:939
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:706
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:131
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:809
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:640
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition FileRepo.php:151
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
FileBackend $backend
Definition FileRepo.php:75
null string $favicon
The URL to a favicon (optional, may be a server-local path URL).
Definition FileRepo.php:134
fileExistsBatch(array $files)
Checks existence of an array of files.
int $descriptionCacheExpiry
Definition FileRepo.php:66
paranoidClean( $param)
Path disclosure protection function.
WANObjectCache $wanCache
Definition FileRepo.php:159
const SKIP_LOCKING
Definition FileRepo.php:56
initZones( $doZones=[])
Ensure that a single zone or list of zones is defined for usage.
Definition FileRepo.php:273
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
const OVERWRITE
Definition FileRepo.php:54
isLocal()
Returns true if this the local file repository.
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition FileRepo.php:398
getUploadStash(UserIdentity $user=null)
Get an UploadStash associated with this repo.
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition FileRepo.php:829
cleanDir( $dir)
Deletes a directory if empty.
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
bool $hasSha1Storage
Definition FileRepo.php:69
const DELETE_SOURCE
Definition FileRepo.php:53
getNameFromTitle( $title)
Get the name of a file from its title.
Definition FileRepo.php:716
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:687
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition FileRepo.php:63
string false $url
Public zone URL.
Definition FileRepo.php:116
callable $fileFactory
Override these in the base class.
Definition FileRepo.php:140
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:288
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition FileRepo.php:888
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition FileRepo.php:86
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:137
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition FileRepo.php:96
string $descBaseUrl
URL of image description pages, e.g.
Definition FileRepo.php:91
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition FileRepo.php:316
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition FileRepo.php:264
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition FileRepo.php:422
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:696
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:585
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition FileRepo.php:125
string $thumbScriptUrl
URL of thumb.php.
Definition FileRepo.php:81
backendSupportsUnicodePaths()
Definition FileRepo.php:346
__construct(array $info=null)
Definition FileRepo.php:173
string $name
Definition FileRepo.php:166
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:119
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition FileRepo.php:106
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:748
callable false $oldFileFactory
Override these in the base class.
Definition FileRepo.php:142
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:99
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition FileRepo.php:863
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:629
getBackend()
Get the file backend instance.
Definition FileRepo.php:254
getInfo()
Return information about the repository.
getThumbScriptUrl()
Get the URL of thumb.php.
Definition FileRepo.php:669
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:79
Library for creating and parsing MW-style timestamps.
FileRepo for temporary files created by FileRepo::getTempRepo()
UploadStash is intended to accomplish a few things:
Multi-datacenter aware caching interface.
Base class for all file backend classes (including multi-write backends).
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.
$source