MediaWiki  master
FileRepo.php
Go to the documentation of this file.
1 <?php
11 
41 class FileRepo {
42  public const DELETE_SOURCE = 1;
43  public const OVERWRITE = 2;
44  public const OVERWRITE_SAME = 4;
45  public const SKIP_LOCKING = 8;
46 
47  public const NAME_AND_TIME_ONLY = 1;
48 
53 
56 
58  protected $hasSha1Storage = false;
59 
61  protected $supportsSha1URLs = false;
62 
64  protected $backend;
65 
67  protected $zones = [];
68 
70  protected $thumbScriptUrl;
71 
75  protected $transformVia404;
76 
80  protected $descBaseUrl;
81 
85  protected $scriptDirUrl;
86 
88  protected $articleUrl;
89 
95  protected $initialCapital;
96 
102  protected $pathDisclosureProtection = 'simple';
103 
105  protected $url;
106 
108  protected $thumbUrl;
109 
111  protected $hashLevels;
112 
115 
120  protected $abbrvThreshold;
121 
123  protected $favicon;
124 
126  protected $isPrivate;
127 
129  protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
131  protected $oldFileFactory = false;
133  protected $fileFactoryKey = false;
135  protected $oldFileFactoryKey = false;
136 
140  protected $thumbProxyUrl;
142  protected $thumbProxySecret;
143 
145  protected $wanCache;
146 
151  public $name;
152 
159  public function __construct( array $info = null ) {
160  // Verify required settings presence
161  if (
162  $info === null
163  || !array_key_exists( 'name', $info )
164  || !array_key_exists( 'backend', $info )
165  ) {
166  throw new MWException( __CLASS__ .
167  " requires an array of options having both 'name' and 'backend' keys.\n" );
168  }
169 
170  // Required settings
171  $this->name = $info['name'];
172  if ( $info['backend'] instanceof FileBackend ) {
173  $this->backend = $info['backend']; // useful for testing
174  } else {
175  $this->backend =
176  MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
177  }
178 
179  // Optional settings that can have no value
180  $optionalSettings = [
181  'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
182  'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
183  'favicon', 'thumbProxyUrl', 'thumbProxySecret',
184  ];
185  foreach ( $optionalSettings as $var ) {
186  if ( isset( $info[$var] ) ) {
187  $this->$var = $info[$var];
188  }
189  }
190 
191  // Optional settings that have a default
192  $localCapitalLinks =
193  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
194  $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
195  if ( $localCapitalLinks && !$this->initialCapital ) {
196  // If the local wiki's file namespace requires an initial capital, but a foreign file
197  // repo doesn't, complications will result. Linker code will want to auto-capitalize the
198  // first letter of links to files, but those links might actually point to files on
199  // foreign wikis with initial-lowercase names. This combination is not likely to be
200  // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
201  // to include a foreign file repo with initialCapital false, set your local file
202  // namespace to not be capitalized either.
203  throw new InvalidArgumentException(
204  'File repos with initial capital false are not allowed on wikis where the File ' .
205  'namespace has initial capital true' );
206  }
207 
208  $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
209  if ( isset( $info['thumbUrl'] ) ) {
210  $this->thumbUrl = $info['thumbUrl'];
211  } else {
212  $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
213  }
214  $this->hashLevels = $info['hashLevels'] ?? 2;
215  $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
216  $this->transformVia404 = !empty( $info['transformVia404'] );
217  $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
218  $this->isPrivate = !empty( $info['isPrivate'] );
219  // Give defaults for the basic zones...
220  $this->zones = $info['zones'] ?? [];
221  foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
222  if ( !isset( $this->zones[$zone]['container'] ) ) {
223  $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
224  }
225  if ( !isset( $this->zones[$zone]['directory'] ) ) {
226  $this->zones[$zone]['directory'] = '';
227  }
228  if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
229  $this->zones[$zone]['urlsByExt'] = [];
230  }
231  }
232 
233  $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
234 
235  $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
236  }
237 
243  public function getBackend() {
244  return $this->backend;
245  }
246 
253  public function getReadOnlyReason() {
254  return $this->backend->getReadOnlyReason();
255  }
256 
264  protected function initZones( $doZones = [] ) {
265  $status = $this->newGood();
266  foreach ( (array)$doZones as $zone ) {
267  $root = $this->getZonePath( $zone );
268  if ( $root === null ) {
269  throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
270  }
271  }
272 
273  return $status;
274  }
275 
282  public static function isVirtualUrl( $url ) {
283  return substr( $url, 0, 9 ) == 'mwrepo://';
284  }
285 
294  public function getVirtualUrl( $suffix = false ) {
295  $path = 'mwrepo://' . $this->name;
296  if ( $suffix !== false ) {
297  $path .= '/' . rawurlencode( $suffix );
298  }
299 
300  return $path;
301  }
302 
310  public function getZoneUrl( $zone, $ext = null ) {
311  if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
312  // standard public zones
313  if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
314  // custom URL for extension/zone
315  return $this->zones[$zone]['urlsByExt'][$ext];
316  } elseif ( isset( $this->zones[$zone]['url'] ) ) {
317  // custom URL for zone
318  return $this->zones[$zone]['url'];
319  }
320  }
321  switch ( $zone ) {
322  case 'public':
323  return $this->url;
324  case 'temp':
325  case 'deleted':
326  return false; // no public URL
327  case 'thumb':
328  return $this->thumbUrl;
329  case 'transcoded':
330  return "{$this->url}/transcoded";
331  default:
332  return false;
333  }
334  }
335 
339  public function backendSupportsUnicodePaths() {
340  return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
341  }
342 
351  public function resolveVirtualUrl( $url ) {
352  if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
353  throw new MWException( __METHOD__ . ': unknown protocol' );
354  }
355  $bits = explode( '/', substr( $url, 9 ), 3 );
356  if ( count( $bits ) != 3 ) {
357  throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
358  }
359  list( $repo, $zone, $rel ) = $bits;
360  if ( $repo !== $this->name ) {
361  throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
362  }
363  $base = $this->getZonePath( $zone );
364  if ( !$base ) {
365  throw new MWException( __METHOD__ . ": invalid zone: $zone" );
366  }
367 
368  return $base . '/' . rawurldecode( $rel );
369  }
370 
377  protected function getZoneLocation( $zone ) {
378  if ( !isset( $this->zones[$zone] ) ) {
379  return [ null, null ]; // bogus
380  }
381 
382  return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
383  }
384 
391  public function getZonePath( $zone ) {
392  list( $container, $base ) = $this->getZoneLocation( $zone );
393  if ( $container === null || $base === null ) {
394  return null;
395  }
396  $backendName = $this->backend->getName();
397  if ( $base != '' ) { // may not be set
398  $base = "/{$base}";
399  }
400 
401  return "mwstore://$backendName/{$container}{$base}";
402  }
403 
415  public function newFile( $title, $time = false ) {
417  if ( !$title ) {
418  return null;
419  }
420  if ( $time ) {
421  if ( $this->oldFileFactory ) {
422  return call_user_func( $this->oldFileFactory, $title, $this, $time );
423  } else {
424  return null;
425  }
426  } else {
427  return call_user_func( $this->fileFactory, $title, $this );
428  }
429  }
430 
448  public function findFile( $title, $options = [] ) {
450  if ( !$title ) {
451  return false;
452  }
453  if ( isset( $options['bypassCache'] ) ) {
454  $options['latest'] = $options['bypassCache']; // b/c
455  }
456  $time = $options['time'] ?? false;
457  $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
458  # First try the current version of the file to see if it precedes the timestamp
459  $img = $this->newFile( $title );
460  if ( !$img ) {
461  return false;
462  }
463  $img->load( $flags );
464  if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
465  return $img;
466  }
467  # Now try an old version of the file
468  if ( $time !== false ) {
469  $img = $this->newFile( $title, $time );
470  if ( $img ) {
471  $img->load( $flags );
472  if ( $img->exists() ) {
473  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
474  return $img; // always OK
475  } elseif ( !empty( $options['private'] ) &&
476  $img->userCan( File::DELETED_FILE,
477  $options['private'] instanceof User ? $options['private'] : null
478  )
479  ) {
480  return $img;
481  }
482  }
483  }
484  }
485 
486  # Now try redirects
487  if ( !empty( $options['ignoreRedirect'] ) ) {
488  return false;
489  }
490  $redir = $this->checkRedirect( $title );
491  if ( $redir && $title->getNamespace() == NS_FILE ) {
492  $img = $this->newFile( $redir );
493  if ( !$img ) {
494  return false;
495  }
496  $img->load( $flags );
497  if ( $img->exists() ) {
498  $img->redirectedFrom( $title->getDBkey() );
499 
500  return $img;
501  }
502  }
503 
504  return false;
505  }
506 
524  public function findFiles( array $items, $flags = 0 ) {
525  $result = [];
526  foreach ( $items as $item ) {
527  if ( is_array( $item ) ) {
528  $title = $item['title'];
529  $options = $item;
530  unset( $options['title'] );
531  } else {
532  $title = $item;
533  $options = [];
534  }
535  $file = $this->findFile( $title, $options );
536  if ( $file ) {
537  $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
538  if ( $flags & self::NAME_AND_TIME_ONLY ) {
539  $result[$searchName] = [
540  'title' => $file->getTitle()->getDBkey(),
541  'timestamp' => $file->getTimestamp()
542  ];
543  } else {
544  $result[$searchName] = $file;
545  }
546  }
547  }
548 
549  return $result;
550  }
551 
561  public function findFileFromKey( $sha1, $options = [] ) {
562  $time = $options['time'] ?? false;
563  # First try to find a matching current version of a file...
564  if ( !$this->fileFactoryKey ) {
565  return false; // find-by-sha1 not supported
566  }
567  $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
568  if ( $img && $img->exists() ) {
569  return $img;
570  }
571  # Now try to find a matching old version of a file...
572  if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
573  $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
574  if ( $img && $img->exists() ) {
575  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
576  return $img; // always OK
577  } elseif ( !empty( $options['private'] ) &&
578  $img->userCan( File::DELETED_FILE,
579  $options['private'] instanceof User ? $options['private'] : null
580  )
581  ) {
582  return $img;
583  }
584  }
585  }
586 
587  return false;
588  }
589 
598  public function findBySha1( $hash ) {
599  return [];
600  }
601 
609  public function findBySha1s( array $hashes ) {
610  $result = [];
611  foreach ( $hashes as $hash ) {
612  $files = $this->findBySha1( $hash );
613  if ( count( $files ) ) {
614  $result[$hash] = $files;
615  }
616  }
617 
618  return $result;
619  }
620 
629  public function findFilesByPrefix( $prefix, $limit ) {
630  return [];
631  }
632 
638  public function getThumbScriptUrl() {
639  return $this->thumbScriptUrl;
640  }
641 
647  public function getThumbProxyUrl() {
648  return $this->thumbProxyUrl;
649  }
650 
656  public function getThumbProxySecret() {
658  }
659 
665  public function canTransformVia404() {
666  return $this->transformVia404;
667  }
668 
675  public function getNameFromTitle( Title $title ) {
676  if (
677  $this->initialCapital !=
678  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
679  ) {
680  $name = $title->getDBkey();
681  if ( $this->initialCapital ) {
682  $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
683  }
684  } else {
685  $name = $title->getDBkey();
686  }
687 
688  return $name;
689  }
690 
696  public function getRootDirectory() {
697  return $this->getZonePath( 'public' );
698  }
699 
707  public function getHashPath( $name ) {
708  return self::getHashPathForLevel( $name, $this->hashLevels );
709  }
710 
718  public function getTempHashPath( $suffix ) {
719  $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
720  $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
721  return self::getHashPathForLevel( $name, $this->hashLevels );
722  }
723 
729  protected static function getHashPathForLevel( $name, $levels ) {
730  if ( $levels == 0 ) {
731  return '';
732  } else {
733  $hash = md5( $name );
734  $path = '';
735  for ( $i = 1; $i <= $levels; $i++ ) {
736  $path .= substr( $hash, 0, $i ) . '/';
737  }
738 
739  return $path;
740  }
741  }
742 
748  public function getHashLevels() {
749  return $this->hashLevels;
750  }
751 
757  public function getName() {
758  return $this->name;
759  }
760 
768  public function makeUrl( $query = '', $entry = 'index' ) {
769  if ( isset( $this->scriptDirUrl ) ) {
770  return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
771  }
772 
773  return false;
774  }
775 
788  public function getDescriptionUrl( $name ) {
789  $encName = wfUrlencode( $name );
790  if ( $this->descBaseUrl !== null ) {
791  # "http://example.com/wiki/File:"
792  return $this->descBaseUrl . $encName;
793  }
794  if ( $this->articleUrl !== null ) {
795  # "http://example.com/wiki/$1"
796  # We use "Image:" as the canonical namespace for
797  # compatibility across all MediaWiki versions.
798  return str_replace( '$1',
799  "Image:$encName", $this->articleUrl );
800  }
801  if ( $this->scriptDirUrl !== null ) {
802  # "http://example.com/w"
803  # We use "Image:" as the canonical namespace for
804  # compatibility across all MediaWiki versions,
805  # and just sort of hope index.php is right. ;)
806  return $this->makeUrl( "title=Image:$encName" );
807  }
808 
809  return false;
810  }
811 
822  public function getDescriptionRenderUrl( $name, $lang = null ) {
823  $query = 'action=render';
824  if ( $lang !== null ) {
825  $query .= '&uselang=' . urlencode( $lang );
826  }
827  if ( isset( $this->scriptDirUrl ) ) {
828  return $this->makeUrl(
829  'title=' .
830  wfUrlencode( 'Image:' . $name ) .
831  "&$query" );
832  } else {
833  $descUrl = $this->getDescriptionUrl( $name );
834  if ( $descUrl ) {
835  return wfAppendQuery( $descUrl, $query );
836  } else {
837  return false;
838  }
839  }
840  }
841 
847  public function getDescriptionStylesheetUrl() {
848  if ( isset( $this->scriptDirUrl ) ) {
849  // Must match canonical query parameter order for optimum caching
850  // See Title::getCdnUrls
851  return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
852  }
853 
854  return false;
855  }
856 
874  public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
875  $this->assertWritableRepo(); // fail out if read-only
876 
877  $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
878  if ( $status->successCount == 0 ) {
879  $status->setOK( false );
880  }
881 
882  return $status;
883  }
884 
899  public function storeBatch( array $triplets, $flags = 0 ) {
900  $this->assertWritableRepo(); // fail out if read-only
901 
902  if ( $flags & self::DELETE_SOURCE ) {
903  throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
904  }
905 
906  $status = $this->newGood();
907  $backend = $this->backend; // convenience
908 
909  $operations = [];
910  // Validate each triplet and get the store operation...
911  foreach ( $triplets as $triplet ) {
912  list( $src, $dstZone, $dstRel ) = $triplet;
913  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
914  wfDebug( __METHOD__
915  . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
916  );
917  // Resolve source path
918  if ( $src instanceof FSFile ) {
919  $op = 'store';
920  } else {
921  $src = $this->resolveToStoragePathIfVirtual( $src );
922  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
923  }
924  // Resolve destination path
925  $root = $this->getZonePath( $dstZone );
926  if ( !$root ) {
927  throw new MWException( "Invalid zone: $dstZone" );
928  }
929  if ( !$this->validateFilename( $dstRel ) ) {
930  throw new MWException( 'Validation error in $dstRel' );
931  }
932  $dstPath = "$root/$dstRel";
933  $dstDir = dirname( $dstPath );
934  // Create destination directories for this triplet
935  if ( !$this->initDirectory( $dstDir )->isOK() ) {
936  return $this->newFatal( 'directorycreateerror', $dstDir );
937  }
938 
939  // Copy the source file to the destination
940  $operations[] = [
941  'op' => $op,
942  'src' => $src, // storage path (copy) or local file path (store)
943  'dst' => $dstPath,
944  'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
945  'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
946  ];
947  }
948 
949  // Execute the store operation for each triplet
950  $opts = [ 'force' => true ];
951  if ( $flags & self::SKIP_LOCKING ) {
952  $opts['nonLocking'] = true;
953  }
954  $status->merge( $backend->doOperations( $operations, $opts ) );
955 
956  return $status;
957  }
958 
969  public function cleanupBatch( array $files, $flags = 0 ) {
970  $this->assertWritableRepo(); // fail out if read-only
971 
972  $status = $this->newGood();
973 
974  $operations = [];
975  foreach ( $files as $path ) {
976  if ( is_array( $path ) ) {
977  // This is a pair, extract it
978  list( $zone, $rel ) = $path;
979  $path = $this->getZonePath( $zone ) . "/$rel";
980  } else {
981  // Resolve source to a storage path if virtual
982  $path = $this->resolveToStoragePathIfVirtual( $path );
983  }
984  $operations[] = [ 'op' => 'delete', 'src' => $path ];
985  }
986  // Actually delete files from storage...
987  $opts = [ 'force' => true ];
988  if ( $flags & self::SKIP_LOCKING ) {
989  $opts['nonLocking'] = true;
990  }
991  $status->merge( $this->backend->doOperations( $operations, $opts ) );
992 
993  return $status;
994  }
995 
1013  final public function quickImport( $src, $dst, $options = null ) {
1014  return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1015  }
1016 
1031  public function quickImportBatch( array $triples ) {
1032  $status = $this->newGood();
1033  $operations = [];
1034  foreach ( $triples as $triple ) {
1035  list( $src, $dst ) = $triple;
1036  if ( $src instanceof FSFile ) {
1037  $op = 'store';
1038  } else {
1039  $src = $this->resolveToStoragePathIfVirtual( $src );
1040  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1041  }
1042  $dst = $this->resolveToStoragePathIfVirtual( $dst );
1043 
1044  if ( !isset( $triple[2] ) ) {
1045  $headers = [];
1046  } elseif ( is_string( $triple[2] ) ) {
1047  // back-compat
1048  $headers = [ 'Content-Disposition' => $triple[2] ];
1049  } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1050  $headers = $triple[2]['headers'];
1051  } else {
1052  $headers = [];
1053  }
1054 
1055  $operations[] = [
1056  'op' => $op,
1057  'src' => $src, // storage path (copy) or local path/FSFile (store)
1058  'dst' => $dst,
1059  'headers' => $headers
1060  ];
1061  $status->merge( $this->initDirectory( dirname( $dst ) ) );
1062  }
1063  $status->merge( $this->backend->doQuickOperations( $operations ) );
1064 
1065  return $status;
1066  }
1067 
1076  final public function quickPurge( $path ) {
1077  return $this->quickPurgeBatch( [ $path ] );
1078  }
1079 
1087  public function quickCleanDir( $dir ) {
1088  $status = $this->newGood();
1089  $status->merge( $this->backend->clean(
1090  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1091 
1092  return $status;
1093  }
1094 
1103  public function quickPurgeBatch( array $paths ) {
1104  $status = $this->newGood();
1105  $operations = [];
1106  foreach ( $paths as $path ) {
1107  $operations[] = [
1108  'op' => 'delete',
1109  'src' => $this->resolveToStoragePathIfVirtual( $path ),
1110  'ignoreMissingSource' => true
1111  ];
1112  }
1113  $status->merge( $this->backend->doQuickOperations( $operations ) );
1114 
1115  return $status;
1116  }
1117 
1128  public function storeTemp( $originalName, $srcPath ) {
1129  $this->assertWritableRepo(); // fail out if read-only
1130 
1131  $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1132  $hashPath = $this->getHashPath( $originalName );
1133  $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1134  $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1135 
1136  $result = $this->quickImport( $srcPath, $virtualUrl );
1137  $result->value = $virtualUrl;
1138 
1139  return $result;
1140  }
1141 
1148  public function freeTemp( $virtualUrl ) {
1149  $this->assertWritableRepo(); // fail out if read-only
1150 
1151  $temp = $this->getVirtualUrl( 'temp' );
1152  if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1153  wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1154 
1155  return false;
1156  }
1157 
1158  return $this->quickPurge( $virtualUrl )->isOK();
1159  }
1160 
1170  public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1171  $this->assertWritableRepo(); // fail out if read-only
1172 
1173  $status = $this->newGood();
1174 
1175  $sources = [];
1176  foreach ( $srcPaths as $srcPath ) {
1177  // Resolve source to a storage path if virtual
1178  $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1179  $sources[] = $source; // chunk to merge
1180  }
1181 
1182  // Concatenate the chunks into one FS file
1183  $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1184  $status->merge( $this->backend->concatenate( $params ) );
1185  if ( !$status->isOK() ) {
1186  return $status;
1187  }
1188 
1189  // Delete the sources if required
1190  if ( $flags & self::DELETE_SOURCE ) {
1191  $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1192  }
1193 
1194  // Make sure status is OK, despite any quickPurgeBatch() fatals
1195  $status->setResult( true );
1196 
1197  return $status;
1198  }
1199 
1223  public function publish(
1224  $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1225  ) {
1226  $this->assertWritableRepo(); // fail out if read-only
1227 
1228  $status = $this->publishBatch(
1229  [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1230  if ( $status->successCount == 0 ) {
1231  $status->setOK( false );
1232  }
1233  $status->value = $status->value[0] ?? false;
1234 
1235  return $status;
1236  }
1237 
1250  public function publishBatch( array $ntuples, $flags = 0 ) {
1251  $this->assertWritableRepo(); // fail out if read-only
1252 
1253  $backend = $this->backend; // convenience
1254  // Try creating directories
1255  $status = $this->initZones( 'public' );
1256  if ( !$status->isOK() ) {
1257  return $status;
1258  }
1259 
1260  $status = $this->newGood( [] );
1261 
1262  $operations = [];
1263  $sourceFSFilesToDelete = []; // cleanup for disk source files
1264  // Validate each triplet and get the store operation...
1265  foreach ( $ntuples as $ntuple ) {
1266  list( $src, $dstRel, $archiveRel ) = $ntuple;
1267  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1268 
1269  $options = $ntuple[3] ?? [];
1270  // Resolve source to a storage path if virtual
1271  $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1272  if ( !$this->validateFilename( $dstRel ) ) {
1273  throw new MWException( 'Validation error in $dstRel' );
1274  }
1275  if ( !$this->validateFilename( $archiveRel ) ) {
1276  throw new MWException( 'Validation error in $archiveRel' );
1277  }
1278 
1279  $publicRoot = $this->getZonePath( 'public' );
1280  $dstPath = "$publicRoot/$dstRel";
1281  $archivePath = "$publicRoot/$archiveRel";
1282 
1283  $dstDir = dirname( $dstPath );
1284  $archiveDir = dirname( $archivePath );
1285  // Abort immediately on directory creation errors since they're likely to be repetitive
1286  if ( !$this->initDirectory( $dstDir )->isOK() ) {
1287  return $this->newFatal( 'directorycreateerror', $dstDir );
1288  }
1289  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1290  return $this->newFatal( 'directorycreateerror', $archiveDir );
1291  }
1292 
1293  // Set any desired headers to be use in GET/HEAD responses
1294  $headers = $options['headers'] ?? [];
1295 
1296  // Archive destination file if it exists.
1297  // This will check if the archive file also exists and fail if does.
1298  // This is a sanity check to avoid data loss. On Windows and Linux,
1299  // copy() will overwrite, so the existence check is vulnerable to
1300  // race conditions unless a functioning LockManager is used.
1301  // LocalFile also uses SELECT FOR UPDATE for synchronization.
1302  $operations[] = [
1303  'op' => 'copy',
1304  'src' => $dstPath,
1305  'dst' => $archivePath,
1306  'ignoreMissingSource' => true
1307  ];
1308 
1309  // Copy (or move) the source file to the destination
1310  if ( FileBackend::isStoragePath( $srcPath ) ) {
1311  $operations[] = [
1312  'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1313  'src' => $srcPath,
1314  'dst' => $dstPath,
1315  'overwrite' => true, // replace current
1316  'headers' => $headers
1317  ];
1318  } else {
1319  $operations[] = [
1320  'op' => 'store',
1321  'src' => $src, // storage path (copy) or local path/FSFile (store)
1322  'dst' => $dstPath,
1323  'overwrite' => true, // replace current
1324  'headers' => $headers
1325  ];
1326  if ( $flags & self::DELETE_SOURCE ) {
1327  $sourceFSFilesToDelete[] = $srcPath;
1328  }
1329  }
1330  }
1331 
1332  // Execute the operations for each triplet
1333  $status->merge( $backend->doOperations( $operations ) );
1334  // Find out which files were archived...
1335  foreach ( $ntuples as $i => $ntuple ) {
1336  list( , , $archiveRel ) = $ntuple;
1337  $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1338  if ( $this->fileExists( $archivePath ) ) {
1339  $status->value[$i] = 'archived';
1340  } else {
1341  $status->value[$i] = 'new';
1342  }
1343  }
1344  // Cleanup for disk source files...
1345  foreach ( $sourceFSFilesToDelete as $file ) {
1346  Wikimedia\suppressWarnings();
1347  unlink( $file ); // FS cleanup
1348  Wikimedia\restoreWarnings();
1349  }
1350 
1351  return $status;
1352  }
1353 
1361  protected function initDirectory( $dir ) {
1362  $path = $this->resolveToStoragePathIfVirtual( $dir );
1363  list( , $container, ) = FileBackend::splitStoragePath( $path );
1364 
1365  $params = [ 'dir' => $path ];
1366  if ( $this->isPrivate
1367  || $container === $this->zones['deleted']['container']
1368  || $container === $this->zones['temp']['container']
1369  ) {
1370  # Take all available measures to prevent web accessibility of new deleted
1371  # directories, in case the user has not configured offline storage
1372  $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1373  }
1374 
1375  $status = $this->newGood();
1376  $status->merge( $this->backend->prepare( $params ) );
1377 
1378  return $status;
1379  }
1380 
1387  public function cleanDir( $dir ) {
1388  $this->assertWritableRepo(); // fail out if read-only
1389 
1390  $status = $this->newGood();
1391  $status->merge( $this->backend->clean(
1392  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1393 
1394  return $status;
1395  }
1396 
1403  public function fileExists( $file ) {
1404  $result = $this->fileExistsBatch( [ $file ] );
1405 
1406  return $result[0];
1407  }
1408 
1415  public function fileExistsBatch( array $files ) {
1416  $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1417  $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1418 
1419  $result = [];
1420  foreach ( $files as $key => $file ) {
1422  $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1423  }
1424 
1425  return $result;
1426  }
1427 
1438  public function delete( $srcRel, $archiveRel ) {
1439  $this->assertWritableRepo(); // fail out if read-only
1440 
1441  return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1442  }
1443 
1461  public function deleteBatch( array $sourceDestPairs ) {
1462  $this->assertWritableRepo(); // fail out if read-only
1463 
1464  // Try creating directories
1465  $status = $this->initZones( [ 'public', 'deleted' ] );
1466  if ( !$status->isOK() ) {
1467  return $status;
1468  }
1469 
1470  $status = $this->newGood();
1471 
1472  $backend = $this->backend; // convenience
1473  $operations = [];
1474  // Validate filenames and create archive directories
1475  foreach ( $sourceDestPairs as $pair ) {
1476  list( $srcRel, $archiveRel ) = $pair;
1477  if ( !$this->validateFilename( $srcRel ) ) {
1478  throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1479  } elseif ( !$this->validateFilename( $archiveRel ) ) {
1480  throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1481  }
1482 
1483  $publicRoot = $this->getZonePath( 'public' );
1484  $srcPath = "{$publicRoot}/$srcRel";
1485 
1486  $deletedRoot = $this->getZonePath( 'deleted' );
1487  $archivePath = "{$deletedRoot}/{$archiveRel}";
1488  $archiveDir = dirname( $archivePath ); // does not touch FS
1489 
1490  // Create destination directories
1491  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1492  return $this->newFatal( 'directorycreateerror', $archiveDir );
1493  }
1494 
1495  $operations[] = [
1496  'op' => 'move',
1497  'src' => $srcPath,
1498  'dst' => $archivePath,
1499  // We may have 2+ identical files being deleted,
1500  // all of which will map to the same destination file
1501  'overwriteSame' => true // also see T33792
1502  ];
1503  }
1504 
1505  // Move the files by execute the operations for each pair.
1506  // We're now committed to returning an OK result, which will
1507  // lead to the files being moved in the DB also.
1508  $opts = [ 'force' => true ];
1509  $status->merge( $backend->doOperations( $operations, $opts ) );
1510 
1511  return $status;
1512  }
1513 
1520  public function cleanupDeletedBatch( array $storageKeys ) {
1521  $this->assertWritableRepo();
1522  }
1523 
1532  public function getDeletedHashPath( $key ) {
1533  if ( strlen( $key ) < 31 ) {
1534  throw new MWException( "Invalid storage key '$key'." );
1535  }
1536  $path = '';
1537  for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1538  $path .= $key[$i] . '/';
1539  }
1540 
1541  return $path;
1542  }
1543 
1552  protected function resolveToStoragePathIfVirtual( $path ) {
1553  if ( self::isVirtualUrl( $path ) ) {
1554  return $this->resolveVirtualUrl( $path );
1555  }
1556 
1557  return $path;
1558  }
1559 
1567  public function getLocalCopy( $virtualUrl ) {
1568  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1569 
1570  return $this->backend->getLocalCopy( [ 'src' => $path ] );
1571  }
1572 
1581  public function getLocalReference( $virtualUrl ) {
1582  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1583 
1584  return $this->backend->getLocalReference( [ 'src' => $path ] );
1585  }
1586 
1594  public function getFileProps( $virtualUrl ) {
1595  $fsFile = $this->getLocalReference( $virtualUrl );
1596  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1597  if ( $fsFile ) {
1598  $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1599  } else {
1600  $props = $mwProps->newPlaceholderProps();
1601  }
1602 
1603  return $props;
1604  }
1605 
1612  public function getFileTimestamp( $virtualUrl ) {
1613  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1614 
1615  return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1616  }
1617 
1624  public function getFileSize( $virtualUrl ) {
1625  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1626 
1627  return $this->backend->getFileSize( [ 'src' => $path ] );
1628  }
1629 
1636  public function getFileSha1( $virtualUrl ) {
1637  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1638 
1639  return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1640  }
1641 
1651  public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1652  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1653  $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1654 
1655  // T172851: HHVM does not flush the output properly, causing OOM
1656  ob_start( null, 1048576 );
1657  ob_implicit_flush( true );
1658 
1659  $status = $this->newGood();
1660  $status->merge( $this->backend->streamFile( $params ) );
1661 
1662  // T186565: Close the buffer, unless it has already been closed
1663  // in HTTPFileStreamer::resetOutputBuffers().
1664  if ( ob_get_status() ) {
1665  ob_end_flush();
1666  }
1667 
1668  return $status;
1669  }
1670 
1679  public function enumFiles( $callback ) {
1680  $this->enumFilesInStorage( $callback );
1681  }
1682 
1690  protected function enumFilesInStorage( $callback ) {
1691  $publicRoot = $this->getZonePath( 'public' );
1692  $numDirs = 1 << ( $this->hashLevels * 4 );
1693  // Use a priori assumptions about directory structure
1694  // to reduce the tree height of the scanning process.
1695  for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1696  $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1697  $path = $publicRoot;
1698  for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1699  $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1700  }
1701  $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1702  if ( $iterator === null ) {
1703  throw new MWException( __METHOD__ . ': could not get file listing for ' . $path );
1704  }
1705  foreach ( $iterator as $name ) {
1706  // Each item returned is a public file
1707  call_user_func( $callback, "{$path}/{$name}" );
1708  }
1709  }
1710  }
1711 
1718  public function validateFilename( $filename ) {
1719  if ( strval( $filename ) == '' ) {
1720  return false;
1721  }
1722 
1723  return FileBackend::isPathTraversalFree( $filename );
1724  }
1725 
1731  private function getErrorCleanupFunction() {
1732  switch ( $this->pathDisclosureProtection ) {
1733  case 'none':
1734  case 'simple': // b/c
1735  $callback = [ $this, 'passThrough' ];
1736  break;
1737  default: // 'paranoid'
1738  $callback = [ $this, 'paranoidClean' ];
1739  }
1740  return $callback;
1741  }
1742 
1749  public function paranoidClean( $param ) {
1750  return '[hidden]';
1751  }
1752 
1759  public function passThrough( $param ) {
1760  return $param;
1761  }
1762 
1770  public function newFatal( $message, ...$parameters ) {
1771  $status = Status::newFatal( $message, ...$parameters );
1772  $status->cleanCallback = $this->getErrorCleanupFunction();
1773 
1774  return $status;
1775  }
1776 
1783  public function newGood( $value = null ) {
1784  $status = Status::newGood( $value );
1785  $status->cleanCallback = $this->getErrorCleanupFunction();
1786 
1787  return $status;
1788  }
1789 
1798  public function checkRedirect( Title $title ) {
1799  return false;
1800  }
1801 
1809  public function invalidateImageRedirect( Title $title ) {
1810  }
1811 
1817  public function getDisplayName() {
1818  global $wgSitename;
1819 
1820  if ( $this->isLocal() ) {
1821  return $wgSitename;
1822  }
1823 
1824  // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1825  return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1826  }
1827 
1835  public function nameForThumb( $name ) {
1836  if ( strlen( $name ) > $this->abbrvThreshold ) {
1838  $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1839  }
1840 
1841  return $name;
1842  }
1843 
1849  public function isLocal() {
1850  return $this->getName() == 'local';
1851  }
1852 
1862  public function getSharedCacheKey( ...$args ) {
1863  return false;
1864  }
1865 
1874  public function getLocalCacheKey( ...$args ) {
1875  array_unshift( $args, 'filerepo', $this->getName() );
1876 
1877  return $this->wanCache->makeKey( ...$args );
1878  }
1879 
1888  public function getTempRepo() {
1889  return new TempFileRepo( [
1890  'name' => "{$this->name}-temp",
1891  'backend' => $this->backend,
1892  'zones' => [
1893  'public' => [
1894  // Same place storeTemp() uses in the base repo, though
1895  // the path hashing is mismatched, which is annoying.
1896  'container' => $this->zones['temp']['container'],
1897  'directory' => $this->zones['temp']['directory']
1898  ],
1899  'thumb' => [
1900  'container' => $this->zones['temp']['container'],
1901  'directory' => $this->zones['temp']['directory'] == ''
1902  ? 'thumb'
1903  : $this->zones['temp']['directory'] . '/thumb'
1904  ],
1905  'transcoded' => [
1906  'container' => $this->zones['temp']['container'],
1907  'directory' => $this->zones['temp']['directory'] == ''
1908  ? 'transcoded'
1909  : $this->zones['temp']['directory'] . '/transcoded'
1910  ]
1911  ],
1912  'hashLevels' => $this->hashLevels, // performance
1913  'isPrivate' => true // all in temp zone
1914  ] );
1915  }
1916 
1923  public function getUploadStash( User $user = null ) {
1924  return new UploadStash( $this, $user );
1925  }
1926 
1934  protected function assertWritableRepo() {
1935  }
1936 
1943  public function getInfo() {
1944  $ret = [
1945  'name' => $this->getName(),
1946  'displayname' => $this->getDisplayName(),
1947  'rootUrl' => $this->getZoneUrl( 'public' ),
1948  'local' => $this->isLocal(),
1949  ];
1950 
1951  $optionalSettings = [
1952  'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1953  'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1954  ];
1955  foreach ( $optionalSettings as $k ) {
1956  if ( isset( $this->$k ) ) {
1957  $ret[$k] = $this->$k;
1958  }
1959  }
1960 
1961  return $ret;
1962  }
1963 
1968  public function hasSha1Storage() {
1969  return $this->hasSha1Storage;
1970  }
1971 
1976  public function supportsSha1URLs() {
1977  return $this->supportsSha1URLs;
1978  }
1979 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1536
FileBackend\doOperations
doOperations(array $ops, array $opts=[])
This is the main entry point into the backend for write operations.
Definition: FileBackend.php:464
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:253
FileRepo\$supportsSha1URLs
bool $supportsSha1URLs
Definition: FileRepo.php:61
FileRepo\initZones
initZones( $doZones=[])
Check if a single zone or list of zones is defined for usage.
Definition: FileRepo.php:264
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1221
FileRepo\$hasSha1Storage
bool $hasSha1Storage
Definition: FileRepo.php:58
FileRepo\passThrough
passThrough( $param)
Path disclosure protection function.
Definition: FileRepo.php:1759
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
FileRepo\findBySha1
findBySha1( $hash)
Get an array or iterator of file objects for files that have a given SHA-1 content hash.
Definition: FileRepo.php:598
FileRepo\getThumbScriptUrl
getThumbScriptUrl()
Get the URL of thumb.php.
Definition: FileRepo.php:638
FileRepo\newGood
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1783
FileRepo\getDescriptionRenderUrl
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition: FileRepo.php:822
FileBackend
Base class for all file backend classes (including multi-write backends).
Definition: FileBackend.php:96
FileRepo\$deletedHashLevels
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition: FileRepo.php:114
FileRepo\enumFilesInStorage
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
Definition: FileRepo.php:1690
FileRepo\$favicon
string $favicon
The URL of the repo's favicon, if any.
Definition: FileRepo.php:123
FileRepo\OVERWRITE_SAME
const OVERWRITE_SAME
Definition: FileRepo.php:44
FileRepo\$isPrivate
bool $isPrivate
Whether all zones should be private (e.g.
Definition: FileRepo.php:126
FileRepo\validateFilename
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Definition: FileRepo.php:1718
FileRepo\getRootDirectory
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition: FileRepo.php:696
FileRepo\$fileFactoryKey
callable false $fileFactoryKey
Override these in the base class.
Definition: FileRepo.php:133
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:149
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
FileRepo\OVERWRITE
const OVERWRITE
Definition: FileRepo.php:43
FileRepo\getVirtualUrl
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:294
FileRepo\makeUrl
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition: FileRepo.php:768
FileRepo\$oldFileFactory
callable false $oldFileFactory
Override these in the base class.
Definition: FileRepo.php:131
FileRepo\storeBatch
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:899
FileRepo\$pathDisclosureProtection
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition: FileRepo.php:102
true
return true
Definition: router.php:90
FileRepo\streamFileWithStatus
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
Definition: FileRepo.php:1651
FileRepo\getTempRepo
getTempRepo()
Get a temporary private FileRepo associated with this repo.
Definition: FileRepo.php:1888
FileRepo\resolveToStoragePathIfVirtual
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
Definition: FileRepo.php:1552
FileRepo\getInfo
getInfo()
Return information about the repository.
Definition: FileRepo.php:1943
UploadStash
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:53
FileRepo\$descriptionCacheExpiry
int $descriptionCacheExpiry
Definition: FileRepo.php:55
FileRepo\getName
getName()
Get the name of this repository, as specified by $info['name]' to the constructor.
Definition: FileRepo.php:757
FileRepo\$thumbUrl
string $thumbUrl
The base thumbnail URL.
Definition: FileRepo.php:108
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:309
FileRepo\quickImportBatch
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
Definition: FileRepo.php:1031
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1598
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
FileRepo\getHashPathForLevel
static getHashPathForLevel( $name, $levels)
Definition: FileRepo.php:729
FileRepo\getZoneUrl
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition: FileRepo.php:310
FileRepo\$oldFileFactoryKey
callable false $oldFileFactoryKey
Override these in the base class.
Definition: FileRepo.php:135
FileRepo\getZonePath
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition: FileRepo.php:391
FileRepo\getLocalReference
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
Definition: FileRepo.php:1581
FileRepo\getZoneLocation
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition: FileRepo.php:377
FileRepo\$backend
FileBackend $backend
Definition: FileRepo.php:64
$base
$base
Definition: generateLocalAutoload.php:11
FileRepo\$wanCache
WANObjectCache $wanCache
Definition: FileRepo.php:145
FileRepo\$initialCapital
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition: FileRepo.php:95
File\normalizeTitle
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:197
FileRepo\publish
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:1223
FileRepo\getDescriptionStylesheetUrl
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition: FileRepo.php:847
FileRepo\fileExistsBatch
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1415
FileRepo
Base class for file repositories.
Definition: FileRepo.php:41
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:439
WANObjectCache\newEmpty
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Definition: WANObjectCache.php:348
FileRepo\freeTemp
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
Definition: FileRepo.php:1148
FileRepo\findFiles
findFiles(array $items, $flags=0)
Find many files at once.
Definition: FileRepo.php:524
FileRepo\quickPurge
quickPurge( $path)
Purge a file from the repo.
Definition: FileRepo.php:1076
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1968
FileRepo\findFileFromKey
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:561
FileRepo\newFile
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition: FileRepo.php:415
MWException
MediaWiki exception.
Definition: MWException.php:26
FileRepo\getLocalCacheKey
getLocalCacheKey(... $args)
Get a key for this repo in the local cache domain.
Definition: FileRepo.php:1874
FileRepo\enumFiles
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
Definition: FileRepo.php:1679
FileRepo\checkRedirect
checkRedirect(Title $title)
Checks if there is a redirect named as $title.
Definition: FileRepo.php:1798
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1013
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1524
FileRepo\getUploadStash
getUploadStash(User $user=null)
Get an UploadStash associated with this repo.
Definition: FileRepo.php:1923
FileRepo\$thumbScriptUrl
string $thumbScriptUrl
URL of thumb.php.
Definition: FileRepo.php:70
FileRepo\findFilesByPrefix
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition: FileRepo.php:629
FileRepo\$zones
array $zones
Map of zones to config.
Definition: FileRepo.php:67
FileRepo\paranoidClean
paranoidClean( $param)
Path disclosure protection function.
Definition: FileRepo.php:1749
MediaWiki
A helper class for throttling authentication attempts.
FileBackend\ATTR_UNICODE_PATHS
const ATTR_UNICODE_PATHS
Definition: FileBackend.php:134
FileRepo\getDescriptionUrl
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition: FileRepo.php:788
FileRepo\getThumbProxySecret
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition: FileRepo.php:656
$args
if( $line===false) $args
Definition: mcc.php:124
FileRepo\store
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition: FileRepo.php:874
MWTimestamp\getInstance
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:39
$title
$title
Definition: testCompression.php:38
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
FileRepo\nameForThumb
nameForThumb( $name)
Get the portion of the file that contains the origin file name.
Definition: FileRepo.php:1835
FileRepo\invalidateImageRedirect
invalidateImageRedirect(Title $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
Definition: FileRepo.php:1809
FileRepo\getThumbProxyUrl
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition: FileRepo.php:647
FileRepo\getLocalCopy
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1567
TempFileRepo
FileRepo for temporary files created via FileRepo::getTempRepo()
Definition: TempFileRepo.php:5
FileRepo\cleanupBatch
cleanupBatch(array $files, $flags=0)
Deletes a batch of files.
Definition: FileRepo.php:969
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:913
FileRepo\fileExists
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1403
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1636
FileRepo\backendSupportsUnicodePaths
backendSupportsUnicodePaths()
Definition: FileRepo.php:339
FileRepo\newFatal
newFatal( $message,... $parameters)
Create a new fatal error.
Definition: FileRepo.php:1770
FileRepo\getNameFromTitle
getNameFromTitle(Title $title)
Get the name of a file from its title object.
Definition: FileRepo.php:675
FileRepo\getDisplayName
getDisplayName()
Get the human-readable name of the repo.
Definition: FileRepo.php:1817
FileRepo\findFile
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:448
FileRepo\SKIP_LOCKING
const SKIP_LOCKING
Definition: FileRepo.php:45
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
FileRepo\storeTemp
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
Definition: FileRepo.php:1128
FileRepo\publishBatch
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
Definition: FileRepo.php:1250
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:125
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:80
FileRepo\$scriptDirUrl
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition: FileRepo.php:85
FileRepo\$articleUrl
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition: FileRepo.php:88
FileRepo\getHashLevels
getHashLevels()
Get the number of hash directory levels.
Definition: FileRepo.php:748
FileRepo\initDirectory
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
Definition: FileRepo.php:1361
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
FileRepo\getBackend
getBackend()
Get the file backend instance.
Definition: FileRepo.php:243
FileRepo\$fileFactory
callable $fileFactory
Override these in the base class.
Definition: FileRepo.php:129
FileRepo\quickPurgeBatch
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
Definition: FileRepo.php:1103
FileRepo\getFileSize
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1624
FileRepo\isLocal
isLocal()
Returns true if this the local file repository.
Definition: FileRepo.php:1849
FileRepo\$thumbProxySecret
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition: FileRepo.php:142
FileRepo\getHashPath
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:707
FileRepo\$name
string $name
Definition: FileRepo.php:151
FileRepo\getErrorCleanupFunction
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
Definition: FileRepo.php:1731
Title
Represents a title within MediaWiki.
Definition: Title.php:42
FileRepo\__construct
__construct(array $info=null)
Definition: FileRepo.php:159
FileRepo\findBySha1s
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:609
FileRepo\getSharedCacheKey
getSharedCacheKey(... $args)
Get a key on the primary cache for this repository.
Definition: FileRepo.php:1862
FileRepo\getTempHashPath
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:718
FileRepo\$descBaseUrl
string $descBaseUrl
URL of image description pages, e.g.
Definition: FileRepo.php:80
$path
$path
Definition: NoLocalSettings.php:25
FileRepo\quickCleanDir
quickCleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1087
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:282
FileRepo\getFileTimestamp
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1612
FileRepo\concatenate
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
Definition: FileRepo.php:1170
FileRepo\deleteBatch
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
Definition: FileRepo.php:1461
FileRepo\resolveVirtualUrl
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:351
$source
$source
Definition: mwdoc-filter.php:34
FileBackend\isPathTraversalFree
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
Definition: FileBackend.php:1620
FileRepo\cleanDir
cleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1387
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
$hashes
$hashes
Definition: testCompression.php:71
FileRepo\DELETE_SOURCE
const DELETE_SOURCE
Definition: FileRepo.php:42
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:66
FileRepo\getFileProps
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1594
FileRepo\$abbrvThreshold
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
Definition: FileRepo.php:120
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:55
FileRepo\$transformVia404
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition: FileRepo.php:75
FileRepo\supportsSha1URLs
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
Definition: FileRepo.php:1976
FileRepo\$hashLevels
int $hashLevels
The number of directory levels for hash-based division of files.
Definition: FileRepo.php:111
FileRepo\getDeletedHashPath
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1532
FileRepo\assertWritableRepo
assertWritableRepo()
Throw an exception if this repo is read-only by design.
Definition: FileRepo.php:1934
FileRepo\NAME_AND_TIME_ONLY
const NAME_AND_TIME_ONLY
Definition: FileRepo.php:47
FileRepo\cleanupDeletedBatch
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table.
Definition: FileRepo.php:1520
FileRepo\$url
string false $url
Public zone URL.
Definition: FileRepo.php:105
FileRepo\canTransformVia404
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
Definition: FileRepo.php:665
FileRepo\$fetchDescription
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition: FileRepo.php:52
FileRepo\$thumbProxyUrl
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition: FileRepo.php:140