MediaWiki  master
FileRepo.php
Go to the documentation of this file.
1 <?php
15 
45 class FileRepo {
46  public const DELETE_SOURCE = 1;
47  public const OVERWRITE = 2;
48  public const OVERWRITE_SAME = 4;
49  public const SKIP_LOCKING = 8;
50 
51  public const NAME_AND_TIME_ONLY = 1;
52 
57 
60 
62  protected $hasSha1Storage = false;
63 
65  protected $supportsSha1URLs = false;
66 
68  protected $backend;
69 
71  protected $zones = [];
72 
74  protected $thumbScriptUrl;
75 
79  protected $transformVia404;
80 
84  protected $descBaseUrl;
85 
89  protected $scriptDirUrl;
90 
92  protected $articleUrl;
93 
99  protected $initialCapital;
100 
106  protected $pathDisclosureProtection = 'simple';
107 
109  protected $url;
110 
112  protected $thumbUrl;
113 
115  protected $hashLevels;
116 
119 
124  protected $abbrvThreshold;
125 
127  protected $favicon;
128 
130  protected $isPrivate;
131 
133  protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
135  protected $oldFileFactory = false;
137  protected $fileFactoryKey = false;
139  protected $oldFileFactoryKey = false;
140 
144  protected $thumbProxyUrl;
146  protected $thumbProxySecret;
147 
149  protected $disableLocalTransform = false;
150 
152  protected $wanCache;
153 
159  public $name;
160 
167  public function __construct( array $info = null ) {
168  // Verify required settings presence
169  if (
170  $info === null
171  || !array_key_exists( 'name', $info )
172  || !array_key_exists( 'backend', $info )
173  ) {
174  throw new MWException( __CLASS__ .
175  " requires an array of options having both 'name' and 'backend' keys.\n" );
176  }
177 
178  // Required settings
179  $this->name = $info['name'];
180  if ( $info['backend'] instanceof FileBackend ) {
181  $this->backend = $info['backend']; // useful for testing
182  } else {
183  $this->backend =
184  MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
185  }
186 
187  // Optional settings that can have no value
188  $optionalSettings = [
189  'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
190  'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
191  'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
192  ];
193  foreach ( $optionalSettings as $var ) {
194  if ( isset( $info[$var] ) ) {
195  $this->$var = $info[$var];
196  }
197  }
198 
199  // Optional settings that have a default
200  $localCapitalLinks =
201  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
202  $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
203  if ( $localCapitalLinks && !$this->initialCapital ) {
204  // If the local wiki's file namespace requires an initial capital, but a foreign file
205  // repo doesn't, complications will result. Linker code will want to auto-capitalize the
206  // first letter of links to files, but those links might actually point to files on
207  // foreign wikis with initial-lowercase names. This combination is not likely to be
208  // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
209  // to include a foreign file repo with initialCapital false, set your local file
210  // namespace to not be capitalized either.
211  throw new InvalidArgumentException(
212  'File repos with initial capital false are not allowed on wikis where the File ' .
213  'namespace has initial capital true' );
214  }
215 
216  $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
217  if ( isset( $info['thumbUrl'] ) ) {
218  $this->thumbUrl = $info['thumbUrl'];
219  } else {
220  $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
221  }
222  $this->hashLevels = $info['hashLevels'] ?? 2;
223  $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
224  $this->transformVia404 = !empty( $info['transformVia404'] );
225  $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
226  $this->isPrivate = !empty( $info['isPrivate'] );
227  // Give defaults for the basic zones...
228  $this->zones = $info['zones'] ?? [];
229  foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
230  if ( !isset( $this->zones[$zone]['container'] ) ) {
231  $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
232  }
233  if ( !isset( $this->zones[$zone]['directory'] ) ) {
234  $this->zones[$zone]['directory'] = '';
235  }
236  if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
237  $this->zones[$zone]['urlsByExt'] = [];
238  }
239  }
240 
241  $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
242 
243  $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
244  }
245 
251  public function getBackend() {
252  return $this->backend;
253  }
254 
261  public function getReadOnlyReason() {
262  return $this->backend->getReadOnlyReason();
263  }
264 
272  protected function initZones( $doZones = [] ) {
273  $status = $this->newGood();
274  foreach ( (array)$doZones as $zone ) {
275  $root = $this->getZonePath( $zone );
276  if ( $root === null ) {
277  throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
278  }
279  }
280 
281  return $status;
282  }
283 
290  public static function isVirtualUrl( $url ) {
291  return substr( $url, 0, 9 ) == 'mwrepo://';
292  }
293 
302  public function getVirtualUrl( $suffix = false ) {
303  $path = 'mwrepo://' . $this->name;
304  if ( $suffix !== false ) {
305  $path .= '/' . rawurlencode( $suffix );
306  }
307 
308  return $path;
309  }
310 
318  public function getZoneUrl( $zone, $ext = null ) {
319  if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
320  // standard public zones
321  if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
322  // custom URL for extension/zone
323  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
324  return $this->zones[$zone]['urlsByExt'][$ext];
325  } elseif ( isset( $this->zones[$zone]['url'] ) ) {
326  // custom URL for zone
327  return $this->zones[$zone]['url'];
328  }
329  }
330  switch ( $zone ) {
331  case 'public':
332  return $this->url;
333  case 'temp':
334  case 'deleted':
335  return false; // no public URL
336  case 'thumb':
337  return $this->thumbUrl;
338  case 'transcoded':
339  return "{$this->url}/transcoded";
340  default:
341  return false;
342  }
343  }
344 
348  public function backendSupportsUnicodePaths() {
349  return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
350  }
351 
360  public function resolveVirtualUrl( $url ) {
361  if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
362  throw new MWException( __METHOD__ . ': unknown protocol' );
363  }
364  $bits = explode( '/', substr( $url, 9 ), 3 );
365  if ( count( $bits ) != 3 ) {
366  throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
367  }
368  list( $repo, $zone, $rel ) = $bits;
369  if ( $repo !== $this->name ) {
370  throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
371  }
372  $base = $this->getZonePath( $zone );
373  if ( !$base ) {
374  throw new MWException( __METHOD__ . ": invalid zone: $zone" );
375  }
376 
377  return $base . '/' . rawurldecode( $rel );
378  }
379 
386  protected function getZoneLocation( $zone ) {
387  if ( !isset( $this->zones[$zone] ) ) {
388  return [ null, null ]; // bogus
389  }
390 
391  return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
392  }
393 
400  public function getZonePath( $zone ) {
401  list( $container, $base ) = $this->getZoneLocation( $zone );
402  if ( $container === null || $base === null ) {
403  return null;
404  }
405  $backendName = $this->backend->getName();
406  if ( $base != '' ) { // may not be set
407  $base = "/{$base}";
408  }
409 
410  return "mwstore://$backendName/{$container}{$base}";
411  }
412 
424  public function newFile( $title, $time = false ) {
426  if ( !$title ) {
427  return null;
428  }
429  if ( $time ) {
430  if ( $this->oldFileFactory ) {
431  return call_user_func( $this->oldFileFactory, $title, $this, $time );
432  } else {
433  return null;
434  }
435  } else {
436  return call_user_func( $this->fileFactory, $title, $this );
437  }
438  }
439 
459  public function findFile( $title, $options = [] ) {
460  if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
461  throw new InvalidArgumentException(
462  __METHOD__ . ' called with the `private` option set to something ' .
463  'other than an Authority object'
464  );
465  }
466 
468  if ( !$title ) {
469  return false;
470  }
471  if ( isset( $options['bypassCache'] ) ) {
472  $options['latest'] = $options['bypassCache']; // b/c
473  }
474  $time = $options['time'] ?? false;
475  $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
476  # First try the current version of the file to see if it precedes the timestamp
477  $img = $this->newFile( $title );
478  if ( !$img ) {
479  return false;
480  }
481  $img->load( $flags );
482  if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
483  return $img;
484  }
485  # Now try an old version of the file
486  if ( $time !== false ) {
487  $img = $this->newFile( $title, $time );
488  if ( $img ) {
489  $img->load( $flags );
490  if ( $img->exists() ) {
491  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
492  return $img; // always OK
493  } elseif (
494  // If its not empty, its an Authority object
495  !empty( $options['private'] ) &&
496  $img->userCan( File::DELETED_FILE, $options['private'] )
497  ) {
498  return $img;
499  }
500  }
501  }
502  }
503 
504  # Now try redirects
505  if ( !empty( $options['ignoreRedirect'] ) ) {
506  return false;
507  }
508  $redir = $this->checkRedirect( $title );
509  if ( $redir && $title->getNamespace() === NS_FILE ) {
510  $img = $this->newFile( $redir );
511  if ( !$img ) {
512  return false;
513  }
514  $img->load( $flags );
515  if ( $img->exists() ) {
516  $img->redirectedFrom( $title->getDBkey() );
517 
518  return $img;
519  }
520  }
521 
522  return false;
523  }
524 
542  public function findFiles( array $items, $flags = 0 ) {
543  $result = [];
544  foreach ( $items as $item ) {
545  if ( is_array( $item ) ) {
546  $title = $item['title'];
547  $options = $item;
548  unset( $options['title'] );
549 
550  if (
551  !empty( $options['private'] ) &&
552  !( $options['private'] instanceof Authority )
553  ) {
554  $options['private'] = RequestContext::getMain()->getAuthority();
555  }
556  } else {
557  $title = $item;
558  $options = [];
559  }
560  $file = $this->findFile( $title, $options );
561  if ( $file ) {
562  $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
563  if ( $flags & self::NAME_AND_TIME_ONLY ) {
564  $result[$searchName] = [
565  'title' => $file->getTitle()->getDBkey(),
566  'timestamp' => $file->getTimestamp()
567  ];
568  } else {
569  $result[$searchName] = $file;
570  }
571  }
572  }
573 
574  return $result;
575  }
576 
587  public function findFileFromKey( $sha1, $options = [] ) {
588  if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority ) ) {
589  throw new InvalidArgumentException(
590  __METHOD__ . ' called with the `private` option set to something ' .
591  'other than an Authority object'
592  );
593  }
594 
595  $time = $options['time'] ?? false;
596  # First try to find a matching current version of a file...
597  if ( !$this->fileFactoryKey ) {
598  return false; // find-by-sha1 not supported
599  }
600  $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
601  if ( $img && $img->exists() ) {
602  return $img;
603  }
604  # Now try to find a matching old version of a file...
605  if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
606  $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
607  if ( $img && $img->exists() ) {
608  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
609  return $img; // always OK
610  } elseif (
611  // If its not empty, its an Authority object
612  !empty( $options['private'] ) &&
613  $img->userCan( File::DELETED_FILE, $options['private'] )
614  ) {
615  return $img;
616  }
617  }
618  }
619 
620  return false;
621  }
622 
631  public function findBySha1( $hash ) {
632  return [];
633  }
634 
642  public function findBySha1s( array $hashes ) {
643  $result = [];
644  foreach ( $hashes as $hash ) {
645  $files = $this->findBySha1( $hash );
646  if ( count( $files ) ) {
647  $result[$hash] = $files;
648  }
649  }
650 
651  return $result;
652  }
653 
662  public function findFilesByPrefix( $prefix, $limit ) {
663  return [];
664  }
665 
671  public function getThumbScriptUrl() {
672  return $this->thumbScriptUrl;
673  }
674 
680  public function getThumbProxyUrl() {
681  return $this->thumbProxyUrl;
682  }
683 
689  public function getThumbProxySecret() {
691  }
692 
698  public function canTransformVia404() {
699  return $this->transformVia404;
700  }
701 
708  public function canTransformLocally() {
710  }
711 
718  public function getNameFromTitle( $title ) {
719  if (
720  $this->initialCapital !=
721  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
722  ) {
723  $name = $title->getDBkey();
724  if ( $this->initialCapital ) {
725  $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
726  }
727  } else {
728  $name = $title->getDBkey();
729  }
730 
731  return $name;
732  }
733 
739  public function getRootDirectory() {
740  return $this->getZonePath( 'public' );
741  }
742 
750  public function getHashPath( $name ) {
751  return self::getHashPathForLevel( $name, $this->hashLevels );
752  }
753 
761  public function getTempHashPath( $suffix ) {
762  $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
763  $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
764  return self::getHashPathForLevel( $name, $this->hashLevels );
765  }
766 
772  protected static function getHashPathForLevel( $name, $levels ) {
773  if ( $levels == 0 ) {
774  return '';
775  } else {
776  $hash = md5( $name );
777  $path = '';
778  for ( $i = 1; $i <= $levels; $i++ ) {
779  $path .= substr( $hash, 0, $i ) . '/';
780  }
781 
782  return $path;
783  }
784  }
785 
791  public function getHashLevels() {
792  return $this->hashLevels;
793  }
794 
800  public function getName() {
801  return $this->name;
802  }
803 
811  public function makeUrl( $query = '', $entry = 'index' ) {
812  if ( isset( $this->scriptDirUrl ) ) {
813  return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
814  }
815 
816  return false;
817  }
818 
831  public function getDescriptionUrl( $name ) {
832  $encName = wfUrlencode( $name );
833  if ( $this->descBaseUrl !== null ) {
834  # "http://example.com/wiki/File:"
835  return $this->descBaseUrl . $encName;
836  }
837  if ( $this->articleUrl !== null ) {
838  # "http://example.com/wiki/$1"
839  # We use "Image:" as the canonical namespace for
840  # compatibility across all MediaWiki versions.
841  return str_replace( '$1',
842  "Image:$encName", $this->articleUrl );
843  }
844  if ( $this->scriptDirUrl !== null ) {
845  # "http://example.com/w"
846  # We use "Image:" as the canonical namespace for
847  # compatibility across all MediaWiki versions,
848  # and just sort of hope index.php is right. ;)
849  return $this->makeUrl( "title=Image:$encName" );
850  }
851 
852  return false;
853  }
854 
865  public function getDescriptionRenderUrl( $name, $lang = null ) {
866  $query = 'action=render';
867  if ( $lang !== null ) {
868  $query .= '&uselang=' . urlencode( $lang );
869  }
870  if ( isset( $this->scriptDirUrl ) ) {
871  return $this->makeUrl(
872  'title=' .
873  wfUrlencode( 'Image:' . $name ) .
874  "&$query" );
875  } else {
876  $descUrl = $this->getDescriptionUrl( $name );
877  if ( $descUrl ) {
878  return wfAppendQuery( $descUrl, $query );
879  } else {
880  return false;
881  }
882  }
883  }
884 
890  public function getDescriptionStylesheetUrl() {
891  if ( isset( $this->scriptDirUrl ) ) {
892  // Must match canonical query parameter order for optimum caching
893  // See HtmlCacheUpdater::getUrls
894  return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
895  }
896 
897  return false;
898  }
899 
917  public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
918  $this->assertWritableRepo(); // fail out if read-only
919 
920  $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
921  if ( $status->successCount == 0 ) {
922  $status->setOK( false );
923  }
924 
925  return $status;
926  }
927 
942  public function storeBatch( array $triplets, $flags = 0 ) {
943  $this->assertWritableRepo(); // fail out if read-only
944 
945  if ( $flags & self::DELETE_SOURCE ) {
946  throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
947  }
948 
949  $status = $this->newGood();
950  $backend = $this->backend; // convenience
951 
952  $operations = [];
953  // Validate each triplet and get the store operation...
954  foreach ( $triplets as $triplet ) {
955  list( $src, $dstZone, $dstRel ) = $triplet;
956  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
957  wfDebug( __METHOD__
958  . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
959  );
960  // Resolve source path
961  if ( $src instanceof FSFile ) {
962  $op = 'store';
963  } else {
964  $src = $this->resolveToStoragePathIfVirtual( $src );
965  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
966  }
967  // Resolve destination path
968  $root = $this->getZonePath( $dstZone );
969  if ( !$root ) {
970  throw new MWException( "Invalid zone: $dstZone" );
971  }
972  if ( !$this->validateFilename( $dstRel ) ) {
973  throw new MWException( 'Validation error in $dstRel' );
974  }
975  $dstPath = "$root/$dstRel";
976  $dstDir = dirname( $dstPath );
977  // Create destination directories for this triplet
978  if ( !$this->initDirectory( $dstDir )->isOK() ) {
979  return $this->newFatal( 'directorycreateerror', $dstDir );
980  }
981 
982  // Copy the source file to the destination
983  $operations[] = [
984  'op' => $op,
985  'src' => $src, // storage path (copy) or local file path (store)
986  'dst' => $dstPath,
987  'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
988  'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
989  ];
990  }
991 
992  // Execute the store operation for each triplet
993  $opts = [ 'force' => true ];
994  if ( $flags & self::SKIP_LOCKING ) {
995  $opts['nonLocking'] = true;
996  }
997 
998  return $status->merge( $backend->doOperations( $operations, $opts ) );
999  }
1000 
1011  public function cleanupBatch( array $files, $flags = 0 ) {
1012  $this->assertWritableRepo(); // fail out if read-only
1013 
1014  $status = $this->newGood();
1015 
1016  $operations = [];
1017  foreach ( $files as $path ) {
1018  if ( is_array( $path ) ) {
1019  // This is a pair, extract it
1020  list( $zone, $rel ) = $path;
1021  $path = $this->getZonePath( $zone ) . "/$rel";
1022  } else {
1023  // Resolve source to a storage path if virtual
1024  $path = $this->resolveToStoragePathIfVirtual( $path );
1025  }
1026  $operations[] = [ 'op' => 'delete', 'src' => $path ];
1027  }
1028  // Actually delete files from storage...
1029  $opts = [ 'force' => true ];
1030  if ( $flags & self::SKIP_LOCKING ) {
1031  $opts['nonLocking'] = true;
1032  }
1033 
1034  return $status->merge( $this->backend->doOperations( $operations, $opts ) );
1035  }
1036 
1054  final public function quickImport( $src, $dst, $options = null ) {
1055  return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1056  }
1057 
1072  public function quickImportBatch( array $triples ) {
1073  $status = $this->newGood();
1074  $operations = [];
1075  foreach ( $triples as $triple ) {
1076  list( $src, $dst ) = $triple;
1077  if ( $src instanceof FSFile ) {
1078  $op = 'store';
1079  } else {
1080  $src = $this->resolveToStoragePathIfVirtual( $src );
1081  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1082  }
1083  $dst = $this->resolveToStoragePathIfVirtual( $dst );
1084 
1085  if ( !isset( $triple[2] ) ) {
1086  $headers = [];
1087  } elseif ( is_string( $triple[2] ) ) {
1088  // back-compat
1089  $headers = [ 'Content-Disposition' => $triple[2] ];
1090  } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1091  $headers = $triple[2]['headers'];
1092  } else {
1093  $headers = [];
1094  }
1095 
1096  $operations[] = [
1097  'op' => $op,
1098  'src' => $src, // storage path (copy) or local path/FSFile (store)
1099  'dst' => $dst,
1100  'headers' => $headers
1101  ];
1102  $status->merge( $this->initDirectory( dirname( $dst ) ) );
1103  }
1104 
1105  return $status->merge( $this->backend->doQuickOperations( $operations ) );
1106  }
1107 
1116  final public function quickPurge( $path ) {
1117  return $this->quickPurgeBatch( [ $path ] );
1118  }
1119 
1127  public function quickCleanDir( $dir ) {
1128  return $this->newGood()->merge(
1129  $this->backend->clean(
1130  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1131  )
1132  );
1133  }
1134 
1143  public function quickPurgeBatch( array $paths ) {
1144  $status = $this->newGood();
1145  $operations = [];
1146  foreach ( $paths as $path ) {
1147  $operations[] = [
1148  'op' => 'delete',
1149  'src' => $this->resolveToStoragePathIfVirtual( $path ),
1150  'ignoreMissingSource' => true
1151  ];
1152  }
1153  $status->merge( $this->backend->doQuickOperations( $operations ) );
1154 
1155  return $status;
1156  }
1157 
1168  public function storeTemp( $originalName, $srcPath ) {
1169  $this->assertWritableRepo(); // fail out if read-only
1170 
1171  $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1172  $hashPath = $this->getHashPath( $originalName );
1173  $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1174  $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1175 
1176  $result = $this->quickImport( $srcPath, $virtualUrl );
1177  $result->value = $virtualUrl;
1178 
1179  return $result;
1180  }
1181 
1188  public function freeTemp( $virtualUrl ) {
1189  $this->assertWritableRepo(); // fail out if read-only
1190 
1191  $temp = $this->getVirtualUrl( 'temp' );
1192  if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1193  wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1194 
1195  return false;
1196  }
1197 
1198  return $this->quickPurge( $virtualUrl )->isOK();
1199  }
1200 
1210  public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1211  $this->assertWritableRepo(); // fail out if read-only
1212 
1213  $status = $this->newGood();
1214 
1215  $sources = [];
1216  foreach ( $srcPaths as $srcPath ) {
1217  // Resolve source to a storage path if virtual
1218  $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1219  $sources[] = $source; // chunk to merge
1220  }
1221 
1222  // Concatenate the chunks into one FS file
1223  $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1224  $status->merge( $this->backend->concatenate( $params ) );
1225  if ( !$status->isOK() ) {
1226  return $status;
1227  }
1228 
1229  // Delete the sources if required
1230  if ( $flags & self::DELETE_SOURCE ) {
1231  $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1232  }
1233 
1234  // Make sure status is OK, despite any quickPurgeBatch() fatals
1235  $status->setResult( true );
1236 
1237  return $status;
1238  }
1239 
1263  public function publish(
1264  $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1265  ) {
1266  $this->assertWritableRepo(); // fail out if read-only
1267 
1268  $status = $this->publishBatch(
1269  [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1270  if ( $status->successCount == 0 ) {
1271  $status->setOK( false );
1272  }
1273  $status->value = $status->value[0] ?? false;
1274 
1275  return $status;
1276  }
1277 
1290  public function publishBatch( array $ntuples, $flags = 0 ) {
1291  $this->assertWritableRepo(); // fail out if read-only
1292 
1293  $backend = $this->backend; // convenience
1294  // Try creating directories
1295  $status = $this->initZones( 'public' );
1296  if ( !$status->isOK() ) {
1297  return $status;
1298  }
1299 
1300  $status = $this->newGood( [] );
1301 
1302  $operations = [];
1303  $sourceFSFilesToDelete = []; // cleanup for disk source files
1304  // Validate each triplet and get the store operation...
1305  foreach ( $ntuples as $ntuple ) {
1306  list( $src, $dstRel, $archiveRel ) = $ntuple;
1307  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1308 
1309  $options = $ntuple[3] ?? [];
1310  // Resolve source to a storage path if virtual
1311  $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1312  if ( !$this->validateFilename( $dstRel ) ) {
1313  throw new MWException( 'Validation error in $dstRel' );
1314  }
1315  if ( !$this->validateFilename( $archiveRel ) ) {
1316  throw new MWException( 'Validation error in $archiveRel' );
1317  }
1318 
1319  $publicRoot = $this->getZonePath( 'public' );
1320  $dstPath = "$publicRoot/$dstRel";
1321  $archivePath = "$publicRoot/$archiveRel";
1322 
1323  $dstDir = dirname( $dstPath );
1324  $archiveDir = dirname( $archivePath );
1325  // Abort immediately on directory creation errors since they're likely to be repetitive
1326  if ( !$this->initDirectory( $dstDir )->isOK() ) {
1327  return $this->newFatal( 'directorycreateerror', $dstDir );
1328  }
1329  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1330  return $this->newFatal( 'directorycreateerror', $archiveDir );
1331  }
1332 
1333  // Set any desired headers to be use in GET/HEAD responses
1334  $headers = $options['headers'] ?? [];
1335 
1336  // Archive destination file if it exists.
1337  // This will check if the archive file also exists and fail if does.
1338  // This is a sanity check to avoid data loss. On Windows and Linux,
1339  // copy() will overwrite, so the existence check is vulnerable to
1340  // race conditions unless a functioning LockManager is used.
1341  // LocalFile also uses SELECT FOR UPDATE for synchronization.
1342  $operations[] = [
1343  'op' => 'copy',
1344  'src' => $dstPath,
1345  'dst' => $archivePath,
1346  'ignoreMissingSource' => true
1347  ];
1348 
1349  // Copy (or move) the source file to the destination
1350  if ( FileBackend::isStoragePath( $srcPath ) ) {
1351  $operations[] = [
1352  'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1353  'src' => $srcPath,
1354  'dst' => $dstPath,
1355  'overwrite' => true, // replace current
1356  'headers' => $headers
1357  ];
1358  } else {
1359  $operations[] = [
1360  'op' => 'store',
1361  'src' => $src, // storage path (copy) or local path/FSFile (store)
1362  'dst' => $dstPath,
1363  'overwrite' => true, // replace current
1364  'headers' => $headers
1365  ];
1366  if ( $flags & self::DELETE_SOURCE ) {
1367  $sourceFSFilesToDelete[] = $srcPath;
1368  }
1369  }
1370  }
1371 
1372  // Execute the operations for each triplet
1373  $status->merge( $backend->doOperations( $operations ) );
1374  // Find out which files were archived...
1375  foreach ( $ntuples as $i => $ntuple ) {
1376  list( , , $archiveRel ) = $ntuple;
1377  $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1378  if ( $this->fileExists( $archivePath ) ) {
1379  $status->value[$i] = 'archived';
1380  } else {
1381  $status->value[$i] = 'new';
1382  }
1383  }
1384  // Cleanup for disk source files...
1385  foreach ( $sourceFSFilesToDelete as $file ) {
1386  Wikimedia\suppressWarnings();
1387  unlink( $file ); // FS cleanup
1388  Wikimedia\restoreWarnings();
1389  }
1390 
1391  return $status;
1392  }
1393 
1401  protected function initDirectory( $dir ) {
1402  $path = $this->resolveToStoragePathIfVirtual( $dir );
1403  list( , $container, ) = FileBackend::splitStoragePath( $path );
1404 
1405  $params = [ 'dir' => $path ];
1406  if ( $this->isPrivate
1407  || $container === $this->zones['deleted']['container']
1408  || $container === $this->zones['temp']['container']
1409  ) {
1410  # Take all available measures to prevent web accessibility of new deleted
1411  # directories, in case the user has not configured offline storage
1412  $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1413  }
1414 
1415  return $this->newGood()->merge( $this->backend->prepare( $params ) );
1416  }
1417 
1424  public function cleanDir( $dir ) {
1425  $this->assertWritableRepo(); // fail out if read-only
1426 
1427  return $this->newGood()->merge(
1428  $this->backend->clean(
1429  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1430  )
1431  );
1432  }
1433 
1440  public function fileExists( $file ) {
1441  $result = $this->fileExistsBatch( [ $file ] );
1442 
1443  return $result[0];
1444  }
1445 
1452  public function fileExistsBatch( array $files ) {
1453  $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1454  $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1455 
1456  $result = [];
1457  foreach ( $files as $key => $file ) {
1459  $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1460  }
1461 
1462  return $result;
1463  }
1464 
1475  public function delete( $srcRel, $archiveRel ) {
1476  $this->assertWritableRepo(); // fail out if read-only
1477 
1478  return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1479  }
1480 
1498  public function deleteBatch( array $sourceDestPairs ) {
1499  $this->assertWritableRepo(); // fail out if read-only
1500 
1501  // Try creating directories
1502  $status = $this->initZones( [ 'public', 'deleted' ] );
1503  if ( !$status->isOK() ) {
1504  return $status;
1505  }
1506 
1507  $status = $this->newGood();
1508 
1509  $backend = $this->backend; // convenience
1510  $operations = [];
1511  // Validate filenames and create archive directories
1512  foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1513  if ( !$this->validateFilename( $srcRel ) ) {
1514  throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1515  } elseif ( !$this->validateFilename( $archiveRel ) ) {
1516  throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1517  }
1518 
1519  $publicRoot = $this->getZonePath( 'public' );
1520  $srcPath = "{$publicRoot}/$srcRel";
1521 
1522  $deletedRoot = $this->getZonePath( 'deleted' );
1523  $archivePath = "{$deletedRoot}/{$archiveRel}";
1524  $archiveDir = dirname( $archivePath ); // does not touch FS
1525 
1526  // Create destination directories
1527  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1528  return $this->newFatal( 'directorycreateerror', $archiveDir );
1529  }
1530 
1531  $operations[] = [
1532  'op' => 'move',
1533  'src' => $srcPath,
1534  'dst' => $archivePath,
1535  // We may have 2+ identical files being deleted,
1536  // all of which will map to the same destination file
1537  'overwriteSame' => true // also see T33792
1538  ];
1539  }
1540 
1541  // Move the files by execute the operations for each pair.
1542  // We're now committed to returning an OK result, which will
1543  // lead to the files being moved in the DB also.
1544  $opts = [ 'force' => true ];
1545  return $status->merge( $backend->doOperations( $operations, $opts ) );
1546  }
1547 
1554  public function cleanupDeletedBatch( array $storageKeys ) {
1555  $this->assertWritableRepo();
1556  }
1557 
1566  public function getDeletedHashPath( $key ) {
1567  if ( strlen( $key ) < 31 ) {
1568  throw new MWException( "Invalid storage key '$key'." );
1569  }
1570  $path = '';
1571  for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1572  $path .= $key[$i] . '/';
1573  }
1574 
1575  return $path;
1576  }
1577 
1586  protected function resolveToStoragePathIfVirtual( $path ) {
1587  if ( self::isVirtualUrl( $path ) ) {
1588  return $this->resolveVirtualUrl( $path );
1589  }
1590 
1591  return $path;
1592  }
1593 
1601  public function getLocalCopy( $virtualUrl ) {
1602  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1603 
1604  return $this->backend->getLocalCopy( [ 'src' => $path ] );
1605  }
1606 
1615  public function getLocalReference( $virtualUrl ) {
1616  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1617 
1618  return $this->backend->getLocalReference( [ 'src' => $path ] );
1619  }
1620 
1628  public function getFileProps( $virtualUrl ) {
1629  $fsFile = $this->getLocalReference( $virtualUrl );
1630  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1631  if ( $fsFile ) {
1632  $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1633  } else {
1634  $props = $mwProps->newPlaceholderProps();
1635  }
1636 
1637  return $props;
1638  }
1639 
1646  public function getFileTimestamp( $virtualUrl ) {
1647  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1648 
1649  return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1650  }
1651 
1658  public function getFileSize( $virtualUrl ) {
1659  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1660 
1661  return $this->backend->getFileSize( [ 'src' => $path ] );
1662  }
1663 
1670  public function getFileSha1( $virtualUrl ) {
1671  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1672 
1673  return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1674  }
1675 
1685  public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1686  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1687  $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1688 
1689  // T172851: HHVM does not flush the output properly, causing OOM
1690  ob_start( null, 1048576 );
1691  ob_implicit_flush( true );
1692 
1693  $status = $this->newGood()->merge( $this->backend->streamFile( $params ) );
1694 
1695  // T186565: Close the buffer, unless it has already been closed
1696  // in HTTPFileStreamer::resetOutputBuffers().
1697  if ( ob_get_status() ) {
1698  ob_end_flush();
1699  }
1700 
1701  return $status;
1702  }
1703 
1712  public function enumFiles( $callback ) {
1713  $this->enumFilesInStorage( $callback );
1714  }
1715 
1723  protected function enumFilesInStorage( $callback ) {
1724  $publicRoot = $this->getZonePath( 'public' );
1725  $numDirs = 1 << ( $this->hashLevels * 4 );
1726  // Use a priori assumptions about directory structure
1727  // to reduce the tree height of the scanning process.
1728  for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1729  $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1730  $path = $publicRoot;
1731  for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1732  $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1733  }
1734  $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1735  if ( $iterator === null ) {
1736  throw new MWException( __METHOD__ . ': could not get file listing for ' . $path );
1737  }
1738  foreach ( $iterator as $name ) {
1739  // Each item returned is a public file
1740  call_user_func( $callback, "{$path}/{$name}" );
1741  }
1742  }
1743  }
1744 
1751  public function validateFilename( $filename ) {
1752  if ( strval( $filename ) == '' ) {
1753  return false;
1754  }
1755 
1756  return FileBackend::isPathTraversalFree( $filename );
1757  }
1758 
1764  private function getErrorCleanupFunction() {
1765  switch ( $this->pathDisclosureProtection ) {
1766  case 'none':
1767  case 'simple': // b/c
1768  $callback = [ $this, 'passThrough' ];
1769  break;
1770  default: // 'paranoid'
1771  $callback = [ $this, 'paranoidClean' ];
1772  }
1773  return $callback;
1774  }
1775 
1782  public function paranoidClean( $param ) {
1783  return '[hidden]';
1784  }
1785 
1792  public function passThrough( $param ) {
1793  return $param;
1794  }
1795 
1803  public function newFatal( $message, ...$parameters ) {
1804  $status = Status::newFatal( $message, ...$parameters );
1805  $status->cleanCallback = $this->getErrorCleanupFunction();
1806 
1807  return $status;
1808  }
1809 
1816  public function newGood( $value = null ) {
1817  $status = Status::newGood( $value );
1818  $status->cleanCallback = $this->getErrorCleanupFunction();
1819 
1820  return $status;
1821  }
1822 
1831  public function checkRedirect( $title ) {
1832  return false;
1833  }
1834 
1842  public function invalidateImageRedirect( $title ) {
1843  }
1844 
1850  public function getDisplayName() {
1851  global $wgSitename;
1852 
1853  if ( $this->isLocal() ) {
1854  return $wgSitename;
1855  }
1856 
1857  // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1858  return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1859  }
1860 
1868  public function nameForThumb( $name ) {
1869  if ( strlen( $name ) > $this->abbrvThreshold ) {
1871  $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1872  }
1873 
1874  return $name;
1875  }
1876 
1882  public function isLocal() {
1883  return $this->getName() == 'local';
1884  }
1885 
1897  public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1898  return false;
1899  }
1900 
1912  public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1913  return $this->wanCache->makeKey(
1914  'filerepo-' . $kClassSuffix,
1915  $this->getName(),
1916  ...$components
1917  );
1918  }
1919 
1928  public function getTempRepo() {
1929  return new TempFileRepo( [
1930  'name' => "{$this->name}-temp",
1931  'backend' => $this->backend,
1932  'zones' => [
1933  'public' => [
1934  // Same place storeTemp() uses in the base repo, though
1935  // the path hashing is mismatched, which is annoying.
1936  'container' => $this->zones['temp']['container'],
1937  'directory' => $this->zones['temp']['directory']
1938  ],
1939  'thumb' => [
1940  'container' => $this->zones['temp']['container'],
1941  'directory' => $this->zones['temp']['directory'] == ''
1942  ? 'thumb'
1943  : $this->zones['temp']['directory'] . '/thumb'
1944  ],
1945  'transcoded' => [
1946  'container' => $this->zones['temp']['container'],
1947  'directory' => $this->zones['temp']['directory'] == ''
1948  ? 'transcoded'
1949  : $this->zones['temp']['directory'] . '/transcoded'
1950  ]
1951  ],
1952  'hashLevels' => $this->hashLevels, // performance
1953  'isPrivate' => true // all in temp zone
1954  ] );
1955  }
1956 
1963  public function getUploadStash( UserIdentity $user = null ) {
1964  return new UploadStash( $this, $user );
1965  }
1966 
1974  protected function assertWritableRepo() {
1975  }
1976 
1983  public function getInfo() {
1984  $ret = [
1985  'name' => $this->getName(),
1986  'displayname' => $this->getDisplayName(),
1987  'rootUrl' => $this->getZoneUrl( 'public' ),
1988  'local' => $this->isLocal(),
1989  ];
1990 
1991  $optionalSettings = [
1992  'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1993  'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1994  ];
1995  foreach ( $optionalSettings as $k ) {
1996  if ( isset( $this->$k ) ) {
1997  $ret[$k] = $this->$k;
1998  }
1999  }
2000 
2001  return $ret;
2002  }
2003 
2008  public function hasSha1Storage() {
2009  return $this->hasSha1Storage;
2010  }
2011 
2016  public function supportsSha1URLs() {
2017  return $this->supportsSha1URLs;
2018  }
2019 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1537
Page\PageIdentity
Interface for objects (potentially) representing an editable wiki page.
Definition: PageIdentity.php:64
FileBackend\doOperations
doOperations(array $ops, array $opts=[])
This is the main entry point into the backend for write operations.
Definition: FileBackend.php:467
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:261
FileRepo\$supportsSha1URLs
bool $supportsSha1URLs
Definition: FileRepo.php:65
FileRepo\initZones
initZones( $doZones=[])
Check if a single zone or list of zones is defined for usage.
Definition: FileRepo.php:272
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1206
FileRepo\$hasSha1Storage
bool $hasSha1Storage
Definition: FileRepo.php:62
FileRepo\passThrough
passThrough( $param)
Path disclosure protection function.
Definition: FileRepo.php:1792
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
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:631
FileRepo\getThumbScriptUrl
getThumbScriptUrl()
Get the URL of thumb.php.
Definition: FileRepo.php:671
FileRepo\newGood
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1816
FileRepo\getDescriptionRenderUrl
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition: FileRepo.php:865
FileBackend
Base class for all file backend classes (including multi-write backends).
Definition: FileBackend.php:98
FileRepo\$deletedHashLevels
int $deletedHashLevels
The number of directory levels for hash-based division of deleted files.
Definition: FileRepo.php:118
FileRepo\enumFilesInStorage
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
Definition: FileRepo.php:1723
FileRepo\$favicon
string $favicon
The URL of the repo's favicon, if any.
Definition: FileRepo.php:127
FileRepo\OVERWRITE_SAME
const OVERWRITE_SAME
Definition: FileRepo.php:48
FileRepo\$isPrivate
bool $isPrivate
Whether all zones should be private (e.g.
Definition: FileRepo.php:130
FileRepo\validateFilename
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Definition: FileRepo.php:1751
FileRepo\getRootDirectory
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition: FileRepo.php:739
FileRepo\$fileFactoryKey
callable false $fileFactoryKey
Override these in the base class.
Definition: FileRepo.php:137
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:199
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
FileRepo\OVERWRITE
const OVERWRITE
Definition: FileRepo.php:47
FileRepo\getVirtualUrl
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:302
FileRepo\makeUrl
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition: FileRepo.php:811
FileRepo\$oldFileFactory
callable false $oldFileFactory
Override these in the base class.
Definition: FileRepo.php:135
FileRepo\storeBatch
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:942
FileRepo\canTransformLocally
canTransformLocally()
Returns true if the repository can transform files locally.
Definition: FileRepo.php:708
FileRepo\$pathDisclosureProtection
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition: FileRepo.php:106
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:1685
FileRepo\$disableLocalTransform
bool $disableLocalTransform
Disable local image scaling.
Definition: FileRepo.php:149
FileRepo\getTempRepo
getTempRepo()
Get a temporary private FileRepo associated with this repo.
Definition: FileRepo.php:1928
FileRepo\resolveToStoragePathIfVirtual
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
Definition: FileRepo.php:1586
FileRepo\getInfo
getInfo()
Return information about the repository.
Definition: FileRepo.php:1983
UploadStash
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:55
FileRepo\$descriptionCacheExpiry
int $descriptionCacheExpiry
Definition: FileRepo.php:59
FileRepo\getName
getName()
Get the name of this repository, as specified by $info['name]' to the constructor.
Definition: FileRepo.php:800
FileRepo\$thumbUrl
string $thumbUrl
The base thumbnail URL.
Definition: FileRepo.php:112
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:292
FileRepo\quickImportBatch
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
Definition: FileRepo.php:1072
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1599
$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:772
FileRepo\getZoneUrl
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition: FileRepo.php:318
FileRepo\$oldFileFactoryKey
callable false $oldFileFactoryKey
Override these in the base class.
Definition: FileRepo.php:139
FileRepo\getZonePath
getZonePath( $zone)
Get the storage path corresponding to one of the zones.
Definition: FileRepo.php:400
FileRepo\getLocalReference
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
Definition: FileRepo.php:1615
FileRepo\getZoneLocation
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition: FileRepo.php:386
FileRepo\$backend
FileBackend $backend
Definition: FileRepo.php:68
$base
$base
Definition: generateLocalAutoload.php:11
FileRepo\getUploadStash
getUploadStash(UserIdentity $user=null)
Get an UploadStash associated with this repo.
Definition: FileRepo.php:1963
FileRepo\$wanCache
WANObjectCache $wanCache
Definition: FileRepo.php:152
FileRepo\$initialCapital
bool $initialCapital
Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE], determines whether filenames impl...
Definition: FileRepo.php:99
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
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:205
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:1263
FileRepo\getNameFromTitle
getNameFromTitle( $title)
Get the name of a file from its title.
Definition: FileRepo.php:718
FileRepo\getDescriptionStylesheetUrl
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition: FileRepo.php:890
FileRepo\fileExistsBatch
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1452
FileRepo
Base class for file repositories.
Definition: FileRepo.php:45
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:422
WANObjectCache\newEmpty
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Definition: WANObjectCache.php:408
FileRepo\freeTemp
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
Definition: FileRepo.php:1188
FileRepo\findFiles
findFiles(array $items, $flags=0)
Find many files at once.
Definition: FileRepo.php:542
FileRepo\quickPurge
quickPurge( $path)
Purge a file from the repo.
Definition: FileRepo.php:1116
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:2008
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:587
FileRepo\newFile
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition: FileRepo.php:424
MWException
MediaWiki exception.
Definition: MWException.php:29
FileRepo\enumFiles
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
Definition: FileRepo.php:1712
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1054
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1525
FileRepo\$thumbScriptUrl
string $thumbScriptUrl
URL of thumb.php.
Definition: FileRepo.php:74
FileRepo\findFilesByPrefix
findFilesByPrefix( $prefix, $limit)
Return an array of files where the name starts with $prefix.
Definition: FileRepo.php:662
FileRepo\$zones
array $zones
Map of zones to config.
Definition: FileRepo.php:71
FileRepo\paranoidClean
paranoidClean( $param)
Path disclosure protection function.
Definition: FileRepo.php:1782
FileRepo\invalidateImageRedirect
invalidateImageRedirect( $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
Definition: FileRepo.php:1842
MediaWiki
A helper class for throttling authentication attempts.
FileBackend\ATTR_UNICODE_PATHS
const ATTR_UNICODE_PATHS
Definition: FileBackend.php:136
FileRepo\getDescriptionUrl
getDescriptionUrl( $name)
Get the URL of an image description page.
Definition: FileRepo.php:831
FileRepo\getThumbProxySecret
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition: FileRepo.php:689
FileRepo\store
store( $srcPath, $dstZone, $dstRel, $flags=0)
Store a file to a given destination.
Definition: FileRepo.php:917
FileRepo\getSharedCacheKey
getSharedCacheKey( $kClassSuffix,... $components)
Get a global, repository-qualified, WAN cache key.
Definition: FileRepo.php:1897
MWTimestamp\getInstance
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:45
$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:1868
FileRepo\getThumbProxyUrl
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition: FileRepo.php:680
FileRepo\getLocalCopy
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1601
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:1011
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:894
FileRepo\fileExists
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1440
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1670
FileRepo\backendSupportsUnicodePaths
backendSupportsUnicodePaths()
Definition: FileRepo.php:348
FileRepo\newFatal
newFatal( $message,... $parameters)
Create a new fatal error.
Definition: FileRepo.php:1803
MediaWiki\Permissions\Authority
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
FileRepo\getLocalCacheKey
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
Definition: FileRepo.php:1912
FileRepo\getDisplayName
getDisplayName()
Get the human-readable name of the repo.
Definition: FileRepo.php:1850
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:459
FileRepo\SKIP_LOCKING
const SKIP_LOCKING
Definition: FileRepo.php:49
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
FileRepo\storeTemp
storeTemp( $originalName, $srcPath)
Pick a random name in the temp zone and store a file to it.
Definition: FileRepo.php:1168
FileRepo\publishBatch
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
Definition: FileRepo.php:1290
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:137
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:82
FileRepo\$scriptDirUrl
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition: FileRepo.php:89
FileRepo\$articleUrl
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition: FileRepo.php:92
FileRepo\getHashLevels
getHashLevels()
Get the number of hash directory levels.
Definition: FileRepo.php:791
FileRepo\initDirectory
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
Definition: FileRepo.php:1401
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:251
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
FileRepo\$fileFactory
callable $fileFactory
Override these in the base class.
Definition: FileRepo.php:133
FileRepo\quickPurgeBatch
quickPurgeBatch(array $paths)
Purge a batch of files from the repo.
Definition: FileRepo.php:1143
FileRepo\getFileSize
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1658
FileRepo\isLocal
isLocal()
Returns true if this the local file repository.
Definition: FileRepo.php:1882
FileRepo\$thumbProxySecret
string $thumbProxySecret
Secret key to pass as an X-Swift-Secret header to the proxied thumb service.
Definition: FileRepo.php:146
FileRepo\getHashPath
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:750
FileRepo\$name
string $name
Definition: FileRepo.php:159
FileRepo\getErrorCleanupFunction
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
Definition: FileRepo.php:1764
FileRepo\__construct
__construct(array $info=null)
Definition: FileRepo.php:167
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:642
FileRepo\getTempHashPath
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:761
FileRepo\$descBaseUrl
string $descBaseUrl
URL of image description pages, e.g.
Definition: FileRepo.php:84
$path
$path
Definition: NoLocalSettings.php:25
FileRepo\quickCleanDir
quickCleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1127
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:290
FileRepo\getFileTimestamp
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1646
FileRepo\concatenate
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
Definition: FileRepo.php:1210
FileRepo\deleteBatch
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
Definition: FileRepo.php:1498
FileRepo\resolveVirtualUrl
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:360
$source
$source
Definition: mwdoc-filter.php:34
FileBackend\isPathTraversalFree
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
Definition: FileBackend.php:1621
FileRepo\cleanDir
cleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1424
$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:46
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:70
FileRepo\checkRedirect
checkRedirect( $title)
Checks if there is a redirect named as $title.
Definition: FileRepo.php:1831
NS_FILE
const NS_FILE
Definition: Defines.php:70
FileRepo\getFileProps
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1628
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
FileRepo\$abbrvThreshold
int $abbrvThreshold
File names over this size will use the short form of thumbnail names.
Definition: FileRepo.php:124
FileRepo\$transformVia404
bool $transformVia404
Whether to skip media file transformation on parse and rely on a 404 handler instead.
Definition: FileRepo.php:79
FileRepo\supportsSha1URLs
supportsSha1URLs()
Returns whether or not repo supports having originals SHA-1s in the thumb URLs.
Definition: FileRepo.php:2016
FileRepo\$hashLevels
int $hashLevels
The number of directory levels for hash-based division of files.
Definition: FileRepo.php:115
FileRepo\getDeletedHashPath
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1566
FileRepo\assertWritableRepo
assertWritableRepo()
Throw an exception if this repo is read-only by design.
Definition: FileRepo.php:1974
FileRepo\NAME_AND_TIME_ONLY
const NAME_AND_TIME_ONLY
Definition: FileRepo.php:51
FileRepo\cleanupDeletedBatch
cleanupDeletedBatch(array $storageKeys)
Delete files in the deleted directory if they are not referenced in the filearchive table.
Definition: FileRepo.php:1554
FileRepo\$url
string false $url
Public zone URL.
Definition: FileRepo.php:109
FileRepo\canTransformVia404
canTransformVia404()
Returns true if the repository can transform files via a 404 handler.
Definition: FileRepo.php:698
FileRepo\$fetchDescription
bool $fetchDescription
Whether to fetch commons image description pages and display them on the local wiki.
Definition: FileRepo.php:56
FileRepo\$thumbProxyUrl
string $thumbProxyUrl
URL of where to proxy thumb.php requests to.
Definition: FileRepo.php:144