MediaWiki REL1_35
FileRepo.php
Go to the documentation of this file.
1<?php
11
41class FileRepo {
42 public const DELETE_SOURCE = 1;
43 public const OVERWRITE = 2;
44 public const OVERWRITE_SAME = 4;
45 public const SKIP_LOCKING = 8;
46
47 public const NAME_AND_TIME_ONLY = 1;
48
53
56
58 protected $hasSha1Storage = false;
59
61 protected $supportsSha1URLs = false;
62
64 protected $backend;
65
67 protected $zones = [];
68
70 protected $thumbScriptUrl;
71
76
80 protected $descBaseUrl;
81
85 protected $scriptDirUrl;
86
88 protected $articleUrl;
89
95 protected $initialCapital;
96
102 protected $pathDisclosureProtection = 'simple';
103
105 protected $url;
106
108 protected $thumbUrl;
109
111 protected $hashLevels;
112
115
121
123 protected $favicon;
124
126 protected $isPrivate;
127
129 protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
131 protected $oldFileFactory = false;
133 protected $fileFactoryKey = false;
135 protected $oldFileFactoryKey = false;
136
140 protected $thumbProxyUrl;
143
145 protected $wanCache;
146
152 public $name;
153
160 public function __construct( array $info = null ) {
161 // Verify required settings presence
162 if (
163 $info === null
164 || !array_key_exists( 'name', $info )
165 || !array_key_exists( 'backend', $info )
166 ) {
167 throw new MWException( __CLASS__ .
168 " requires an array of options having both 'name' and 'backend' keys.\n" );
169 }
170
171 // Required settings
172 $this->name = $info['name'];
173 if ( $info['backend'] instanceof FileBackend ) {
174 $this->backend = $info['backend']; // useful for testing
175 } else {
176 $this->backend =
177 MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
178 }
179
180 // Optional settings that can have no value
181 $optionalSettings = [
182 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
183 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
184 'favicon', 'thumbProxyUrl', 'thumbProxySecret',
185 ];
186 foreach ( $optionalSettings as $var ) {
187 if ( isset( $info[$var] ) ) {
188 $this->$var = $info[$var];
189 }
190 }
191
192 // Optional settings that have a default
193 $localCapitalLinks =
194 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
195 $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
196 if ( $localCapitalLinks && !$this->initialCapital ) {
197 // If the local wiki's file namespace requires an initial capital, but a foreign file
198 // repo doesn't, complications will result. Linker code will want to auto-capitalize the
199 // first letter of links to files, but those links might actually point to files on
200 // foreign wikis with initial-lowercase names. This combination is not likely to be
201 // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
202 // to include a foreign file repo with initialCapital false, set your local file
203 // namespace to not be capitalized either.
204 throw new InvalidArgumentException(
205 'File repos with initial capital false are not allowed on wikis where the File ' .
206 'namespace has initial capital true' );
207 }
208
209 $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
210 if ( isset( $info['thumbUrl'] ) ) {
211 $this->thumbUrl = $info['thumbUrl'];
212 } else {
213 $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
214 }
215 $this->hashLevels = $info['hashLevels'] ?? 2;
216 $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
217 $this->transformVia404 = !empty( $info['transformVia404'] );
218 $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
219 $this->isPrivate = !empty( $info['isPrivate'] );
220 // Give defaults for the basic zones...
221 $this->zones = $info['zones'] ?? [];
222 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
223 if ( !isset( $this->zones[$zone]['container'] ) ) {
224 $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
225 }
226 if ( !isset( $this->zones[$zone]['directory'] ) ) {
227 $this->zones[$zone]['directory'] = '';
228 }
229 if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
230 $this->zones[$zone]['urlsByExt'] = [];
231 }
232 }
233
234 $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
235
236 $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
237 }
238
244 public function getBackend() {
245 return $this->backend;
246 }
247
254 public function getReadOnlyReason() {
255 return $this->backend->getReadOnlyReason();
256 }
257
265 protected function initZones( $doZones = [] ) {
266 $status = $this->newGood();
267 foreach ( (array)$doZones as $zone ) {
268 $root = $this->getZonePath( $zone );
269 if ( $root === null ) {
270 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
271 }
272 }
273
274 return $status;
275 }
276
283 public static function isVirtualUrl( $url ) {
284 return substr( $url, 0, 9 ) == 'mwrepo://';
285 }
286
295 public function getVirtualUrl( $suffix = false ) {
296 $path = 'mwrepo://' . $this->name;
297 if ( $suffix !== false ) {
298 $path .= '/' . rawurlencode( $suffix );
299 }
300
301 return $path;
302 }
303
311 public function getZoneUrl( $zone, $ext = null ) {
312 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
313 // standard public zones
314 if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
315 // custom URL for extension/zone
316 return $this->zones[$zone]['urlsByExt'][$ext];
317 } elseif ( isset( $this->zones[$zone]['url'] ) ) {
318 // custom URL for zone
319 return $this->zones[$zone]['url'];
320 }
321 }
322 switch ( $zone ) {
323 case 'public':
324 return $this->url;
325 case 'temp':
326 case 'deleted':
327 return false; // no public URL
328 case 'thumb':
329 return $this->thumbUrl;
330 case 'transcoded':
331 return "{$this->url}/transcoded";
332 default:
333 return false;
334 }
335 }
336
340 public function backendSupportsUnicodePaths() {
341 return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
342 }
343
352 public function resolveVirtualUrl( $url ) {
353 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
354 throw new MWException( __METHOD__ . ': unknown protocol' );
355 }
356 $bits = explode( '/', substr( $url, 9 ), 3 );
357 if ( count( $bits ) != 3 ) {
358 throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
359 }
360 list( $repo, $zone, $rel ) = $bits;
361 if ( $repo !== $this->name ) {
362 throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
363 }
364 $base = $this->getZonePath( $zone );
365 if ( !$base ) {
366 throw new MWException( __METHOD__ . ": invalid zone: $zone" );
367 }
368
369 return $base . '/' . rawurldecode( $rel );
370 }
371
378 protected function getZoneLocation( $zone ) {
379 if ( !isset( $this->zones[$zone] ) ) {
380 return [ null, null ]; // bogus
381 }
382
383 return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
384 }
385
392 public function getZonePath( $zone ) {
393 list( $container, $base ) = $this->getZoneLocation( $zone );
394 if ( $container === null || $base === null ) {
395 return null;
396 }
397 $backendName = $this->backend->getName();
398 if ( $base != '' ) { // may not be set
399 $base = "/{$base}";
400 }
401
402 return "mwstore://$backendName/{$container}{$base}";
403 }
404
416 public function newFile( $title, $time = false ) {
417 $title = File::normalizeTitle( $title );
418 if ( !$title ) {
419 return null;
420 }
421 if ( $time ) {
422 if ( $this->oldFileFactory ) {
423 return call_user_func( $this->oldFileFactory, $title, $this, $time );
424 } else {
425 return null;
426 }
427 } else {
428 return call_user_func( $this->fileFactory, $title, $this );
429 }
430 }
431
449 public function findFile( $title, $options = [] ) {
450 $title = File::normalizeTitle( $title );
451 if ( !$title ) {
452 return false;
453 }
454 if ( isset( $options['bypassCache'] ) ) {
455 $options['latest'] = $options['bypassCache']; // b/c
456 }
457 $time = $options['time'] ?? false;
458 $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
459 # First try the current version of the file to see if it precedes the timestamp
460 $img = $this->newFile( $title );
461 if ( !$img ) {
462 return false;
463 }
464 $img->load( $flags );
465 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
466 return $img;
467 }
468 # Now try an old version of the file
469 if ( $time !== false ) {
470 $img = $this->newFile( $title, $time );
471 if ( $img ) {
472 $img->load( $flags );
473 if ( $img->exists() ) {
474 global $wgUser;
475 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
476 return $img; // always OK
477 } elseif ( !empty( $options['private'] ) &&
478 $img->userCan( File::DELETED_FILE,
479 $options['private'] instanceof User ? $options['private'] : $wgUser
480 )
481 ) {
482 return $img;
483 }
484 }
485 }
486 }
487
488 # Now try redirects
489 if ( !empty( $options['ignoreRedirect'] ) ) {
490 return false;
491 }
492 $redir = $this->checkRedirect( $title );
493 if ( $redir && $title->getNamespace() == NS_FILE ) {
494 $img = $this->newFile( $redir );
495 if ( !$img ) {
496 return false;
497 }
498 $img->load( $flags );
499 if ( $img->exists() ) {
500 $img->redirectedFrom( $title->getDBkey() );
501
502 return $img;
503 }
504 }
505
506 return false;
507 }
508
526 public function findFiles( array $items, $flags = 0 ) {
527 $result = [];
528 foreach ( $items as $item ) {
529 if ( is_array( $item ) ) {
530 $title = $item['title'];
531 $options = $item;
532 unset( $options['title'] );
533 } else {
534 $title = $item;
535 $options = [];
536 }
537 $file = $this->findFile( $title, $options );
538 if ( $file ) {
539 $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
540 if ( $flags & self::NAME_AND_TIME_ONLY ) {
541 $result[$searchName] = [
542 'title' => $file->getTitle()->getDBkey(),
543 'timestamp' => $file->getTimestamp()
544 ];
545 } else {
546 $result[$searchName] = $file;
547 }
548 }
549 }
550
551 return $result;
552 }
553
563 public function findFileFromKey( $sha1, $options = [] ) {
564 $time = $options['time'] ?? false;
565 # First try to find a matching current version of a file...
566 if ( !$this->fileFactoryKey ) {
567 return false; // find-by-sha1 not supported
568 }
569 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
570 if ( $img && $img->exists() ) {
571 return $img;
572 }
573 # Now try to find a matching old version of a file...
574 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
575 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
576 if ( $img && $img->exists() ) {
577 global $wgUser;
578 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
579 return $img; // always OK
580 } elseif ( !empty( $options['private'] ) &&
581 $img->userCan( File::DELETED_FILE,
582 $options['private'] instanceof User ? $options['private'] : $wgUser
583 )
584 ) {
585 return $img;
586 }
587 }
588 }
589
590 return false;
591 }
592
601 public function findBySha1( $hash ) {
602 return [];
603 }
604
612 public function findBySha1s( array $hashes ) {
613 $result = [];
614 foreach ( $hashes as $hash ) {
615 $files = $this->findBySha1( $hash );
616 if ( count( $files ) ) {
617 $result[$hash] = $files;
618 }
619 }
620
621 return $result;
622 }
623
632 public function findFilesByPrefix( $prefix, $limit ) {
633 return [];
634 }
635
641 public function getThumbScriptUrl() {
643 }
644
650 public function getThumbProxyUrl() {
652 }
653
659 public function getThumbProxySecret() {
661 }
662
668 public function canTransformVia404() {
670 }
671
678 public function getNameFromTitle( Title $title ) {
679 if (
680 $this->initialCapital !=
681 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
682 ) {
683 $name = $title->getDBkey();
684 if ( $this->initialCapital ) {
685 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
686 }
687 } else {
688 $name = $title->getDBkey();
689 }
690
691 return $name;
692 }
693
699 public function getRootDirectory() {
700 return $this->getZonePath( 'public' );
701 }
702
710 public function getHashPath( $name ) {
711 return self::getHashPathForLevel( $name, $this->hashLevels );
712 }
713
721 public function getTempHashPath( $suffix ) {
722 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
723 $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
724 return self::getHashPathForLevel( $name, $this->hashLevels );
725 }
726
732 protected static function getHashPathForLevel( $name, $levels ) {
733 if ( $levels == 0 ) {
734 return '';
735 } else {
736 $hash = md5( $name );
737 $path = '';
738 for ( $i = 1; $i <= $levels; $i++ ) {
739 $path .= substr( $hash, 0, $i ) . '/';
740 }
741
742 return $path;
743 }
744 }
745
751 public function getHashLevels() {
752 return $this->hashLevels;
753 }
754
760 public function getName() {
761 return $this->name;
762 }
763
771 public function makeUrl( $query = '', $entry = 'index' ) {
772 if ( isset( $this->scriptDirUrl ) ) {
773 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
774 }
775
776 return false;
777 }
778
791 public function getDescriptionUrl( $name ) {
792 $encName = wfUrlencode( $name );
793 if ( $this->descBaseUrl !== null ) {
794 # "http://example.com/wiki/File:"
795 return $this->descBaseUrl . $encName;
796 }
797 if ( $this->articleUrl !== null ) {
798 # "http://example.com/wiki/$1"
799 # We use "Image:" as the canonical namespace for
800 # compatibility across all MediaWiki versions.
801 return str_replace( '$1',
802 "Image:$encName", $this->articleUrl );
803 }
804 if ( $this->scriptDirUrl !== null ) {
805 # "http://example.com/w"
806 # We use "Image:" as the canonical namespace for
807 # compatibility across all MediaWiki versions,
808 # and just sort of hope index.php is right. ;)
809 return $this->makeUrl( "title=Image:$encName" );
810 }
811
812 return false;
813 }
814
825 public function getDescriptionRenderUrl( $name, $lang = null ) {
826 $query = 'action=render';
827 if ( $lang !== null ) {
828 $query .= '&uselang=' . urlencode( $lang );
829 }
830 if ( isset( $this->scriptDirUrl ) ) {
831 return $this->makeUrl(
832 'title=' .
833 wfUrlencode( 'Image:' . $name ) .
834 "&$query" );
835 } else {
836 $descUrl = $this->getDescriptionUrl( $name );
837 if ( $descUrl ) {
838 return wfAppendQuery( $descUrl, $query );
839 } else {
840 return false;
841 }
842 }
843 }
844
850 public function getDescriptionStylesheetUrl() {
851 if ( isset( $this->scriptDirUrl ) ) {
852 // Must match canonical query parameter order for optimum caching
853 // See Title::getCdnUrls
854 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
855 }
856
857 return false;
858 }
859
877 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
878 $this->assertWritableRepo(); // fail out if read-only
879
880 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
881 if ( $status->successCount == 0 ) {
882 $status->setOK( false );
883 }
884
885 return $status;
886 }
887
902 public function storeBatch( array $triplets, $flags = 0 ) {
903 $this->assertWritableRepo(); // fail out if read-only
904
905 if ( $flags & self::DELETE_SOURCE ) {
906 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
907 }
908
909 $status = $this->newGood();
910 $backend = $this->backend; // convenience
911
912 $operations = [];
913 // Validate each triplet and get the store operation...
914 foreach ( $triplets as $triplet ) {
915 list( $src, $dstZone, $dstRel ) = $triplet;
916 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
917 wfDebug( __METHOD__
918 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
919 );
920 // Resolve source path
921 if ( $src instanceof FSFile ) {
922 $op = 'store';
923 } else {
924 $src = $this->resolveToStoragePathIfVirtual( $src );
925 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
926 }
927 // Resolve destination path
928 $root = $this->getZonePath( $dstZone );
929 if ( !$root ) {
930 throw new MWException( "Invalid zone: $dstZone" );
931 }
932 if ( !$this->validateFilename( $dstRel ) ) {
933 throw new MWException( 'Validation error in $dstRel' );
934 }
935 $dstPath = "$root/$dstRel";
936 $dstDir = dirname( $dstPath );
937 // Create destination directories for this triplet
938 if ( !$this->initDirectory( $dstDir )->isOK() ) {
939 return $this->newFatal( 'directorycreateerror', $dstDir );
940 }
941
942 // Copy the source file to the destination
943 $operations[] = [
944 'op' => $op,
945 'src' => $src, // storage path (copy) or local file path (store)
946 'dst' => $dstPath,
947 'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
948 'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
949 ];
950 }
951
952 // Execute the store operation for each triplet
953 $opts = [ 'force' => true ];
954 if ( $flags & self::SKIP_LOCKING ) {
955 $opts['nonLocking'] = true;
956 }
957 $status->merge( $backend->doOperations( $operations, $opts ) );
958
959 return $status;
960 }
961
972 public function cleanupBatch( array $files, $flags = 0 ) {
973 $this->assertWritableRepo(); // fail out if read-only
974
975 $status = $this->newGood();
976
977 $operations = [];
978 foreach ( $files as $path ) {
979 if ( is_array( $path ) ) {
980 // This is a pair, extract it
981 list( $zone, $rel ) = $path;
982 $path = $this->getZonePath( $zone ) . "/$rel";
983 } else {
984 // Resolve source to a storage path if virtual
985 $path = $this->resolveToStoragePathIfVirtual( $path );
986 }
987 $operations[] = [ 'op' => 'delete', 'src' => $path ];
988 }
989 // Actually delete files from storage...
990 $opts = [ 'force' => true ];
991 if ( $flags & self::SKIP_LOCKING ) {
992 $opts['nonLocking'] = true;
993 }
994 $status->merge( $this->backend->doOperations( $operations, $opts ) );
995
996 return $status;
997 }
998
1016 final public function quickImport( $src, $dst, $options = null ) {
1017 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1018 }
1019
1034 public function quickImportBatch( array $triples ) {
1035 $status = $this->newGood();
1036 $operations = [];
1037 foreach ( $triples as $triple ) {
1038 list( $src, $dst ) = $triple;
1039 if ( $src instanceof FSFile ) {
1040 $op = 'store';
1041 } else {
1042 $src = $this->resolveToStoragePathIfVirtual( $src );
1043 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1044 }
1045 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1046
1047 if ( !isset( $triple[2] ) ) {
1048 $headers = [];
1049 } elseif ( is_string( $triple[2] ) ) {
1050 // back-compat
1051 $headers = [ 'Content-Disposition' => $triple[2] ];
1052 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1053 $headers = $triple[2]['headers'];
1054 } else {
1055 $headers = [];
1056 }
1057
1058 $operations[] = [
1059 'op' => $op,
1060 'src' => $src, // storage path (copy) or local path/FSFile (store)
1061 'dst' => $dst,
1062 'headers' => $headers
1063 ];
1064 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1065 }
1066 $status->merge( $this->backend->doQuickOperations( $operations ) );
1067
1068 return $status;
1069 }
1070
1079 final public function quickPurge( $path ) {
1080 return $this->quickPurgeBatch( [ $path ] );
1081 }
1082
1090 public function quickCleanDir( $dir ) {
1091 $status = $this->newGood();
1092 $status->merge( $this->backend->clean(
1093 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1094
1095 return $status;
1096 }
1097
1106 public function quickPurgeBatch( array $paths ) {
1107 $status = $this->newGood();
1108 $operations = [];
1109 foreach ( $paths as $path ) {
1110 $operations[] = [
1111 'op' => 'delete',
1112 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1113 'ignoreMissingSource' => true
1114 ];
1115 }
1116 $status->merge( $this->backend->doQuickOperations( $operations ) );
1117
1118 return $status;
1119 }
1120
1131 public function storeTemp( $originalName, $srcPath ) {
1132 $this->assertWritableRepo(); // fail out if read-only
1133
1134 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1135 $hashPath = $this->getHashPath( $originalName );
1136 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1137 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1138
1139 $result = $this->quickImport( $srcPath, $virtualUrl );
1140 $result->value = $virtualUrl;
1141
1142 return $result;
1143 }
1144
1151 public function freeTemp( $virtualUrl ) {
1152 $this->assertWritableRepo(); // fail out if read-only
1153
1154 $temp = $this->getVirtualUrl( 'temp' );
1155 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1156 wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1157
1158 return false;
1159 }
1160
1161 return $this->quickPurge( $virtualUrl )->isOK();
1162 }
1163
1173 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1174 $this->assertWritableRepo(); // fail out if read-only
1175
1176 $status = $this->newGood();
1177
1178 $sources = [];
1179 foreach ( $srcPaths as $srcPath ) {
1180 // Resolve source to a storage path if virtual
1181 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1182 $sources[] = $source; // chunk to merge
1183 }
1184
1185 // Concatenate the chunks into one FS file
1186 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1187 $status->merge( $this->backend->concatenate( $params ) );
1188 if ( !$status->isOK() ) {
1189 return $status;
1190 }
1191
1192 // Delete the sources if required
1193 if ( $flags & self::DELETE_SOURCE ) {
1194 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1195 }
1196
1197 // Make sure status is OK, despite any quickPurgeBatch() fatals
1198 $status->setResult( true );
1199
1200 return $status;
1201 }
1202
1226 public function publish(
1227 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1228 ) {
1229 $this->assertWritableRepo(); // fail out if read-only
1230
1231 $status = $this->publishBatch(
1232 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1233 if ( $status->successCount == 0 ) {
1234 $status->setOK( false );
1235 }
1236 $status->value = $status->value[0] ?? false;
1237
1238 return $status;
1239 }
1240
1253 public function publishBatch( array $ntuples, $flags = 0 ) {
1254 $this->assertWritableRepo(); // fail out if read-only
1255
1256 $backend = $this->backend; // convenience
1257 // Try creating directories
1258 $status = $this->initZones( 'public' );
1259 if ( !$status->isOK() ) {
1260 return $status;
1261 }
1262
1263 $status = $this->newGood( [] );
1264
1265 $operations = [];
1266 $sourceFSFilesToDelete = []; // cleanup for disk source files
1267 // Validate each triplet and get the store operation...
1268 foreach ( $ntuples as $ntuple ) {
1269 list( $src, $dstRel, $archiveRel ) = $ntuple;
1270 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1271
1272 $options = $ntuple[3] ?? [];
1273 // Resolve source to a storage path if virtual
1274 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1275 if ( !$this->validateFilename( $dstRel ) ) {
1276 throw new MWException( 'Validation error in $dstRel' );
1277 }
1278 if ( !$this->validateFilename( $archiveRel ) ) {
1279 throw new MWException( 'Validation error in $archiveRel' );
1280 }
1281
1282 $publicRoot = $this->getZonePath( 'public' );
1283 $dstPath = "$publicRoot/$dstRel";
1284 $archivePath = "$publicRoot/$archiveRel";
1285
1286 $dstDir = dirname( $dstPath );
1287 $archiveDir = dirname( $archivePath );
1288 // Abort immediately on directory creation errors since they're likely to be repetitive
1289 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1290 return $this->newFatal( 'directorycreateerror', $dstDir );
1291 }
1292 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1293 return $this->newFatal( 'directorycreateerror', $archiveDir );
1294 }
1295
1296 // Set any desired headers to be use in GET/HEAD responses
1297 $headers = $options['headers'] ?? [];
1298
1299 // Archive destination file if it exists.
1300 // This will check if the archive file also exists and fail if does.
1301 // This is a sanity check to avoid data loss. On Windows and Linux,
1302 // copy() will overwrite, so the existence check is vulnerable to
1303 // race conditions unless a functioning LockManager is used.
1304 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1305 $operations[] = [
1306 'op' => 'copy',
1307 'src' => $dstPath,
1308 'dst' => $archivePath,
1309 'ignoreMissingSource' => true
1310 ];
1311
1312 // Copy (or move) the source file to the destination
1313 if ( FileBackend::isStoragePath( $srcPath ) ) {
1314 $operations[] = [
1315 'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1316 'src' => $srcPath,
1317 'dst' => $dstPath,
1318 'overwrite' => true, // replace current
1319 'headers' => $headers
1320 ];
1321 } else {
1322 $operations[] = [
1323 'op' => 'store',
1324 'src' => $src, // storage path (copy) or local path/FSFile (store)
1325 'dst' => $dstPath,
1326 'overwrite' => true, // replace current
1327 'headers' => $headers
1328 ];
1329 if ( $flags & self::DELETE_SOURCE ) {
1330 $sourceFSFilesToDelete[] = $srcPath;
1331 }
1332 }
1333 }
1334
1335 // Execute the operations for each triplet
1336 $status->merge( $backend->doOperations( $operations ) );
1337 // Find out which files were archived...
1338 foreach ( $ntuples as $i => $ntuple ) {
1339 list( , , $archiveRel ) = $ntuple;
1340 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1341 if ( $this->fileExists( $archivePath ) ) {
1342 $status->value[$i] = 'archived';
1343 } else {
1344 $status->value[$i] = 'new';
1345 }
1346 }
1347 // Cleanup for disk source files...
1348 foreach ( $sourceFSFilesToDelete as $file ) {
1349 Wikimedia\suppressWarnings();
1350 unlink( $file ); // FS cleanup
1351 Wikimedia\restoreWarnings();
1352 }
1353
1354 return $status;
1355 }
1356
1364 protected function initDirectory( $dir ) {
1365 $path = $this->resolveToStoragePathIfVirtual( $dir );
1366 list( , $container, ) = FileBackend::splitStoragePath( $path );
1367
1368 $params = [ 'dir' => $path ];
1369 if ( $this->isPrivate
1370 || $container === $this->zones['deleted']['container']
1371 || $container === $this->zones['temp']['container']
1372 ) {
1373 # Take all available measures to prevent web accessibility of new deleted
1374 # directories, in case the user has not configured offline storage
1375 $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1376 }
1377
1378 $status = $this->newGood();
1379 $status->merge( $this->backend->prepare( $params ) );
1380
1381 return $status;
1382 }
1383
1390 public function cleanDir( $dir ) {
1391 $this->assertWritableRepo(); // fail out if read-only
1392
1393 $status = $this->newGood();
1394 $status->merge( $this->backend->clean(
1395 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1396
1397 return $status;
1398 }
1399
1406 public function fileExists( $file ) {
1407 $result = $this->fileExistsBatch( [ $file ] );
1408
1409 return $result[0];
1410 }
1411
1418 public function fileExistsBatch( array $files ) {
1419 $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1420 $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1421
1422 $result = [];
1423 foreach ( $files as $key => $file ) {
1425 $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1426 }
1427
1428 return $result;
1429 }
1430
1441 public function delete( $srcRel, $archiveRel ) {
1442 $this->assertWritableRepo(); // fail out if read-only
1443
1444 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1445 }
1446
1464 public function deleteBatch( array $sourceDestPairs ) {
1465 $this->assertWritableRepo(); // fail out if read-only
1466
1467 // Try creating directories
1468 $status = $this->initZones( [ 'public', 'deleted' ] );
1469 if ( !$status->isOK() ) {
1470 return $status;
1471 }
1472
1473 $status = $this->newGood();
1474
1475 $backend = $this->backend; // convenience
1476 $operations = [];
1477 // Validate filenames and create archive directories
1478 foreach ( $sourceDestPairs as $pair ) {
1479 list( $srcRel, $archiveRel ) = $pair;
1480 if ( !$this->validateFilename( $srcRel ) ) {
1481 throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1482 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1483 throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1484 }
1485
1486 $publicRoot = $this->getZonePath( 'public' );
1487 $srcPath = "{$publicRoot}/$srcRel";
1488
1489 $deletedRoot = $this->getZonePath( 'deleted' );
1490 $archivePath = "{$deletedRoot}/{$archiveRel}";
1491 $archiveDir = dirname( $archivePath ); // does not touch FS
1492
1493 // Create destination directories
1494 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1495 return $this->newFatal( 'directorycreateerror', $archiveDir );
1496 }
1497
1498 $operations[] = [
1499 'op' => 'move',
1500 'src' => $srcPath,
1501 'dst' => $archivePath,
1502 // We may have 2+ identical files being deleted,
1503 // all of which will map to the same destination file
1504 'overwriteSame' => true // also see T33792
1505 ];
1506 }
1507
1508 // Move the files by execute the operations for each pair.
1509 // We're now committed to returning an OK result, which will
1510 // lead to the files being moved in the DB also.
1511 $opts = [ 'force' => true ];
1512 $status->merge( $backend->doOperations( $operations, $opts ) );
1513
1514 return $status;
1515 }
1516
1523 public function cleanupDeletedBatch( array $storageKeys ) {
1524 $this->assertWritableRepo();
1525 }
1526
1535 public function getDeletedHashPath( $key ) {
1536 if ( strlen( $key ) < 31 ) {
1537 throw new MWException( "Invalid storage key '$key'." );
1538 }
1539 $path = '';
1540 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1541 $path .= $key[$i] . '/';
1542 }
1543
1544 return $path;
1545 }
1546
1555 protected function resolveToStoragePathIfVirtual( $path ) {
1556 if ( self::isVirtualUrl( $path ) ) {
1557 return $this->resolveVirtualUrl( $path );
1558 }
1559
1560 return $path;
1561 }
1562
1570 public function getLocalCopy( $virtualUrl ) {
1571 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1572
1573 return $this->backend->getLocalCopy( [ 'src' => $path ] );
1574 }
1575
1584 public function getLocalReference( $virtualUrl ) {
1585 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1586
1587 return $this->backend->getLocalReference( [ 'src' => $path ] );
1588 }
1589
1597 public function getFileProps( $virtualUrl ) {
1598 $fsFile = $this->getLocalReference( $virtualUrl );
1599 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1600 if ( $fsFile ) {
1601 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1602 } else {
1603 $props = $mwProps->newPlaceholderProps();
1604 }
1605
1606 return $props;
1607 }
1608
1615 public function getFileTimestamp( $virtualUrl ) {
1616 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1617
1618 return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1619 }
1620
1627 public function getFileSize( $virtualUrl ) {
1628 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1629
1630 return $this->backend->getFileSize( [ 'src' => $path ] );
1631 }
1632
1639 public function getFileSha1( $virtualUrl ) {
1640 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1641
1642 return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1643 }
1644
1654 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1655 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1656 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1657
1658 // T172851: HHVM does not flush the output properly, causing OOM
1659 ob_start( null, 1048576 );
1660 ob_implicit_flush( true );
1661
1662 $status = $this->newGood();
1663 $status->merge( $this->backend->streamFile( $params ) );
1664
1665 // T186565: Close the buffer, unless it has already been closed
1666 // in HTTPFileStreamer::resetOutputBuffers().
1667 if ( ob_get_status() ) {
1668 ob_end_flush();
1669 }
1670
1671 return $status;
1672 }
1673
1682 public function enumFiles( $callback ) {
1683 $this->enumFilesInStorage( $callback );
1684 }
1685
1693 protected function enumFilesInStorage( $callback ) {
1694 $publicRoot = $this->getZonePath( 'public' );
1695 $numDirs = 1 << ( $this->hashLevels * 4 );
1696 // Use a priori assumptions about directory structure
1697 // to reduce the tree height of the scanning process.
1698 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1699 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1700 $path = $publicRoot;
1701 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1702 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1703 }
1704 $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1705 if ( $iterator === null ) {
1706 throw new MWException( __METHOD__ . ': could not get file listing for ' . $path );
1707 }
1708 foreach ( $iterator as $name ) {
1709 // Each item returned is a public file
1710 call_user_func( $callback, "{$path}/{$name}" );
1711 }
1712 }
1713 }
1714
1721 public function validateFilename( $filename ) {
1722 if ( strval( $filename ) == '' ) {
1723 return false;
1724 }
1725
1726 return FileBackend::isPathTraversalFree( $filename );
1727 }
1728
1734 private function getErrorCleanupFunction() {
1735 switch ( $this->pathDisclosureProtection ) {
1736 case 'none':
1737 case 'simple': // b/c
1738 $callback = [ $this, 'passThrough' ];
1739 break;
1740 default: // 'paranoid'
1741 $callback = [ $this, 'paranoidClean' ];
1742 }
1743 return $callback;
1744 }
1745
1752 public function paranoidClean( $param ) {
1753 return '[hidden]';
1754 }
1755
1762 public function passThrough( $param ) {
1763 return $param;
1764 }
1765
1773 public function newFatal( $message, ...$parameters ) {
1774 $status = Status::newFatal( $message, ...$parameters );
1775 $status->cleanCallback = $this->getErrorCleanupFunction();
1776
1777 return $status;
1778 }
1779
1786 public function newGood( $value = null ) {
1787 $status = Status::newGood( $value );
1788 $status->cleanCallback = $this->getErrorCleanupFunction();
1789
1790 return $status;
1791 }
1792
1801 public function checkRedirect( Title $title ) {
1802 return false;
1803 }
1804
1813 }
1814
1820 public function getDisplayName() {
1821 global $wgSitename;
1822
1823 if ( $this->isLocal() ) {
1824 return $wgSitename;
1825 }
1826
1827 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1828 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1829 }
1830
1838 public function nameForThumb( $name ) {
1839 if ( strlen( $name ) > $this->abbrvThreshold ) {
1841 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1842 }
1843
1844 return $name;
1845 }
1846
1852 public function isLocal() {
1853 return $this->getName() == 'local';
1854 }
1855
1865 public function getSharedCacheKey( ...$args ) {
1866 return false;
1867 }
1868
1877 public function getLocalCacheKey( ...$args ) {
1878 array_unshift( $args, 'filerepo', $this->getName() );
1879
1880 return $this->wanCache->makeKey( ...$args );
1881 }
1882
1891 public function getTempRepo() {
1892 return new TempFileRepo( [
1893 'name' => "{$this->name}-temp",
1894 'backend' => $this->backend,
1895 'zones' => [
1896 'public' => [
1897 // Same place storeTemp() uses in the base repo, though
1898 // the path hashing is mismatched, which is annoying.
1899 'container' => $this->zones['temp']['container'],
1900 'directory' => $this->zones['temp']['directory']
1901 ],
1902 'thumb' => [
1903 'container' => $this->zones['temp']['container'],
1904 'directory' => $this->zones['temp']['directory'] == ''
1905 ? 'thumb'
1906 : $this->zones['temp']['directory'] . '/thumb'
1907 ],
1908 'transcoded' => [
1909 'container' => $this->zones['temp']['container'],
1910 'directory' => $this->zones['temp']['directory'] == ''
1911 ? 'transcoded'
1912 : $this->zones['temp']['directory'] . '/transcoded'
1913 ]
1914 ],
1915 'hashLevels' => $this->hashLevels, // performance
1916 'isPrivate' => true // all in temp zone
1917 ] );
1918 }
1919
1926 public function getUploadStash( User $user = null ) {
1927 return new UploadStash( $this, $user );
1928 }
1929
1937 protected function assertWritableRepo() {
1938 }
1939
1946 public function getInfo() {
1947 $ret = [
1948 'name' => $this->getName(),
1949 'displayname' => $this->getDisplayName(),
1950 'rootUrl' => $this->getZoneUrl( 'public' ),
1951 'local' => $this->isLocal(),
1952 ];
1953
1954 $optionalSettings = [
1955 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1956 'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1957 ];
1958 foreach ( $optionalSettings as $k ) {
1959 if ( isset( $this->$k ) ) {
1960 $ret[$k] = $this->$k;
1961 }
1962 }
1963
1964 return $ret;
1965 }
1966
1971 public function hasSha1Storage() {
1972 return $this->hasSha1Storage;
1973 }
1974
1979 public function supportsSha1URLs() {
1981 }
1982}
$wgSitename
Name of the site.
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.
doOperations(array $ops, array $opts=[])
This is the main entry point into the backend for write operations.
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
Base class for file repositories.
Definition FileRepo.php:41
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition FileRepo.php:102
getSharedCacheKey(... $args)
Get a key on the primary cache for this repository.
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:721
int $hashLevels
The number of directory levels for hash-based division of files.
Definition FileRepo.php:111
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:44
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition FileRepo.php:352
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:526
newFatal( $message,... $parameters)
Create a new fatal error.
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition FileRepo.php:650
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition FileRepo.php:378
string $favicon
The URL of the repo's favicon, if any.
Definition FileRepo.php:123
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:61
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:699
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:632
getHashLevels()
Get the number of hash directory levels.
Definition FileRepo.php:751
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition FileRepo.php:142
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:760
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition FileRepo.php:877
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:449
callable false $oldFileFactoryKey
Override these in the base class.
Definition FileRepo.php:135
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition FileRepo.php:295
const NAME_AND_TIME_ONLY
Definition FileRepo.php:47
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:732
array $zones
Map of zones to config.
Definition FileRepo.php:67
callable false $fileFactoryKey
Override these in the base class.
Definition FileRepo.php:133
getUploadStash(User $user=null)
Get an UploadStash associated with this repo.
getDisplayName()
Get the human-readable name of the repo.
getLocalCacheKey(... $args)
Get a key for this repo in the local cache domain.
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition FileRepo.php:902
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
Definition FileRepo.php:972
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:120
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:771
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:612
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition FileRepo.php:140
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
FileBackend $backend
Definition FileRepo.php:64
fileExistsBatch(array $files)
Checks existence of an array of files.
int $descriptionCacheExpiry
Definition FileRepo.php:55
paranoidClean( $param)
Path disclosure protection function.
WANObjectCache $wanCache
Definition FileRepo.php:145
const SKIP_LOCKING
Definition FileRepo.php:45
initZones( $doZones=[])
Check if a single zone or list of zones is defined for usage.
Definition FileRepo.php:265
string $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:108
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
const OVERWRITE
Definition FileRepo.php:43
isLocal()
Returns true if this the local file repository.
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition FileRepo.php:392
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition FileRepo.php:791
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:58
const DELETE_SOURCE
Definition FileRepo.php:42
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:659
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition FileRepo.php:52
string false $url
Public zone URL.
Definition FileRepo.php:105
callable $fileFactory
Override these in the base class.
Definition FileRepo.php:129
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:283
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition FileRepo.php:850
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition FileRepo.php:75
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
checkRedirect(Title $title)
Checks if there is a redirect named as $title.
bool $isPrivate
Whether all zones should be private (e.g.
Definition FileRepo.php:126
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition FileRepo.php:85
string $descBaseUrl
URL of image description pages, e.g.
Definition FileRepo.php:80
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition FileRepo.php:311
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition FileRepo.php:254
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition FileRepo.php:416
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:668
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:563
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition FileRepo.php:114
string $thumbScriptUrl
URL of thumb.php.
Definition FileRepo.php:70
backendSupportsUnicodePaths()
Definition FileRepo.php:340
__construct(array $info=null)
Definition FileRepo.php:160
string $name
Definition FileRepo.php:152
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition FileRepo.php:95
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:710
getNameFromTitle(Title $title)
Get the name of a file from its title object.
Definition FileRepo.php:678
callable false $oldFileFactory
Override these in the base class.
Definition FileRepo.php:131
invalidateImageRedirect(Title $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
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:88
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition FileRepo.php:825
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:601
getBackend()
Get the file backend instance.
Definition FileRepo.php:244
getInfo()
Return information about the repository.
getThumbScriptUrl()
Get the URL of thumb.php.
Definition FileRepo.php:641
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
MediaWiki exception.
MimeMagic helper wrapper.
MediaWikiServices is the service locator for the application scope of MediaWiki.
FileRepo for temporary files created via FileRepo::getTempRepo()
Represents a title within MediaWiki.
Definition Title.php:42
UploadStash is intended to accomplish a few things:
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:60
Multi-datacenter aware caching interface.
const NS_FILE
Definition Defines.php:76
if( $line===false) $args
Definition mcc.php:124
$source
A helper class for throttling authentication attempts.
return true
Definition router.php:92
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48
if(!isset( $args[0])) $lang