MediaWiki  master
FileRepo.php
Go to the documentation of this file.
1 <?php
16 use Wikimedia\AtEase\AtEase;
17 
47 class FileRepo {
48  public const DELETE_SOURCE = 1;
49  public const OVERWRITE = 2;
50  public const OVERWRITE_SAME = 4;
51  public const SKIP_LOCKING = 8;
52 
53  public const NAME_AND_TIME_ONLY = 1;
54 
59 
62 
64  protected $hasSha1Storage = false;
65 
67  protected $supportsSha1URLs = false;
68 
70  protected $backend;
71 
73  protected $zones = [];
74 
76  protected $thumbScriptUrl;
77 
81  protected $transformVia404;
82 
86  protected $descBaseUrl;
87 
91  protected $scriptDirUrl;
92 
94  protected $articleUrl;
95 
101  protected $initialCapital;
102 
108  protected $pathDisclosureProtection = 'simple';
109 
111  protected $url;
112 
114  protected $thumbUrl;
115 
117  protected $hashLevels;
118 
121 
126  protected $abbrvThreshold;
127 
129  protected $favicon = null;
130 
132  protected $isPrivate;
133 
135  protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
137  protected $oldFileFactory = false;
139  protected $fileFactoryKey = false;
141  protected $oldFileFactoryKey = false;
142 
146  protected $thumbProxyUrl;
148  protected $thumbProxySecret;
149 
151  protected $disableLocalTransform = false;
152 
154  protected $wanCache;
155 
161  public $name;
162 
169  public function __construct( array $info = null ) {
170  // Verify required settings presence
171  if (
172  $info === null
173  || !array_key_exists( 'name', $info )
174  || !array_key_exists( 'backend', $info )
175  ) {
176  throw new MWException( __CLASS__ .
177  " requires an array of options having both 'name' and 'backend' keys.\n" );
178  }
179 
180  // Required settings
181  $this->name = $info['name'];
182  if ( $info['backend'] instanceof FileBackend ) {
183  $this->backend = $info['backend']; // useful for testing
184  } else {
185  $this->backend =
186  MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
187  }
188 
189  // Optional settings that can have no value
190  $optionalSettings = [
191  'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
192  'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
193  'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
194  ];
195  foreach ( $optionalSettings as $var ) {
196  if ( isset( $info[$var] ) ) {
197  $this->$var = $info[$var];
198  }
199  }
200 
201  // Optional settings that have a default
202  $localCapitalLinks =
203  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
204  $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
205  if ( $localCapitalLinks && !$this->initialCapital ) {
206  // If the local wiki's file namespace requires an initial capital, but a foreign file
207  // repo doesn't, complications will result. Linker code will want to auto-capitalize the
208  // first letter of links to files, but those links might actually point to files on
209  // foreign wikis with initial-lowercase names. This combination is not likely to be
210  // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
211  // to include a foreign file repo with initialCapital false, set your local file
212  // namespace to not be capitalized either.
213  throw new InvalidArgumentException(
214  'File repos with initial capital false are not allowed on wikis where the File ' .
215  'namespace has initial capital true' );
216  }
217 
218  $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
219  if ( isset( $info['thumbUrl'] ) ) {
220  $this->thumbUrl = $info['thumbUrl'];
221  } else {
222  $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
223  }
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 
273  protected function initZones( $doZones = [] ): void {
274  foreach ( (array)$doZones as $zone ) {
275  $root = $this->getZonePath( $zone );
276  if ( $root === null ) {
277  throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
278  }
279  }
280  }
281 
288  public static function isVirtualUrl( $url ) {
289  return substr( $url, 0, 9 ) == 'mwrepo://';
290  }
291 
300  public function getVirtualUrl( $suffix = false ) {
301  $path = 'mwrepo://' . $this->name;
302  if ( $suffix !== false ) {
303  $path .= '/' . rawurlencode( $suffix );
304  }
305 
306  return $path;
307  }
308 
316  public function getZoneUrl( $zone, $ext = null ) {
317  if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
318  // standard public zones
319  if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
320  // custom URL for extension/zone
321  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
322  return $this->zones[$zone]['urlsByExt'][$ext];
323  } elseif ( isset( $this->zones[$zone]['url'] ) ) {
324  // custom URL for zone
325  return $this->zones[$zone]['url'];
326  }
327  }
328  switch ( $zone ) {
329  case 'public':
330  return $this->url;
331  case 'temp':
332  case 'deleted':
333  return false; // no public URL
334  case 'thumb':
335  return $this->thumbUrl;
336  case 'transcoded':
337  return "{$this->url}/transcoded";
338  default:
339  return false;
340  }
341  }
342 
346  public function backendSupportsUnicodePaths() {
347  return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
348  }
349 
358  public function resolveVirtualUrl( $url ) {
359  if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
360  throw new MWException( __METHOD__ . ': unknown protocol' );
361  }
362  $bits = explode( '/', substr( $url, 9 ), 3 );
363  if ( count( $bits ) != 3 ) {
364  throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
365  }
366  list( $repo, $zone, $rel ) = $bits;
367  if ( $repo !== $this->name ) {
368  throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
369  }
370  $base = $this->getZonePath( $zone );
371  if ( !$base ) {
372  throw new MWException( __METHOD__ . ": invalid zone: $zone" );
373  }
374 
375  return $base . '/' . rawurldecode( $rel );
376  }
377 
384  protected function getZoneLocation( $zone ) {
385  if ( !isset( $this->zones[$zone] ) ) {
386  return [ null, null ]; // bogus
387  }
388 
389  return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
390  }
391 
398  public function getZonePath( $zone ) {
399  list( $container, $base ) = $this->getZoneLocation( $zone );
400  if ( $container === null || $base === null ) {
401  return null;
402  }
403  $backendName = $this->backend->getName();
404  if ( $base != '' ) { // may not be set
405  $base = "/{$base}";
406  }
407 
408  return "mwstore://$backendName/{$container}{$base}";
409  }
410 
422  public function newFile( $title, $time = false ) {
424  if ( !$title ) {
425  return null;
426  }
427  if ( $time ) {
428  if ( $this->oldFileFactory ) {
429  return call_user_func( $this->oldFileFactory, $title, $this, $time );
430  } else {
431  return null;
432  }
433  } else {
434  return call_user_func( $this->fileFactory, $title, $this );
435  }
436  }
437 
457  public function findFile( $title, $options = [] ) {
458  if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
459  throw new InvalidArgumentException(
460  __METHOD__ . ' called with the `private` option set to something ' .
461  'other than an Authority object'
462  );
463  }
464 
466  if ( !$title ) {
467  return false;
468  }
469  if ( isset( $options['bypassCache'] ) ) {
470  $options['latest'] = $options['bypassCache']; // b/c
471  }
472  $time = $options['time'] ?? false;
473  $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
474  # First try the current version of the file to see if it precedes the timestamp
475  $img = $this->newFile( $title );
476  if ( !$img ) {
477  return false;
478  }
479  $img->load( $flags );
480  if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
481  return $img;
482  }
483  # Now try an old version of the file
484  if ( $time !== false ) {
485  $img = $this->newFile( $title, $time );
486  if ( $img ) {
487  $img->load( $flags );
488  if ( $img->exists() ) {
489  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
490  return $img; // always OK
491  } elseif (
492  // If its not empty, its an Authority object
493  !empty( $options['private'] ) &&
494  $img->userCan( File::DELETED_FILE, $options['private'] )
495  ) {
496  return $img;
497  }
498  }
499  }
500  }
501 
502  # Now try redirects
503  if ( !empty( $options['ignoreRedirect'] ) ) {
504  return false;
505  }
506  $redir = $this->checkRedirect( $title );
507  if ( $redir && $title->getNamespace() === NS_FILE ) {
508  $img = $this->newFile( $redir );
509  if ( !$img ) {
510  return false;
511  }
512  $img->load( $flags );
513  if ( $img->exists() ) {
514  $img->redirectedFrom( $title->getDBkey() );
515 
516  return $img;
517  }
518  }
519 
520  return false;
521  }
522 
540  public function findFiles( array $items, $flags = 0 ) {
541  $result = [];
542  foreach ( $items as $item ) {
543  if ( is_array( $item ) ) {
544  $title = $item['title'];
545  $options = $item;
546  unset( $options['title'] );
547 
548  if (
549  !empty( $options['private'] ) &&
550  !( $options['private'] instanceof Authority )
551  ) {
552  $options['private'] = RequestContext::getMain()->getAuthority();
553  }
554  } else {
555  $title = $item;
556  $options = [];
557  }
558  $file = $this->findFile( $title, $options );
559  if ( $file ) {
560  $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
561  if ( $flags & self::NAME_AND_TIME_ONLY ) {
562  $result[$searchName] = [
563  'title' => $file->getTitle()->getDBkey(),
564  'timestamp' => $file->getTimestamp()
565  ];
566  } else {
567  $result[$searchName] = $file;
568  }
569  }
570  }
571 
572  return $result;
573  }
574 
585  public function findFileFromKey( $sha1, $options = [] ) {
586  if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
587  throw new InvalidArgumentException(
588  __METHOD__ . ' called with the `private` option set to something ' .
589  'other than an Authority object'
590  );
591  }
592 
593  $time = $options['time'] ?? false;
594  # First try to find a matching current version of a file...
595  if ( !$this->fileFactoryKey ) {
596  return false; // find-by-sha1 not supported
597  }
598  $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
599  if ( $img && $img->exists() ) {
600  return $img;
601  }
602  # Now try to find a matching old version of a file...
603  if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
604  $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
605  if ( $img && $img->exists() ) {
606  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
607  return $img; // always OK
608  } elseif (
609  // If its not empty, its an Authority object
610  !empty( $options['private'] ) &&
611  $img->userCan( File::DELETED_FILE, $options['private'] )
612  ) {
613  return $img;
614  }
615  }
616  }
617 
618  return false;
619  }
620 
629  public function findBySha1( $hash ) {
630  return [];
631  }
632 
640  public function findBySha1s( array $hashes ) {
641  $result = [];
642  foreach ( $hashes as $hash ) {
643  $files = $this->findBySha1( $hash );
644  if ( count( $files ) ) {
645  $result[$hash] = $files;
646  }
647  }
648 
649  return $result;
650  }
651 
660  public function findFilesByPrefix( $prefix, $limit ) {
661  return [];
662  }
663 
669  public function getThumbScriptUrl() {
670  return $this->thumbScriptUrl;
671  }
672 
678  public function getThumbProxyUrl() {
679  return $this->thumbProxyUrl;
680  }
681 
687  public function getThumbProxySecret() {
688  return $this->thumbProxySecret;
689  }
690 
696  public function canTransformVia404() {
697  return $this->transformVia404;
698  }
699 
706  public function canTransformLocally() {
707  return !$this->disableLocalTransform;
708  }
709 
716  public function getNameFromTitle( $title ) {
717  if (
718  $this->initialCapital !=
719  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
720  ) {
721  $name = $title->getDBkey();
722  if ( $this->initialCapital ) {
723  $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
724  }
725  } else {
726  $name = $title->getDBkey();
727  }
728 
729  return $name;
730  }
731 
737  public function getRootDirectory() {
738  return $this->getZonePath( 'public' );
739  }
740 
748  public function getHashPath( $name ) {
749  return self::getHashPathForLevel( $name, $this->hashLevels );
750  }
751 
759  public function getTempHashPath( $suffix ) {
760  $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
761  $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
762  return self::getHashPathForLevel( $name, $this->hashLevels );
763  }
764 
770  protected static function getHashPathForLevel( $name, $levels ) {
771  if ( $levels == 0 ) {
772  return '';
773  } else {
774  $hash = md5( $name );
775  $path = '';
776  for ( $i = 1; $i <= $levels; $i++ ) {
777  $path .= substr( $hash, 0, $i ) . '/';
778  }
779 
780  return $path;
781  }
782  }
783 
789  public function getHashLevels() {
790  return $this->hashLevels;
791  }
792 
798  public function getName() {
799  return $this->name;
800  }
801 
809  public function makeUrl( $query = '', $entry = 'index' ) {
810  if ( isset( $this->scriptDirUrl ) ) {
811  return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
812  }
813 
814  return false;
815  }
816 
829  public function getDescriptionUrl( $name ) {
830  $encName = wfUrlencode( $name );
831  if ( $this->descBaseUrl !== null ) {
832  # "http://example.com/wiki/File:"
833  return $this->descBaseUrl . $encName;
834  }
835  if ( $this->articleUrl !== null ) {
836  # "http://example.com/wiki/$1"
837  # We use "Image:" as the canonical namespace for
838  # compatibility across all MediaWiki versions.
839  return str_replace( '$1',
840  "Image:$encName", $this->articleUrl );
841  }
842  if ( $this->scriptDirUrl !== null ) {
843  # "http://example.com/w"
844  # We use "Image:" as the canonical namespace for
845  # compatibility across all MediaWiki versions,
846  # and just sort of hope index.php is right. ;)
847  return $this->makeUrl( "title=Image:$encName" );
848  }
849 
850  return false;
851  }
852 
863  public function getDescriptionRenderUrl( $name, $lang = null ) {
864  $query = 'action=render';
865  if ( $lang !== null ) {
866  $query .= '&uselang=' . urlencode( $lang );
867  }
868  if ( isset( $this->scriptDirUrl ) ) {
869  return $this->makeUrl(
870  'title=' .
871  wfUrlencode( 'Image:' . $name ) .
872  "&$query" );
873  } else {
874  $descUrl = $this->getDescriptionUrl( $name );
875  if ( $descUrl ) {
876  return wfAppendQuery( $descUrl, $query );
877  } else {
878  return false;
879  }
880  }
881  }
882 
888  public function getDescriptionStylesheetUrl() {
889  if ( isset( $this->scriptDirUrl ) ) {
890  // Must match canonical query parameter order for optimum caching
891  // See HtmlCacheUpdater::getUrls
892  return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
893  }
894 
895  return false;
896  }
897 
915  public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
916  $this->assertWritableRepo(); // fail out if read-only
917 
918  $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
919  if ( $status->successCount == 0 ) {
920  $status->setOK( false );
921  }
922 
923  return $status;
924  }
925 
940  public function storeBatch( array $triplets, $flags = 0 ) {
941  $this->assertWritableRepo(); // fail out if read-only
942 
943  if ( $flags & self::DELETE_SOURCE ) {
944  throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
945  }
946 
947  $status = $this->newGood();
948  $backend = $this->backend; // convenience
949 
950  $operations = [];
951  // Validate each triplet and get the store operation...
952  foreach ( $triplets as $triplet ) {
953  list( $src, $dstZone, $dstRel ) = $triplet;
954  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
955  wfDebug( __METHOD__
956  . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
957  );
958  // Resolve source path
959  if ( $src instanceof FSFile ) {
960  $op = 'store';
961  } else {
962  $src = $this->resolveToStoragePathIfVirtual( $src );
963  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
964  }
965  // Resolve destination path
966  $root = $this->getZonePath( $dstZone );
967  if ( !$root ) {
968  throw new MWException( "Invalid zone: $dstZone" );
969  }
970  if ( !$this->validateFilename( $dstRel ) ) {
971  throw new MWException( 'Validation error in $dstRel' );
972  }
973  $dstPath = "$root/$dstRel";
974  $dstDir = dirname( $dstPath );
975  // Create destination directories for this triplet
976  if ( !$this->initDirectory( $dstDir )->isOK() ) {
977  return $this->newFatal( 'directorycreateerror', $dstDir );
978  }
979 
980  // Copy the source file to the destination
981  $operations[] = [
982  'op' => $op,
983  'src' => $src, // storage path (copy) or local file path (store)
984  'dst' => $dstPath,
985  'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
986  'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
987  ];
988  }
989 
990  // Execute the store operation for each triplet
991  $opts = [ 'force' => true ];
992  if ( $flags & self::SKIP_LOCKING ) {
993  $opts['nonLocking'] = true;
994  }
995 
996  return $status->merge( $backend->doOperations( $operations, $opts ) );
997  }
998 
1009  public function cleanupBatch( array $files, $flags = 0 ) {
1010  $this->assertWritableRepo(); // fail out if read-only
1011 
1012  $status = $this->newGood();
1013 
1014  $operations = [];
1015  foreach ( $files as $path ) {
1016  if ( is_array( $path ) ) {
1017  // This is a pair, extract it
1018  list( $zone, $rel ) = $path;
1019  $path = $this->getZonePath( $zone ) . "/$rel";
1020  } else {
1021  // Resolve source to a storage path if virtual
1022  $path = $this->resolveToStoragePathIfVirtual( $path );
1023  }
1024  $operations[] = [ 'op' => 'delete', 'src' => $path ];
1025  }
1026  // Actually delete files from storage...
1027  $opts = [ 'force' => true ];
1028  if ( $flags & self::SKIP_LOCKING ) {
1029  $opts['nonLocking'] = true;
1030  }
1031 
1032  return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1033  }
1034 
1052  final public function quickImport( $src, $dst, $options = null ) {
1053  return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1054  }
1055 
1070  public function quickImportBatch( array $triples ) {
1071  $status = $this->newGood();
1072  $operations = [];
1073  foreach ( $triples as $triple ) {
1074  list( $src, $dst ) = $triple;
1075  if ( $src instanceof FSFile ) {
1076  $op = 'store';
1077  } else {
1078  $src = $this->resolveToStoragePathIfVirtual( $src );
1079  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1080  }
1081  $dst = $this->resolveToStoragePathIfVirtual( $dst );
1082 
1083  if ( !isset( $triple[2] ) ) {
1084  $headers = [];
1085  } elseif ( is_string( $triple[2] ) ) {
1086  // back-compat
1087  $headers = [ 'Content-Disposition' => $triple[2] ];
1088  } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1089  $headers = $triple[2]['headers'];
1090  } else {
1091  $headers = [];
1092  }
1093 
1094  $operations[] = [
1095  'op' => $op,
1096  'src' => $src, // storage path (copy) or local path/FSFile (store)
1097  'dst' => $dst,
1098  'headers' => $headers
1099  ];
1100  $status->merge( $this->initDirectory( dirname( $dst ) ) );
1101  }
1102 
1103  return $status->merge( $this->backend->doQuickOperations( $operations ) );
1104  }
1105 
1114  final public function quickPurge( $path ) {
1115  return $this->quickPurgeBatch( [ $path ] );
1116  }
1117 
1125  public function quickCleanDir( $dir ) {
1126  return $this->newGood()->merge(
1127  $this->backend->clean(
1128  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1129  )
1130  );
1131  }
1132 
1141  public function quickPurgeBatch( array $paths ) {
1142  $status = $this->newGood();
1143  $operations = [];
1144  foreach ( $paths as $path ) {
1145  $operations[] = [
1146  'op' => 'delete',
1147  'src' => $this->resolveToStoragePathIfVirtual( $path ),
1148  'ignoreMissingSource' => true
1149  ];
1150  }
1151  $status->merge( $this->backend->doQuickOperations( $operations ) );
1152 
1153  return $status;
1154  }
1155 
1166  public function storeTemp( $originalName, $srcPath ) {
1167  $this->assertWritableRepo(); // fail out if read-only
1168 
1169  $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1170  $hashPath = $this->getHashPath( $originalName );
1171  $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1172  $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1173 
1174  $result = $this->quickImport( $srcPath, $virtualUrl );
1175  $result->value = $virtualUrl;
1176 
1177  return $result;
1178  }
1179 
1186  public function freeTemp( $virtualUrl ) {
1187  $this->assertWritableRepo(); // fail out if read-only
1188 
1189  $temp = $this->getVirtualUrl( 'temp' );
1190  if ( !str_starts_with( $virtualUrl, $temp ) ) {
1191  wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1192 
1193  return false;
1194  }
1195 
1196  return $this->quickPurge( $virtualUrl )->isOK();
1197  }
1198 
1208  public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1209  $this->assertWritableRepo(); // fail out if read-only
1210 
1211  $status = $this->newGood();
1212 
1213  $sources = [];
1214  foreach ( $srcPaths as $srcPath ) {
1215  // Resolve source to a storage path if virtual
1216  $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1217  $sources[] = $source; // chunk to merge
1218  }
1219 
1220  // Concatenate the chunks into one FS file
1221  $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1222  $status->merge( $this->backend->concatenate( $params ) );
1223  if ( !$status->isOK() ) {
1224  return $status;
1225  }
1226 
1227  // Delete the sources if required
1228  if ( $flags & self::DELETE_SOURCE ) {
1229  $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1230  }
1231 
1232  // Make sure status is OK, despite any quickPurgeBatch() fatals
1233  $status->setResult( true );
1234 
1235  return $status;
1236  }
1237 
1261  public function publish(
1262  $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1263  ) {
1264  $this->assertWritableRepo(); // fail out if read-only
1265 
1266  $status = $this->publishBatch(
1267  [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1268  if ( $status->successCount == 0 ) {
1269  $status->setOK( false );
1270  }
1271  $status->value = $status->value[0] ?? false;
1272 
1273  return $status;
1274  }
1275 
1288  public function publishBatch( array $ntuples, $flags = 0 ) {
1289  $this->assertWritableRepo(); // fail out if read-only
1290 
1291  $backend = $this->backend; // convenience
1292  // Try creating directories
1293  $this->initZones( 'public' );
1294 
1295  $status = $this->newGood( [] );
1296 
1297  $operations = [];
1298  $sourceFSFilesToDelete = []; // cleanup for disk source files
1299  // Validate each triplet and get the store operation...
1300  foreach ( $ntuples as $ntuple ) {
1301  list( $src, $dstRel, $archiveRel ) = $ntuple;
1302  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1303 
1304  $options = $ntuple[3] ?? [];
1305  // Resolve source to a storage path if virtual
1306  $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1307  if ( !$this->validateFilename( $dstRel ) ) {
1308  throw new MWException( 'Validation error in $dstRel' );
1309  }
1310  if ( !$this->validateFilename( $archiveRel ) ) {
1311  throw new MWException( 'Validation error in $archiveRel' );
1312  }
1313 
1314  $publicRoot = $this->getZonePath( 'public' );
1315  $dstPath = "$publicRoot/$dstRel";
1316  $archivePath = "$publicRoot/$archiveRel";
1317 
1318  $dstDir = dirname( $dstPath );
1319  $archiveDir = dirname( $archivePath );
1320  // Abort immediately on directory creation errors since they're likely to be repetitive
1321  if ( !$this->initDirectory( $dstDir )->isOK() ) {
1322  return $this->newFatal( 'directorycreateerror', $dstDir );
1323  }
1324  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1325  return $this->newFatal( 'directorycreateerror', $archiveDir );
1326  }
1327 
1328  // Set any desired headers to be use in GET/HEAD responses
1329  $headers = $options['headers'] ?? [];
1330 
1331  // Archive destination file if it exists.
1332  // This will check if the archive file also exists and fail if does.
1333  // This is a check to avoid data loss. On Windows and Linux,
1334  // copy() will overwrite, so the existence check is vulnerable to
1335  // race conditions unless a functioning LockManager is used.
1336  // LocalFile also uses SELECT FOR UPDATE for synchronization.
1337  $operations[] = [
1338  'op' => 'copy',
1339  'src' => $dstPath,
1340  'dst' => $archivePath,
1341  'ignoreMissingSource' => true
1342  ];
1343 
1344  // Copy (or move) the source file to the destination
1345  if ( FileBackend::isStoragePath( $srcPath ) ) {
1346  $operations[] = [
1347  'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1348  'src' => $srcPath,
1349  'dst' => $dstPath,
1350  'overwrite' => true, // replace current
1351  'headers' => $headers
1352  ];
1353  } else {
1354  $operations[] = [
1355  'op' => 'store',
1356  'src' => $src, // storage path (copy) or local path/FSFile (store)
1357  'dst' => $dstPath,
1358  'overwrite' => true, // replace current
1359  'headers' => $headers
1360  ];
1361  if ( $flags & self::DELETE_SOURCE ) {
1362  $sourceFSFilesToDelete[] = $srcPath;
1363  }
1364  }
1365  }
1366 
1367  // Execute the operations for each triplet
1368  $status->merge( $backend->doOperations( $operations ) );
1369  // Find out which files were archived...
1370  foreach ( $ntuples as $i => $ntuple ) {
1371  list( , , $archiveRel ) = $ntuple;
1372  $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1373  if ( $this->fileExists( $archivePath ) ) {
1374  $status->value[$i] = 'archived';
1375  } else {
1376  $status->value[$i] = 'new';
1377  }
1378  }
1379  // Cleanup for disk source files...
1380  foreach ( $sourceFSFilesToDelete as $file ) {
1381  AtEase::suppressWarnings();
1382  unlink( $file ); // FS cleanup
1383  AtEase::restoreWarnings();
1384  }
1385 
1386  return $status;
1387  }
1388 
1396  protected function initDirectory( $dir ) {
1397  $path = $this->resolveToStoragePathIfVirtual( $dir );
1398  list( , $container, ) = FileBackend::splitStoragePath( $path );
1399 
1400  $params = [ 'dir' => $path ];
1401  if ( $this->isPrivate
1402  || $container === $this->zones['deleted']['container']
1403  || $container === $this->zones['temp']['container']
1404  ) {
1405  # Take all available measures to prevent web accessibility of new deleted
1406  # directories, in case the user has not configured offline storage
1407  $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1408  }
1409 
1410  return $this->newGood()->merge( $this->backend->prepare( $params ) );
1411  }
1412 
1419  public function cleanDir( $dir ) {
1420  $this->assertWritableRepo(); // fail out if read-only
1421 
1422  return $this->newGood()->merge(
1423  $this->backend->clean(
1424  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1425  )
1426  );
1427  }
1428 
1435  public function fileExists( $file ) {
1436  $result = $this->fileExistsBatch( [ $file ] );
1437 
1438  return $result[0];
1439  }
1440 
1448  public function fileExistsBatch( array $files ) {
1449  $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1450  $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1451 
1452  $result = [];
1453  foreach ( $files as $key => $file ) {
1454  $path = $this->resolveToStoragePathIfVirtual( $file );
1455  $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1456  }
1457 
1458  return $result;
1459  }
1460 
1471  public function delete( $srcRel, $archiveRel ) {
1472  $this->assertWritableRepo(); // fail out if read-only
1473 
1474  return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1475  }
1476 
1494  public function deleteBatch( array $sourceDestPairs ) {
1495  $this->assertWritableRepo(); // fail out if read-only
1496 
1497  // Try creating directories
1498  $this->initZones( [ 'public', 'deleted' ] );
1499 
1500  $status = $this->newGood();
1501 
1502  $backend = $this->backend; // convenience
1503  $operations = [];
1504  // Validate filenames and create archive directories
1505  foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1506  if ( !$this->validateFilename( $srcRel ) ) {
1507  throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1508  } elseif ( !$this->validateFilename( $archiveRel ) ) {
1509  throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1510  }
1511 
1512  $publicRoot = $this->getZonePath( 'public' );
1513  $srcPath = "{$publicRoot}/$srcRel";
1514 
1515  $deletedRoot = $this->getZonePath( 'deleted' );
1516  $archivePath = "{$deletedRoot}/{$archiveRel}";
1517  $archiveDir = dirname( $archivePath ); // does not touch FS
1518 
1519  // Create destination directories
1520  if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1521  return $this->newFatal( 'directorycreateerror', $archiveDir );
1522  }
1523 
1524  $operations[] = [
1525  'op' => 'move',
1526  'src' => $srcPath,
1527  'dst' => $archivePath,
1528  // We may have 2+ identical files being deleted,
1529  // all of which will map to the same destination file
1530  'overwriteSame' => true // also see T33792
1531  ];
1532  }
1533 
1534  // Move the files by execute the operations for each pair.
1535  // We're now committed to returning an OK result, which will
1536  // lead to the files being moved in the DB also.
1537  $opts = [ 'force' => true ];
1538  return $status->merge( $backend->doOperations( $operations, $opts ) );
1539  }
1540 
1547  public function cleanupDeletedBatch( array $storageKeys ) {
1548  $this->assertWritableRepo();
1549  }
1550 
1559  public function getDeletedHashPath( $key ) {
1560  if ( strlen( $key ) < 31 ) {
1561  throw new MWException( "Invalid storage key '$key'." );
1562  }
1563  $path = '';
1564  for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1565  $path .= $key[$i] . '/';
1566  }
1567 
1568  return $path;
1569  }
1570 
1579  protected function resolveToStoragePathIfVirtual( $path ) {
1580  if ( self::isVirtualUrl( $path ) ) {
1581  return $this->resolveVirtualUrl( $path );
1582  }
1583 
1584  return $path;
1585  }
1586 
1594  public function getLocalCopy( $virtualUrl ) {
1595  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1596 
1597  return $this->backend->getLocalCopy( [ 'src' => $path ] );
1598  }
1599 
1608  public function getLocalReference( $virtualUrl ) {
1609  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1610 
1611  return $this->backend->getLocalReference( [ 'src' => $path ] );
1612  }
1613 
1621  public function getFileProps( $virtualUrl ) {
1622  $fsFile = $this->getLocalReference( $virtualUrl );
1623  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1624  if ( $fsFile ) {
1625  $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1626  } else {
1627  $props = $mwProps->newPlaceholderProps();
1628  }
1629 
1630  return $props;
1631  }
1632 
1639  public function getFileTimestamp( $virtualUrl ) {
1640  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1641 
1642  return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1643  }
1644 
1651  public function getFileSize( $virtualUrl ) {
1652  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1653 
1654  return $this->backend->getFileSize( [ 'src' => $path ] );
1655  }
1656 
1663  public function getFileSha1( $virtualUrl ) {
1664  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1665 
1666  return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1667  }
1668 
1678  public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1679  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1680  $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1681 
1682  // T172851: HHVM does not flush the output properly, causing OOM
1683  ob_start( null, 1048576 );
1684  ob_implicit_flush( true );
1685 
1686  $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1687 
1688  // T186565: Close the buffer, unless it has already been closed
1689  // in HTTPFileStreamer::resetOutputBuffers().
1690  if ( ob_get_status() ) {
1691  ob_end_flush();
1692  }
1693 
1694  return $status;
1695  }
1696 
1705  public function enumFiles( $callback ) {
1706  $this->enumFilesInStorage( $callback );
1707  }
1708 
1716  protected function enumFilesInStorage( $callback ) {
1717  $publicRoot = $this->getZonePath( 'public' );
1718  $numDirs = 1 << ( $this->hashLevels * 4 );
1719  // Use a priori assumptions about directory structure
1720  // to reduce the tree height of the scanning process.
1721  for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1722  $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1723  $path = $publicRoot;
1724  for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1725  $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1726  }
1727  $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1728  if ( $iterator === null ) {
1729  throw new MWException( __METHOD__ . ': could not get file listing for ' . $path );
1730  }
1731  foreach ( $iterator as $name ) {
1732  // Each item returned is a public file
1733  call_user_func( $callback, "{$path}/{$name}" );
1734  }
1735  }
1736  }
1737 
1744  public function validateFilename( $filename ) {
1745  if ( strval( $filename ) == '' ) {
1746  return false;
1747  }
1748 
1749  return FileBackend::isPathTraversalFree( $filename );
1750  }
1751 
1757  private function getErrorCleanupFunction() {
1758  switch ( $this->pathDisclosureProtection ) {
1759  case 'none':
1760  case 'simple': // b/c
1761  $callback = [ $this, 'passThrough' ];
1762  break;
1763  default: // 'paranoid'
1764  $callback = [ $this, 'paranoidClean' ];
1765  }
1766  return $callback;
1767  }
1768 
1775  public function paranoidClean( $param ) {
1776  return '[hidden]';
1777  }
1778 
1785  public function passThrough( $param ) {
1786  return $param;
1787  }
1788 
1796  public function newFatal( $message, ...$parameters ) {
1797  $status = Status::newFatal( $message, ...$parameters );
1798  $status->cleanCallback = $this->getErrorCleanupFunction();
1799 
1800  return $status;
1801  }
1802 
1809  public function newGood( $value = null ) {
1810  $status = Status::newGood( $value );
1811  $status->cleanCallback = $this->getErrorCleanupFunction();
1812 
1813  return $status;
1814  }
1815 
1824  public function checkRedirect( $title ) {
1825  return false;
1826  }
1827 
1835  public function invalidateImageRedirect( $title ) {
1836  }
1837 
1843  public function getDisplayName() {
1844  $sitename = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Sitename );
1845 
1846  if ( $this->isLocal() ) {
1847  return $sitename;
1848  }
1849 
1850  // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1851  return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1852  }
1853 
1861  public function nameForThumb( $name ) {
1862  if ( strlen( $name ) > $this->abbrvThreshold ) {
1864  $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1865  }
1866 
1867  return $name;
1868  }
1869 
1875  public function isLocal() {
1876  return $this->getName() == 'local';
1877  }
1878 
1890  public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1891  return false;
1892  }
1893 
1905  public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1906  return $this->wanCache->makeKey(
1907  'filerepo-' . $kClassSuffix,
1908  $this->getName(),
1909  ...$components
1910  );
1911  }
1912 
1921  public function getTempRepo() {
1922  return new TempFileRepo( [
1923  'name' => "{$this->name}-temp",
1924  'backend' => $this->backend,
1925  'zones' => [
1926  'public' => [
1927  // Same place storeTemp() uses in the base repo, though
1928  // the path hashing is mismatched, which is annoying.
1929  'container' => $this->zones['temp']['container'],
1930  'directory' => $this->zones['temp']['directory']
1931  ],
1932  'thumb' => [
1933  'container' => $this->zones['temp']['container'],
1934  'directory' => $this->zones['temp']['directory'] == ''
1935  ? 'thumb'
1936  : $this->zones['temp']['directory'] . '/thumb'
1937  ],
1938  'transcoded' => [
1939  'container' => $this->zones['temp']['container'],
1940  'directory' => $this->zones['temp']['directory'] == ''
1941  ? 'transcoded'
1942  : $this->zones['temp']['directory'] . '/transcoded'
1943  ]
1944  ],
1945  'hashLevels' => $this->hashLevels, // performance
1946  'isPrivate' => true // all in temp zone
1947  ] );
1948  }
1949 
1956  public function getUploadStash( UserIdentity $user = null ) {
1957  return new UploadStash( $this, $user );
1958  }
1959 
1967  protected function assertWritableRepo() {
1968  }
1969 
1976  public function getInfo() {
1977  $ret = [
1978  'name' => $this->getName(),
1979  'displayname' => $this->getDisplayName(),
1980  'rootUrl' => $this->getZoneUrl( 'public' ),
1981  'local' => $this->isLocal(),
1982  ];
1983 
1984  $optionalSettings = [
1985  'url',
1986  'thumbUrl',
1987  'initialCapital',
1988  'descBaseUrl',
1989  'scriptDirUrl',
1990  'articleUrl',
1991  'fetchDescription',
1992  'descriptionCacheExpiry',
1993  ];
1994  foreach ( $optionalSettings as $k ) {
1995  if ( isset( $this->$k ) ) {
1996  $ret[$k] = $this->$k;
1997  }
1998  }
1999  if ( isset( $this->favicon ) ) {
2000  // Expand any local path to full URL to improve API usability (T77093).
2001  $ret['favicon'] = wfExpandUrl( $this->favicon );
2002  }
2003 
2004  return $ret;
2005  }
2006 
2011  public function hasSha1Storage() {
2012  return $this->hasSha1Storage;
2013  }
2014 
2019  public function supportsSha1URLs() {
2020  return $this->supportsSha1URLs;
2021  }
2022 }
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,...
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
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).
Definition: FileBackend.php:99
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:47
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition: FileRepo.php:108
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:759
int $hashLevels
The number of directory levels for hash-based division of files.
Definition: FileRepo.php:117
getTempRepo()
Get a temporary private FileRepo associated with this repo.
Definition: FileRepo.php:1921
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table.
Definition: FileRepo.php:1547
const OVERWRITE_SAME
Definition: FileRepo.php:50
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:358
nameForThumb( $name)
Get the portion of the file that contains the origin file name.
Definition: FileRepo.php:1861
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
Definition: FileRepo.php:1288
findFiles(array $items, $flags=0)
Find many files at once.
Definition: FileRepo.php:540
newFatal( $message,... $parameters)
Create a new fatal error.
Definition: FileRepo.php:1796
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition: FileRepo.php:678
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition: FileRepo.php:384
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1435
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1663
bool $supportsSha1URLs
Definition: FileRepo.php:67
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
Definition: FileRepo.php:1070
assertWritableRepo()
Throw an exception if this repo is read-only by design.
Definition: FileRepo.php:1967
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition: FileRepo.php:737
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
Definition: FileRepo.php:2019
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1809
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition: FileRepo.php:660
getHashLevels()
Get the number of hash directory levels.
Definition: FileRepo.php:789
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition: FileRepo.php:148
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
Definition: FileRepo.php:1678
getName()
Get the name of this repository, as specified by $info['name]' to the constructor.
Definition: FileRepo.php:798
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition: FileRepo.php:915
findFile( $title, $options=[])
Find an instance of the named file created at the specified time Returns false if the file does not e...
Definition: FileRepo.php:457
callable false $oldFileFactoryKey
Override these in the base class.
Definition: FileRepo.php:141
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:300
const NAME_AND_TIME_ONLY
Definition: FileRepo.php:53
quickPurge( $path)
Purge a file from the repo.
Definition: FileRepo.php:1114
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
Definition: FileRepo.php:1141
passThrough( $param)
Path disclosure protection function.
Definition: FileRepo.php:1785
static getHashPathForLevel( $name, $levels)
Definition: FileRepo.php:770
array $zones
Map of zones to config.
Definition: FileRepo.php:73
callable false $fileFactoryKey
Override these in the base class.
Definition: FileRepo.php:139
checkRedirect( $title)
Checks if there is a redirect named as $title.
Definition: FileRepo.php:1824
getDisplayName()
Get the human-readable name of the repo.
Definition: FileRepo.php:1843
getSharedCacheKey( $kClassSuffix,... $components)
Get a global, repository-qualified, WAN cache key.
Definition: FileRepo.php:1890
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
Definition: FileRepo.php:1905
bool $disableLocalTransform
Disable local image scaling.
Definition: FileRepo.php:151
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:940
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
Definition: FileRepo.php:1705
canTransformLocally()
Returns true if the repository can transform files locally.
Definition: FileRepo.php:706
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:2011
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
Definition: FileRepo.php:1009
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...
Definition: FileRepo.php:1261
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
Definition: FileRepo.php:1396
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
Definition: FileRepo.php:126
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition: FileRepo.php:809
findBySha1s(array $hashes)
Get an array of arrays or iterators of file objects for files that have the given SHA-1 content hashe...
Definition: FileRepo.php:640
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition: FileRepo.php:146
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
Definition: FileRepo.php:1208
FileBackend $backend
Definition: FileRepo.php:70
null string $favicon
The URL to a favicon (optional, may be a server-local path URL).
Definition: FileRepo.php:129
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1448
int $descriptionCacheExpiry
Definition: FileRepo.php:61
paranoidClean( $param)
Path disclosure protection function.
Definition: FileRepo.php:1775
WANObjectCache $wanCache
Definition: FileRepo.php:154
const SKIP_LOCKING
Definition: FileRepo.php:51
initZones( $doZones=[])
Ensure that a single zone or list of zones is defined for usage.
Definition: FileRepo.php:273
string $thumbUrl
The base thumbnail URL.
Definition: FileRepo.php:114
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1621
const OVERWRITE
Definition: FileRepo.php:49
isLocal()
Returns true if this the local file repository.
Definition: FileRepo.php:1875
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition: FileRepo.php:398
getUploadStash(UserIdentity $user=null)
Get an UploadStash associated with this repo.
Definition: FileRepo.php:1956
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition: FileRepo.php:829
cleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1419
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
Definition: FileRepo.php:1579
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1559
bool $hasSha1Storage
Definition: FileRepo.php:64
const DELETE_SOURCE
Definition: FileRepo.php:48
getNameFromTitle( $title)
Get the name of a file from its title.
Definition: FileRepo.php:716
invalidateImageRedirect( $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
Definition: FileRepo.php:1835
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1651
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition: FileRepo.php:687
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition: FileRepo.php:58
string false $url
Public zone URL.
Definition: FileRepo.php:111
callable $fileFactory
Override these in the base class.
Definition: FileRepo.php:135
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:288
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition: FileRepo.php:888
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition: FileRepo.php:81
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1639
bool $isPrivate
Whether all zones should be private (e.g.
Definition: FileRepo.php:132
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition: FileRepo.php:91
string $descBaseUrl
URL of image description pages, e.g.
Definition: FileRepo.php:86
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition: FileRepo.php:316
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:263
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition: FileRepo.php:422
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
Definition: FileRepo.php:1166
quickCleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1125
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
Definition: FileRepo.php:696
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
Definition: FileRepo.php:1716
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Definition: FileRepo.php:1744
findFileFromKey( $sha1, $options=[])
Find an instance of the file with this key, created at the specified time Returns false if the file d...
Definition: FileRepo.php:585
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition: FileRepo.php:120
string $thumbScriptUrl
URL of thumb.php.
Definition: FileRepo.php:76
backendSupportsUnicodePaths()
Definition: FileRepo.php:346
__construct(array $info=null)
Definition: FileRepo.php:169
string $name
Definition: FileRepo.php:161
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition: FileRepo.php:101
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1594
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
Definition: FileRepo.php:1494
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
Definition: FileRepo.php:1757
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:748
callable false $oldFileFactory
Override these in the base class.
Definition: FileRepo.php:137
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1052
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition: FileRepo.php:94
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition: FileRepo.php:863
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
Definition: FileRepo.php:1186
findBySha1( $hash)
Get an array or iterator of file objects for files that have a given SHA-1 content hash.
Definition: FileRepo.php:629
getBackend()
Get the file backend instance.
Definition: FileRepo.php:253
getInfo()
Return information about the repository.
Definition: FileRepo.php:1976
getThumbScriptUrl()
Get the URL of thumb.php.
Definition: FileRepo.php:669
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
Definition: FileRepo.php:1608
static normalizeTitle( $title, $exception=false)
Given a string or Title object return either a valid Title object with namespace NS_FILE or null.
Definition: File.php:207
const DELETED_FILE
Definition: File.php:72
MediaWiki exception.
Definition: MWException.php:29
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:46
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
static getMain()
Get the RequestContext object associated with the main request.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
FileRepo for temporary files created by FileRepo::getTempRepo()
Definition: TempFileRepo.php:8
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:57
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Interface for objects (potentially) representing an editable wiki page.
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
Interface for objects representing user identity.
$source
return true
Definition: router.php:90
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