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