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