MediaWiki  master
FileRepo.php
Go to the documentation of this file.
1 <?php
11 
39 class FileRepo {
40  const DELETE_SOURCE = 1;
41  const OVERWRITE = 2;
42  const OVERWRITE_SAME = 4;
43  const SKIP_LOCKING = 8;
44 
45  const NAME_AND_TIME_ONLY = 1;
46 
51 
54 
56  protected $hasSha1Storage = false;
57 
59  protected $supportsSha1URLs = false;
60 
62  protected $backend;
63 
65  protected $zones = [];
66 
68  protected $thumbScriptUrl;
69 
73  protected $transformVia404;
74 
78  protected $descBaseUrl;
79 
83  protected $scriptDirUrl;
84 
86  protected $articleUrl;
87 
93  protected $initialCapital;
94 
100  protected $pathDisclosureProtection = 'simple';
101 
103  protected $url;
104 
106  protected $thumbUrl;
107 
109  protected $hashLevels;
110 
113 
118  protected $abbrvThreshold;
119 
121  protected $favicon;
122 
124  protected $isPrivate;
125 
127  protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
129  protected $oldFileFactory = false;
131  protected $fileFactoryKey = false;
133  protected $oldFileFactoryKey = false;
134 
138  protected $thumbProxyUrl;
140  protected $thumbProxySecret;
141 
143  protected $wanCache;
144 
149  public $name;
150 
156  public function __construct( array $info = null ) {
157  // Verify required settings presence
158  if (
159  $info === null
160  || !array_key_exists( 'name', $info )
161  || !array_key_exists( 'backend', $info )
162  ) {
163  throw new MWException( __CLASS__ .
164  " requires an array of options having both 'name' and 'backend' keys.\n" );
165  }
166 
167  // Required settings
168  $this->name = $info['name'];
169  if ( $info['backend'] instanceof FileBackend ) {
170  $this->backend = $info['backend']; // useful for testing
171  } else {
172  $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
173  }
174 
175  // Optional settings that can have no value
176  $optionalSettings = [
177  'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
178  'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
179  'favicon', 'thumbProxyUrl', 'thumbProxySecret',
180  ];
181  foreach ( $optionalSettings as $var ) {
182  if ( isset( $info[$var] ) ) {
183  $this->$var = $info[$var];
184  }
185  }
186 
187  // Optional settings that have a default
188  $this->initialCapital = $info['initialCapital'] ??
189  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
190  $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
191  if ( isset( $info['thumbUrl'] ) ) {
192  $this->thumbUrl = $info['thumbUrl'];
193  } else {
194  $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
195  }
196  $this->hashLevels = $info['hashLevels'] ?? 2;
197  $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
198  $this->transformVia404 = !empty( $info['transformVia404'] );
199  $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
200  $this->isPrivate = !empty( $info['isPrivate'] );
201  // Give defaults for the basic zones...
202  $this->zones = $info['zones'] ?? [];
203  foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
204  if ( !isset( $this->zones[$zone]['container'] ) ) {
205  $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
206  }
207  if ( !isset( $this->zones[$zone]['directory'] ) ) {
208  $this->zones[$zone]['directory'] = '';
209  }
210  if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
211  $this->zones[$zone]['urlsByExt'] = [];
212  }
213  }
214 
215  $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
216 
217  $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
218  }
219 
225  public function getBackend() {
226  return $this->backend;
227  }
228 
235  public function getReadOnlyReason() {
236  return $this->backend->getReadOnlyReason();
237  }
238 
246  protected function initZones( $doZones = [] ) {
247  $status = $this->newGood();
248  foreach ( (array)$doZones as $zone ) {
249  $root = $this->getZonePath( $zone );
250  if ( $root === null ) {
251  throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
252  }
253  }
254 
255  return $status;
256  }
257 
264  public static function isVirtualUrl( $url ) {
265  return substr( $url, 0, 9 ) == 'mwrepo://';
266  }
267 
276  public function getVirtualUrl( $suffix = false ) {
277  $path = 'mwrepo://' . $this->name;
278  if ( $suffix !== false ) {
279  $path .= '/' . rawurlencode( $suffix );
280  }
281 
282  return $path;
283  }
284 
292  public function getZoneUrl( $zone, $ext = null ) {
293  if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
294  // standard public zones
295  if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
296  // custom URL for extension/zone
297  return $this->zones[$zone]['urlsByExt'][$ext];
298  } elseif ( isset( $this->zones[$zone]['url'] ) ) {
299  // custom URL for zone
300  return $this->zones[$zone]['url'];
301  }
302  }
303  switch ( $zone ) {
304  case 'public':
305  return $this->url;
306  case 'temp':
307  case 'deleted':
308  return false; // no public URL
309  case 'thumb':
310  return $this->thumbUrl;
311  case 'transcoded':
312  return "{$this->url}/transcoded";
313  default:
314  return false;
315  }
316  }
317 
321  public function backendSupportsUnicodePaths() {
322  return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
323  }
324 
333  public function resolveVirtualUrl( $url ) {
334  if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
335  throw new MWException( __METHOD__ . ': unknown protocol' );
336  }
337  $bits = explode( '/', substr( $url, 9 ), 3 );
338  if ( count( $bits ) != 3 ) {
339  throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
340  }
341  list( $repo, $zone, $rel ) = $bits;
342  if ( $repo !== $this->name ) {
343  throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
344  }
345  $base = $this->getZonePath( $zone );
346  if ( !$base ) {
347  throw new MWException( __METHOD__ . ": invalid zone: $zone" );
348  }
349 
350  return $base . '/' . rawurldecode( $rel );
351  }
352 
359  protected function getZoneLocation( $zone ) {
360  if ( !isset( $this->zones[$zone] ) ) {
361  return [ null, null ]; // bogus
362  }
363 
364  return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
365  }
366 
373  public function getZonePath( $zone ) {
374  list( $container, $base ) = $this->getZoneLocation( $zone );
375  if ( $container === null || $base === null ) {
376  return null;
377  }
378  $backendName = $this->backend->getName();
379  if ( $base != '' ) { // may not be set
380  $base = "/{$base}";
381  }
382 
383  return "mwstore://$backendName/{$container}{$base}";
384  }
385 
397  public function newFile( $title, $time = false ) {
399  if ( !$title ) {
400  return null;
401  }
402  if ( $time ) {
403  if ( $this->oldFileFactory ) {
404  return call_user_func( $this->oldFileFactory, $title, $this, $time );
405  } else {
406  return null;
407  }
408  } else {
409  return call_user_func( $this->fileFactory, $title, $this );
410  }
411  }
412 
430  public function findFile( $title, $options = [] ) {
432  if ( !$title ) {
433  return false;
434  }
435  if ( isset( $options['bypassCache'] ) ) {
436  $options['latest'] = $options['bypassCache']; // b/c
437  }
438  $time = $options['time'] ?? false;
439  $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
440  # First try the current version of the file to see if it precedes the timestamp
441  $img = $this->newFile( $title );
442  if ( !$img ) {
443  return false;
444  }
445  $img->load( $flags );
446  if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
447  return $img;
448  }
449  # Now try an old version of the file
450  if ( $time !== false ) {
451  $img = $this->newFile( $title, $time );
452  if ( $img ) {
453  $img->load( $flags );
454  if ( $img->exists() ) {
455  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
456  return $img; // always OK
457  } elseif ( !empty( $options['private'] ) &&
458  $img->userCan( File::DELETED_FILE,
459  $options['private'] instanceof User ? $options['private'] : null
460  )
461  ) {
462  return $img;
463  }
464  }
465  }
466  }
467 
468  # Now try redirects
469  if ( !empty( $options['ignoreRedirect'] ) ) {
470  return false;
471  }
472  $redir = $this->checkRedirect( $title );
473  if ( $redir && $title->getNamespace() == NS_FILE ) {
474  $img = $this->newFile( $redir );
475  if ( !$img ) {
476  return false;
477  }
478  $img->load( $flags );
479  if ( $img->exists() ) {
480  $img->redirectedFrom( $title->getDBkey() );
481 
482  return $img;
483  }
484  }
485 
486  return false;
487  }
488 
506  public function findFiles( array $items, $flags = 0 ) {
507  $result = [];
508  foreach ( $items as $item ) {
509  if ( is_array( $item ) ) {
510  $title = $item['title'];
511  $options = $item;
512  unset( $options['title'] );
513  } else {
514  $title = $item;
515  $options = [];
516  }
517  $file = $this->findFile( $title, $options );
518  if ( $file ) {
519  $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
520  if ( $flags & self::NAME_AND_TIME_ONLY ) {
521  $result[$searchName] = [
522  'title' => $file->getTitle()->getDBkey(),
523  'timestamp' => $file->getTimestamp()
524  ];
525  } else {
526  $result[$searchName] = $file;
527  }
528  }
529  }
530 
531  return $result;
532  }
533 
543  public function findFileFromKey( $sha1, $options = [] ) {
544  $time = $options['time'] ?? false;
545  # First try to find a matching current version of a file...
546  if ( !$this->fileFactoryKey ) {
547  return false; // find-by-sha1 not supported
548  }
549  $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
550  if ( $img && $img->exists() ) {
551  return $img;
552  }
553  # Now try to find a matching old version of a file...
554  if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
555  $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
556  if ( $img && $img->exists() ) {
557  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
558  return $img; // always OK
559  } elseif ( !empty( $options['private'] ) &&
560  $img->userCan( File::DELETED_FILE,
561  $options['private'] instanceof User ? $options['private'] : null
562  )
563  ) {
564  return $img;
565  }
566  }
567  }
568 
569  return false;
570  }
571 
580  public function findBySha1( $hash ) {
581  return [];
582  }
583 
591  public function findBySha1s( array $hashes ) {
592  $result = [];
593  foreach ( $hashes as $hash ) {
594  $files = $this->findBySha1( $hash );
595  if ( count( $files ) ) {
596  $result[$hash] = $files;
597  }
598  }
599 
600  return $result;
601  }
602 
611  public function findFilesByPrefix( $prefix, $limit ) {
612  return [];
613  }
614 
620  public function getThumbScriptUrl() {
621  return $this->thumbScriptUrl;
622  }
623 
629  public function getThumbProxyUrl() {
630  return $this->thumbProxyUrl;
631  }
632 
638  public function getThumbProxySecret() {
640  }
641 
647  public function canTransformVia404() {
648  return $this->transformVia404;
649  }
650 
657  public function getNameFromTitle( Title $title ) {
658  if (
659  $this->initialCapital !=
660  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
661  ) {
662  $name = $title->getUserCaseDBKey();
663  if ( $this->initialCapital ) {
664  $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
665  }
666  } else {
667  $name = $title->getDBkey();
668  }
669 
670  return $name;
671  }
672 
678  public function getRootDirectory() {
679  return $this->getZonePath( 'public' );
680  }
681 
689  public function getHashPath( $name ) {
690  return self::getHashPathForLevel( $name, $this->hashLevels );
691  }
692 
700  public function getTempHashPath( $suffix ) {
701  $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
702  $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
703  return self::getHashPathForLevel( $name, $this->hashLevels );
704  }
705 
711  protected static function getHashPathForLevel( $name, $levels ) {
712  if ( $levels == 0 ) {
713  return '';
714  } else {
715  $hash = md5( $name );
716  $path = '';
717  for ( $i = 1; $i <= $levels; $i++ ) {
718  $path .= substr( $hash, 0, $i ) . '/';
719  }
720 
721  return $path;
722  }
723  }
724 
730  public function getHashLevels() {
731  return $this->hashLevels;
732  }
733 
739  public function getName() {
740  return $this->name;
741  }
742 
750  public function makeUrl( $query = '', $entry = 'index' ) {
751  if ( isset( $this->scriptDirUrl ) ) {
752  return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
753  }
754 
755  return false;
756  }
757 
770  public function getDescriptionUrl( $name ) {
771  $encName = wfUrlencode( $name );
772  if ( !is_null( $this->descBaseUrl ) ) {
773  # "http://example.com/wiki/File:"
774  return $this->descBaseUrl . $encName;
775  }
776  if ( !is_null( $this->articleUrl ) ) {
777  # "http://example.com/wiki/$1"
778  # We use "Image:" as the canonical namespace for
779  # compatibility across all MediaWiki versions.
780  return str_replace( '$1',
781  "Image:$encName", $this->articleUrl );
782  }
783  if ( !is_null( $this->scriptDirUrl ) ) {
784  # "http://example.com/w"
785  # We use "Image:" as the canonical namespace for
786  # compatibility across all MediaWiki versions,
787  # and just sort of hope index.php is right. ;)
788  return $this->makeUrl( "title=Image:$encName" );
789  }
790 
791  return false;
792  }
793 
804  public function getDescriptionRenderUrl( $name, $lang = null ) {
805  $query = 'action=render';
806  if ( !is_null( $lang ) ) {
807  $query .= '&uselang=' . urlencode( $lang );
808  }
809  if ( isset( $this->scriptDirUrl ) ) {
810  return $this->makeUrl(
811  'title=' .
812  wfUrlencode( 'Image:' . $name ) .
813  "&$query" );
814  } else {
815  $descUrl = $this->getDescriptionUrl( $name );
816  if ( $descUrl ) {
817  return wfAppendQuery( $descUrl, $query );
818  } else {
819  return false;
820  }
821  }
822  }
823 
829  public function getDescriptionStylesheetUrl() {
830  if ( isset( $this->scriptDirUrl ) ) {
831  // Must match canonical query parameter order for optimum caching
832  // See Title::getCdnUrls
833  return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
834  }
835 
836  return false;
837  }
838 
856  public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
857  $this->assertWritableRepo(); // fail out if read-only
858 
859  $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
860  if ( $status->successCount == 0 ) {
861  $status->setOK( false );
862  }
863 
864  return $status;
865  }
866 
881  public function storeBatch( array $triplets, $flags = 0 ) {
882  $this->assertWritableRepo(); // fail out if read-only
883 
884  if ( $flags & self::DELETE_SOURCE ) {
885  throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
886  }
887 
888  $status = $this->newGood();
889  $backend = $this->backend; // convenience
890 
891  $operations = [];
892  // Validate each triplet and get the store operation...
893  foreach ( $triplets as $triplet ) {
894  list( $src, $dstZone, $dstRel ) = $triplet;
895  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
896  wfDebug( __METHOD__
897  . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
898  );
899  // Resolve source path
900  if ( $src instanceof FSFile ) {
901  $op = 'store';
902  } else {
903  $src = $this->resolveToStoragePathIfVirtual( $src );
904  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
905  }
906  // Resolve destination path
907  $root = $this->getZonePath( $dstZone );
908  if ( !$root ) {
909  throw new MWException( "Invalid zone: $dstZone" );
910  }
911  if ( !$this->validateFilename( $dstRel ) ) {
912  throw new MWException( 'Validation error in $dstRel' );
913  }
914  $dstPath = "$root/$dstRel";
915  $dstDir = dirname( $dstPath );
916  // Create destination directories for this triplet
917  if ( !$this->initDirectory( $dstDir )->isOK() ) {
918  return $this->newFatal( 'directorycreateerror', $dstDir );
919  }
920 
921  // Copy the source file to the destination
922  $operations[] = [
923  'op' => $op,
924  'src' => $src, // storage path (copy) or local file path (store)
925  'dst' => $dstPath,
926  'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
927  'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
928  ];
929  }
930 
931  // Execute the store operation for each triplet
932  $opts = [ 'force' => true ];
933  if ( $flags & self::SKIP_LOCKING ) {
934  $opts['nonLocking'] = true;
935  }
936  $status->merge( $backend->doOperations( $operations, $opts ) );
937 
938  return $status;
939  }
940 
951  public function cleanupBatch( array $files, $flags = 0 ) {
952  $this->assertWritableRepo(); // fail out if read-only
953 
954  $status = $this->newGood();
955 
956  $operations = [];
957  foreach ( $files as $path ) {
958  if ( is_array( $path ) ) {
959  // This is a pair, extract it
960  list( $zone, $rel ) = $path;
961  $path = $this->getZonePath( $zone ) . "/$rel";
962  } else {
963  // Resolve source to a storage path if virtual
964  $path = $this->resolveToStoragePathIfVirtual( $path );
965  }
966  $operations[] = [ 'op' => 'delete', 'src' => $path ];
967  }
968  // Actually delete files from storage...
969  $opts = [ 'force' => true ];
970  if ( $flags & self::SKIP_LOCKING ) {
971  $opts['nonLocking'] = true;
972  }
973  $status->merge( $this->backend->doOperations( $operations, $opts ) );
974 
975  return $status;
976  }
977 
995  final public function quickImport( $src, $dst, $options = null ) {
996  return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
997  }
998 
1013  public function quickImportBatch( array $triples ) {
1014  $status = $this->newGood();
1015  $operations = [];
1016  foreach ( $triples as $triple ) {
1017  list( $src, $dst ) = $triple;
1018  if ( $src instanceof FSFile ) {
1019  $op = 'store';
1020  } else {
1021  $src = $this->resolveToStoragePathIfVirtual( $src );
1022  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1023  }
1024  $dst = $this->resolveToStoragePathIfVirtual( $dst );
1025 
1026  if ( !isset( $triple[2] ) ) {
1027  $headers = [];
1028  } elseif ( is_string( $triple[2] ) ) {
1029  // back-compat
1030  $headers = [ 'Content-Disposition' => $triple[2] ];
1031  } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1032  $headers = $triple[2]['headers'];
1033  } else {
1034  $headers = [];
1035  }
1036 
1037  $operations[] = [
1038  'op' => $op,
1039  'src' => $src, // storage path (copy) or local path/FSFile (store)
1040  'dst' => $dst,
1041  'headers' => $headers
1042  ];
1043  $status->merge( $this->initDirectory( dirname( $dst ) ) );
1044  }
1045  $status->merge( $this->backend->doQuickOperations( $operations ) );
1046 
1047  return $status;
1048  }
1049 
1058  final public function quickPurge( $path ) {
1059  return $this->quickPurgeBatch( [ $path ] );
1060  }
1061 
1069  public function quickCleanDir( $dir ) {
1070  $status = $this->newGood();
1071  $status->merge( $this->backend->clean(
1072  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1073 
1074  return $status;
1075  }
1076 
1085  public function quickPurgeBatch( array $paths ) {
1086  $status = $this->newGood();
1087  $operations = [];
1088  foreach ( $paths as $path ) {
1089  $operations[] = [
1090  'op' => 'delete',
1091  'src' => $this->resolveToStoragePathIfVirtual( $path ),
1092  'ignoreMissingSource' => true
1093  ];
1094  }
1095  $status->merge( $this->backend->doQuickOperations( $operations ) );
1096 
1097  return $status;
1098  }
1099 
1110  public function storeTemp( $originalName, $srcPath ) {
1111  $this->assertWritableRepo(); // fail out if read-only
1112 
1113  $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1114  $hashPath = $this->getHashPath( $originalName );
1115  $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1116  $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1117 
1118  $result = $this->quickImport( $srcPath, $virtualUrl );
1119  $result->value = $virtualUrl;
1120 
1121  return $result;
1122  }
1123 
1130  public function freeTemp( $virtualUrl ) {
1131  $this->assertWritableRepo(); // fail out if read-only
1132 
1133  $temp = $this->getVirtualUrl( 'temp' );
1134  if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1135  wfDebug( __METHOD__ . ": Invalid temp virtual URL\n" );
1136 
1137  return false;
1138  }
1139 
1140  return $this->quickPurge( $virtualUrl )->isOK();
1141  }
1142 
1152  public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1153  $this->assertWritableRepo(); // fail out if read-only
1154 
1155  $status = $this->newGood();
1156 
1157  $sources = [];
1158  foreach ( $srcPaths as $srcPath ) {
1159  // Resolve source to a storage path if virtual
1160  $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1161  $sources[] = $source; // chunk to merge
1162  }
1163 
1164  // Concatenate the chunks into one FS file
1165  $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1166  $status->merge( $this->backend->concatenate( $params ) );
1167  if ( !$status->isOK() ) {
1168  return $status;
1169  }
1170 
1171  // Delete the sources if required
1172  if ( $flags & self::DELETE_SOURCE ) {
1173  $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1174  }
1175 
1176  // Make sure status is OK, despite any quickPurgeBatch() fatals
1177  $status->setResult( true );
1178 
1179  return $status;
1180  }
1181 
1205  public function publish(
1206  $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1207  ) {
1208  $this->assertWritableRepo(); // fail out if read-only
1209 
1210  $status = $this->publishBatch(
1211  [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1212  if ( $status->successCount == 0 ) {
1213  $status->setOK( false );
1214  }
1215  $status->value = $status->value[0] ?? false;
1216 
1217  return $status;
1218  }
1219 
1232  public function publishBatch( array $ntuples, $flags = 0 ) {
1233  $this->assertWritableRepo(); // fail out if read-only
1234 
1235  $backend = $this->backend; // convenience
1236  // Try creating directories
1237  $status = $this->initZones( 'public' );
1238  if ( !$status->isOK() ) {
1239  return $status;
1240  }
1241 
1242  $status = $this->newGood( [] );
1243 
1244  $operations = [];
1245  $sourceFSFilesToDelete = []; // cleanup for disk source files
1246  // Validate each triplet and get the store operation...
1247  foreach ( $ntuples as $ntuple ) {
1248  list( $src, $dstRel, $archiveRel ) = $ntuple;
1249  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1250 
1251  $options = $ntuple[3] ?? [];
1252  // Resolve source to a storage path if virtual
1253  $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1254  if ( !$this->validateFilename( $dstRel ) ) {
1255  throw new MWException( 'Validation error in $dstRel' );
1256  }
1257  if ( !$this->validateFilename( $archiveRel ) ) {
1258  throw new MWException( 'Validation error in $archiveRel' );
1259  }
1260 
1261  $publicRoot = $this->getZonePath( 'public' );
1262  $dstPath = "$publicRoot/$dstRel";
1263  $archivePath = "$publicRoot/$archiveRel";
1264 
1265  $dstDir = dirname( $dstPath );
1266  $archiveDir = dirname( $archivePath );
1267  // Abort immediately on directory creation errors since they're likely to be repetitive
1268  if ( !$this->initDirectory( $dstDir )->isOK() ) {
1269  return $this->newFatal( 'directorycreateerror', $dstDir );
1270  }
1271  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1272  return $this->newFatal( 'directorycreateerror', $archiveDir );
1273  }
1274 
1275  // Set any desired headers to be use in GET/HEAD responses
1276  $headers = $options['headers'] ?? [];
1277 
1278  // Archive destination file if it exists.
1279  // This will check if the archive file also exists and fail if does.
1280  // This is a sanity check to avoid data loss. On Windows and Linux,
1281  // copy() will overwrite, so the existence check is vulnerable to
1282  // race conditions unless a functioning LockManager is used.
1283  // LocalFile also uses SELECT FOR UPDATE for synchronization.
1284  $operations[] = [
1285  'op' => 'copy',
1286  'src' => $dstPath,
1287  'dst' => $archivePath,
1288  'ignoreMissingSource' => true
1289  ];
1290 
1291  // Copy (or move) the source file to the destination
1292  if ( FileBackend::isStoragePath( $srcPath ) ) {
1293  $operations[] = [
1294  'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1295  'src' => $srcPath,
1296  'dst' => $dstPath,
1297  'overwrite' => true, // replace current
1298  'headers' => $headers
1299  ];
1300  } else {
1301  $operations[] = [
1302  'op' => 'store',
1303  'src' => $src, // storage path (copy) or local path/FSFile (store)
1304  'dst' => $dstPath,
1305  'overwrite' => true, // replace current
1306  'headers' => $headers
1307  ];
1308  if ( $flags & self::DELETE_SOURCE ) {
1309  $sourceFSFilesToDelete[] = $srcPath;
1310  }
1311  }
1312  }
1313 
1314  // Execute the operations for each triplet
1315  $status->merge( $backend->doOperations( $operations ) );
1316  // Find out which files were archived...
1317  foreach ( $ntuples as $i => $ntuple ) {
1318  list( , , $archiveRel ) = $ntuple;
1319  $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1320  if ( $this->fileExists( $archivePath ) ) {
1321  $status->value[$i] = 'archived';
1322  } else {
1323  $status->value[$i] = 'new';
1324  }
1325  }
1326  // Cleanup for disk source files...
1327  foreach ( $sourceFSFilesToDelete as $file ) {
1328  Wikimedia\suppressWarnings();
1329  unlink( $file ); // FS cleanup
1330  Wikimedia\restoreWarnings();
1331  }
1332 
1333  return $status;
1334  }
1335 
1343  protected function initDirectory( $dir ) {
1344  $path = $this->resolveToStoragePathIfVirtual( $dir );
1345  list( , $container, ) = FileBackend::splitStoragePath( $path );
1346 
1347  $params = [ 'dir' => $path ];
1348  if ( $this->isPrivate
1349  || $container === $this->zones['deleted']['container']
1350  || $container === $this->zones['temp']['container']
1351  ) {
1352  # Take all available measures to prevent web accessibility of new deleted
1353  # directories, in case the user has not configured offline storage
1354  $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1355  }
1356 
1357  $status = $this->newGood();
1358  $status->merge( $this->backend->prepare( $params ) );
1359 
1360  return $status;
1361  }
1362 
1369  public function cleanDir( $dir ) {
1370  $this->assertWritableRepo(); // fail out if read-only
1371 
1372  $status = $this->newGood();
1373  $status->merge( $this->backend->clean(
1374  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1375 
1376  return $status;
1377  }
1378 
1385  public function fileExists( $file ) {
1386  $result = $this->fileExistsBatch( [ $file ] );
1387 
1388  return $result[0];
1389  }
1390 
1397  public function fileExistsBatch( array $files ) {
1398  $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1399  $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1400 
1401  $result = [];
1402  foreach ( $files as $key => $file ) {
1404  $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1405  }
1406 
1407  return $result;
1408  }
1409 
1420  public function delete( $srcRel, $archiveRel ) {
1421  $this->assertWritableRepo(); // fail out if read-only
1422 
1423  return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1424  }
1425 
1443  public function deleteBatch( array $sourceDestPairs ) {
1444  $this->assertWritableRepo(); // fail out if read-only
1445 
1446  // Try creating directories
1447  $status = $this->initZones( [ 'public', 'deleted' ] );
1448  if ( !$status->isOK() ) {
1449  return $status;
1450  }
1451 
1452  $status = $this->newGood();
1453 
1454  $backend = $this->backend; // convenience
1455  $operations = [];
1456  // Validate filenames and create archive directories
1457  foreach ( $sourceDestPairs as $pair ) {
1458  list( $srcRel, $archiveRel ) = $pair;
1459  if ( !$this->validateFilename( $srcRel ) ) {
1460  throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1461  } elseif ( !$this->validateFilename( $archiveRel ) ) {
1462  throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1463  }
1464 
1465  $publicRoot = $this->getZonePath( 'public' );
1466  $srcPath = "{$publicRoot}/$srcRel";
1467 
1468  $deletedRoot = $this->getZonePath( 'deleted' );
1469  $archivePath = "{$deletedRoot}/{$archiveRel}";
1470  $archiveDir = dirname( $archivePath ); // does not touch FS
1471 
1472  // Create destination directories
1473  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1474  return $this->newFatal( 'directorycreateerror', $archiveDir );
1475  }
1476 
1477  $operations[] = [
1478  'op' => 'move',
1479  'src' => $srcPath,
1480  'dst' => $archivePath,
1481  // We may have 2+ identical files being deleted,
1482  // all of which will map to the same destination file
1483  'overwriteSame' => true // also see T33792
1484  ];
1485  }
1486 
1487  // Move the files by execute the operations for each pair.
1488  // We're now committed to returning an OK result, which will
1489  // lead to the files being moved in the DB also.
1490  $opts = [ 'force' => true ];
1491  $status->merge( $backend->doOperations( $operations, $opts ) );
1492 
1493  return $status;
1494  }
1495 
1502  public function cleanupDeletedBatch( array $storageKeys ) {
1503  $this->assertWritableRepo();
1504  }
1505 
1514  public function getDeletedHashPath( $key ) {
1515  if ( strlen( $key ) < 31 ) {
1516  throw new MWException( "Invalid storage key '$key'." );
1517  }
1518  $path = '';
1519  for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1520  $path .= $key[$i] . '/';
1521  }
1522 
1523  return $path;
1524  }
1525 
1534  protected function resolveToStoragePathIfVirtual( $path ) {
1535  if ( self::isVirtualUrl( $path ) ) {
1536  return $this->resolveVirtualUrl( $path );
1537  }
1538 
1539  return $path;
1540  }
1541 
1549  public function getLocalCopy( $virtualUrl ) {
1550  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1551 
1552  return $this->backend->getLocalCopy( [ 'src' => $path ] );
1553  }
1554 
1563  public function getLocalReference( $virtualUrl ) {
1564  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1565 
1566  return $this->backend->getLocalReference( [ 'src' => $path ] );
1567  }
1568 
1576  public function getFileProps( $virtualUrl ) {
1577  $fsFile = $this->getLocalReference( $virtualUrl );
1578  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1579  if ( $fsFile ) {
1580  $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1581  } else {
1582  $props = $mwProps->newPlaceholderProps();
1583  }
1584 
1585  return $props;
1586  }
1587 
1594  public function getFileTimestamp( $virtualUrl ) {
1595  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1596 
1597  return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1598  }
1599 
1606  public function getFileSize( $virtualUrl ) {
1607  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1608 
1609  return $this->backend->getFileSize( [ 'src' => $path ] );
1610  }
1611 
1618  public function getFileSha1( $virtualUrl ) {
1619  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1620 
1621  return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1622  }
1623 
1633  public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1634  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1635  $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1636 
1637  // T172851: HHVM does not flush the output properly, causing OOM
1638  ob_start( null, 1048576 );
1639  ob_implicit_flush( true );
1640 
1641  $status = $this->newGood();
1642  $status->merge( $this->backend->streamFile( $params ) );
1643 
1644  // T186565: Close the buffer, unless it has already been closed
1645  // in HTTPFileStreamer::resetOutputBuffers().
1646  if ( ob_get_status() ) {
1647  ob_end_flush();
1648  }
1649 
1650  return $status;
1651  }
1652 
1661  public function enumFiles( $callback ) {
1662  $this->enumFilesInStorage( $callback );
1663  }
1664 
1672  protected function enumFilesInStorage( $callback ) {
1673  $publicRoot = $this->getZonePath( 'public' );
1674  $numDirs = 1 << ( $this->hashLevels * 4 );
1675  // Use a priori assumptions about directory structure
1676  // to reduce the tree height of the scanning process.
1677  for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1678  $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1679  $path = $publicRoot;
1680  for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1681  $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1682  }
1683  $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1684  foreach ( $iterator as $name ) {
1685  // Each item returned is a public file
1686  call_user_func( $callback, "{$path}/{$name}" );
1687  }
1688  }
1689  }
1690 
1697  public function validateFilename( $filename ) {
1698  if ( strval( $filename ) == '' ) {
1699  return false;
1700  }
1701 
1702  return FileBackend::isPathTraversalFree( $filename );
1703  }
1704 
1711  switch ( $this->pathDisclosureProtection ) {
1712  case 'none':
1713  case 'simple': // b/c
1714  $callback = [ $this, 'passThrough' ];
1715  break;
1716  default: // 'paranoid'
1717  $callback = [ $this, 'paranoidClean' ];
1718  }
1719  return $callback;
1720  }
1721 
1728  function paranoidClean( $param ) {
1729  return '[hidden]';
1730  }
1731 
1738  function passThrough( $param ) {
1739  return $param;
1740  }
1741 
1748  public function newFatal( $message /*, parameters...*/ ) {
1749  $status = Status::newFatal( ...func_get_args() );
1750  $status->cleanCallback = $this->getErrorCleanupFunction();
1751 
1752  return $status;
1753  }
1754 
1761  public function newGood( $value = null ) {
1762  $status = Status::newGood( $value );
1763  $status->cleanCallback = $this->getErrorCleanupFunction();
1764 
1765  return $status;
1766  }
1767 
1776  public function checkRedirect( Title $title ) {
1777  return false;
1778  }
1779 
1787  public function invalidateImageRedirect( Title $title ) {
1788  }
1789 
1795  public function getDisplayName() {
1796  global $wgSitename;
1797 
1798  if ( $this->isLocal() ) {
1799  return $wgSitename;
1800  }
1801 
1802  // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1803  return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1804  }
1805 
1813  public function nameForThumb( $name ) {
1814  if ( strlen( $name ) > $this->abbrvThreshold ) {
1816  $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1817  }
1818 
1819  return $name;
1820  }
1821 
1827  public function isLocal() {
1828  return $this->getName() == 'local';
1829  }
1830 
1840  public function getSharedCacheKey( ...$args ) {
1841  return false;
1842  }
1843 
1852  public function getLocalCacheKey( ...$args ) {
1853  array_unshift( $args, 'filerepo', $this->getName() );
1854 
1855  return $this->wanCache->makeKey( ...$args );
1856  }
1857 
1866  public function getTempRepo() {
1867  return new TempFileRepo( [
1868  'name' => "{$this->name}-temp",
1869  'backend' => $this->backend,
1870  'zones' => [
1871  'public' => [
1872  // Same place storeTemp() uses in the base repo, though
1873  // the path hashing is mismatched, which is annoying.
1874  'container' => $this->zones['temp']['container'],
1875  'directory' => $this->zones['temp']['directory']
1876  ],
1877  'thumb' => [
1878  'container' => $this->zones['temp']['container'],
1879  'directory' => $this->zones['temp']['directory'] == ''
1880  ? 'thumb'
1881  : $this->zones['temp']['directory'] . '/thumb'
1882  ],
1883  'transcoded' => [
1884  'container' => $this->zones['temp']['container'],
1885  'directory' => $this->zones['temp']['directory'] == ''
1886  ? 'transcoded'
1887  : $this->zones['temp']['directory'] . '/transcoded'
1888  ]
1889  ],
1890  'hashLevels' => $this->hashLevels, // performance
1891  'isPrivate' => true // all in temp zone
1892  ] );
1893  }
1894 
1901  public function getUploadStash( User $user = null ) {
1902  return new UploadStash( $this, $user );
1903  }
1904 
1912  protected function assertWritableRepo() {
1913  }
1914 
1921  public function getInfo() {
1922  $ret = [
1923  'name' => $this->getName(),
1924  'displayname' => $this->getDisplayName(),
1925  'rootUrl' => $this->getZoneUrl( 'public' ),
1926  'local' => $this->isLocal(),
1927  ];
1928 
1929  $optionalSettings = [
1930  'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1931  'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1932  ];
1933  foreach ( $optionalSettings as $k ) {
1934  if ( isset( $this->$k ) ) {
1935  $ret[$k] = $this->$k;
1936  }
1937  }
1938 
1939  return $ret;
1940  }
1941 
1946  public function hasSha1Storage() {
1947  return $this->hasSha1Storage;
1948  }
1949 
1954  public function supportsSha1URLs() {
1955  return $this->supportsSha1URLs;
1956  }
1957 }
string $favicon
The URL of the repo&#39;s favicon, if any.
Definition: FileRepo.php:121
assertWritableRepo()
Throw an exception if this repo is read-only by design.
Definition: FileRepo.php:1912
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition: FileRepo.php:50
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition: FileRepo.php:83
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
Definition: FileRepo.php:118
array $zones
Map of zones to config.
Definition: FileRepo.php:65
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
Definition: FileRepo.php:647
getTempRepo()
Get a temporary private FileRepo associated with this repo.
Definition: FileRepo.php:1866
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:276
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
doOperations(array $ops, array $opts=[])
This is the main entry point into the backend for write operations.
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1606
getUserCaseDBKey()
Get the DB key with the initial letter case as specified by the user.
Definition: Title.php:1026
string $pathDisclosureProtection
May be &#39;paranoid&#39; to remove all parameters from error messages, &#39;none&#39; to leave the paths in unchange...
Definition: FileRepo.php:100
paranoidClean( $param)
Path disclosure protection function.
Definition: FileRepo.php:1728
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition: FileRepo.php:770
$wgSitename
Name of the site.
cleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1369
getLocalCacheKey(... $args)
Get a key for this repo in the local cache domain.
Definition: FileRepo.php:1852
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition: FileRepo.php:678
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
Definition: FileRepo.php:1343
getUploadStash(User $user=null)
Get an UploadStash associated with this repo.
Definition: FileRepo.php:1901
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition: FileRepo.php:750
if(!isset( $args[0])) $lang
string false $url
Public zone URL.
Definition: FileRepo.php:103
nameForThumb( $name)
Get the portion of the file that contains the origin file name.
Definition: FileRepo.php:1813
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:333
const DELETE_SOURCE
Definition: FileRepo.php:40
WANObjectCache $wanCache
Definition: FileRepo.php:143
checkRedirect(Title $title)
Checks if there is a redirect named as $title.
Definition: FileRepo.php:1776
quickCleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1069
$source
getHashLevels()
Get the number of hash directory levels.
Definition: FileRepo.php:730
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition: FileRepo.php:292
A helper class for throttling authentication attempts.
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:995
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
Definition: FileRepo.php:1130
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
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:1205
callable false $oldFileFactory
Override these in the base class.
Definition: FileRepo.php:129
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table...
Definition: FileRepo.php:1502
const DELETED_FILE
Definition: File.php:63
getBackend()
Get the file backend instance.
Definition: FileRepo.php:225
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1385
if( $line===false) $args
Definition: cdb.php:64
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:39
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition: FileRepo.php:359
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
Definition: FileRepo.php:1661
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
const OVERWRITE
Definition: FileRepo.php:41
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
Definition: FileRepo.php:1534
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
Definition: FileRepo.php:1672
isLocal()
Returns true if this the local file repository.
Definition: FileRepo.php:1827
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:235
initZones( $doZones=[])
Check if a single zone or list of zones is defined for usage.
Definition: FileRepo.php:246
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition: FileRepo.php:138
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition: FileRepo.php:629
getInfo()
Return information about the repository.
Definition: FileRepo.php:1921
string $thumbScriptUrl
URL of thumb.php.
Definition: FileRepo.php:68
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition: FileRepo.php:829
getDBkey()
Get the main part with underscores.
Definition: Title.php:1016
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
Definition: FileRepo.php:1085
callable $fileFactory
Override these in the base class.
Definition: FileRepo.php:127
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
Definition: FileRepo.php:1710
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1618
invalidateImageRedirect(Title $title)
Invalidates image redirect cache related to that image Doesn&#39;t do anything for repositories that don&#39;...
Definition: FileRepo.php:1787
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
Definition: FileRepo.php:1152
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
Definition: FileRepo.php:1443
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:700
int $hashLevels
The number of directory levels for hash-based division of files.
Definition: FileRepo.php:109
getThumbScriptUrl()
Get the URL of thumb.php.
Definition: FileRepo.php:620
string $name
Definition: FileRepo.php:149
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition: FileRepo.php:93
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:264
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition: FileRepo.php:86
string $thumbUrl
The base thumbnail URL.
Definition: FileRepo.php:106
const ATTR_UNICODE_PATHS
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition: FileRepo.php:611
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition: FileRepo.php:397
const SKIP_LOCKING
Definition: FileRepo.php:43
findFiles(array $items, $flags=0)
Find many files at once.
Definition: FileRepo.php:506
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1549
static getHashPathForLevel( $name, $levels)
Definition: FileRepo.php:711
const NS_FILE
Definition: Defines.php:66
bool $hasSha1Storage
Definition: FileRepo.php:56
int $descriptionCacheExpiry
Definition: FileRepo.php:53
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition: FileRepo.php:373
string $descBaseUrl
URL of image description pages, e.g.
Definition: FileRepo.php:78
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
Definition: FileRepo.php:1633
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1594
getNameFromTitle(Title $title)
Get the name of a file from its title object.
Definition: FileRepo.php:657
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
Definition: FileRepo.php:1110
const NAME_AND_TIME_ONLY
Definition: FileRepo.php:45
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition: FileRepo.php:140
backendSupportsUnicodePaths()
Definition: FileRepo.php:321
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:53
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
Definition: FileRepo.php:951
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition: FileRepo.php:73
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:430
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:591
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
const OVERWRITE_SAME
Definition: FileRepo.php:42
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1576
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition: FileRepo.php:856
findBySha1( $hash)
Get an array or iterator of file objects for files that have a given SHA-1 content hash...
Definition: FileRepo.php:580
FileRepo for temporary files created via FileRepo::getTempRepo()
Definition: TempFileRepo.php:5
Base class for all file backend classes (including multi-write backends).
Definition: FileBackend.php:94
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:543
getDisplayName()
Get the human-readable name of the repo.
Definition: FileRepo.php:1795
if(!is_readable( $file)) $ext
Definition: router.php:48
Base class for file repositories.
Definition: FileRepo.php:39
bool $supportsSha1URLs
Definition: FileRepo.php:59
getSharedCacheKey(... $args)
Get a key on the primary cache for this repository.
Definition: FileRepo.php:1840
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:689
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:881
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
Definition: FileRepo.php:1563
FileBackend $backend
Definition: FileRepo.php:62
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1397
callable false $fileFactoryKey
Override these in the base class.
Definition: FileRepo.php:131
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
Definition: FileRepo.php:1013
quickPurge( $path)
Purge a file from the repo.
Definition: FileRepo.php:1058
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1514
passThrough( $param)
Path disclosure protection function.
Definition: FileRepo.php:1738
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Definition: FileRepo.php:1697
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
Definition: FileRepo.php:1954
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition: FileRepo.php:112
__construct(array $info=null)
Definition: FileRepo.php:156
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1946
bool $isPrivate
Whether all zones should be private (e.g.
Definition: FileRepo.php:124
return true
Definition: router.php:92
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:194
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition: FileRepo.php:638
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition: FileRepo.php:804
callable false $oldFileFactoryKey
Override these in the base class.
Definition: FileRepo.php:133
getName()
Get the name of this repository, as specified by $info[&#39;name]&#39; to the constructor.
Definition: FileRepo.php:739
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1761
newFatal( $message)
Create a new fatal error.
Definition: FileRepo.php:1748
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
Definition: FileRepo.php:1232