MediaWiki  master
FileRepo.php
Go to the documentation of this file.
1 <?php
11 
41 class FileRepo {
42  public const DELETE_SOURCE = 1;
43  public const OVERWRITE = 2;
44  public const OVERWRITE_SAME = 4;
45  public const SKIP_LOCKING = 8;
46 
47  public const NAME_AND_TIME_ONLY = 1;
48 
53 
56 
58  protected $hasSha1Storage = false;
59 
61  protected $supportsSha1URLs = false;
62 
64  protected $backend;
65 
67  protected $zones = [];
68 
70  protected $thumbScriptUrl;
71 
75  protected $transformVia404;
76 
80  protected $descBaseUrl;
81 
85  protected $scriptDirUrl;
86 
88  protected $articleUrl;
89 
95  protected $initialCapital;
96 
102  protected $pathDisclosureProtection = 'simple';
103 
105  protected $url;
106 
108  protected $thumbUrl;
109 
111  protected $hashLevels;
112 
115 
120  protected $abbrvThreshold;
121 
123  protected $favicon;
124 
126  protected $isPrivate;
127 
129  protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
131  protected $oldFileFactory = false;
133  protected $fileFactoryKey = false;
135  protected $oldFileFactoryKey = false;
136 
140  protected $thumbProxyUrl;
142  protected $thumbProxySecret;
143 
145  protected $wanCache;
146 
152  public $name;
153 
160  public function __construct( array $info = null ) {
161  // Verify required settings presence
162  if (
163  $info === null
164  || !array_key_exists( 'name', $info )
165  || !array_key_exists( 'backend', $info )
166  ) {
167  throw new MWException( __CLASS__ .
168  " requires an array of options having both 'name' and 'backend' keys.\n" );
169  }
170 
171  // Required settings
172  $this->name = $info['name'];
173  if ( $info['backend'] instanceof FileBackend ) {
174  $this->backend = $info['backend']; // useful for testing
175  } else {
176  $this->backend =
177  MediaWikiServices::getInstance()->getFileBackendGroup()->get( $info['backend'] );
178  }
179 
180  // Optional settings that can have no value
181  $optionalSettings = [
182  'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
183  'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
184  'favicon', 'thumbProxyUrl', 'thumbProxySecret',
185  ];
186  foreach ( $optionalSettings as $var ) {
187  if ( isset( $info[$var] ) ) {
188  $this->$var = $info[$var];
189  }
190  }
191 
192  // Optional settings that have a default
193  $localCapitalLinks =
194  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
195  $this->initialCapital = $info['initialCapital'] ?? $localCapitalLinks;
196  if ( $localCapitalLinks && !$this->initialCapital ) {
197  // If the local wiki's file namespace requires an initial capital, but a foreign file
198  // repo doesn't, complications will result. Linker code will want to auto-capitalize the
199  // first letter of links to files, but those links might actually point to files on
200  // foreign wikis with initial-lowercase names. This combination is not likely to be
201  // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
202  // to include a foreign file repo with initialCapital false, set your local file
203  // namespace to not be capitalized either.
204  throw new InvalidArgumentException(
205  'File repos with initial capital false are not allowed on wikis where the File ' .
206  'namespace has initial capital true' );
207  }
208 
209  $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
210  if ( isset( $info['thumbUrl'] ) ) {
211  $this->thumbUrl = $info['thumbUrl'];
212  } else {
213  $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
214  }
215  $this->hashLevels = $info['hashLevels'] ?? 2;
216  $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
217  $this->transformVia404 = !empty( $info['transformVia404'] );
218  $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
219  $this->isPrivate = !empty( $info['isPrivate'] );
220  // Give defaults for the basic zones...
221  $this->zones = $info['zones'] ?? [];
222  foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
223  if ( !isset( $this->zones[$zone]['container'] ) ) {
224  $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
225  }
226  if ( !isset( $this->zones[$zone]['directory'] ) ) {
227  $this->zones[$zone]['directory'] = '';
228  }
229  if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
230  $this->zones[$zone]['urlsByExt'] = [];
231  }
232  }
233 
234  $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
235 
236  $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
237  }
238 
244  public function getBackend() {
245  return $this->backend;
246  }
247 
254  public function getReadOnlyReason() {
255  return $this->backend->getReadOnlyReason();
256  }
257 
265  protected function initZones( $doZones = [] ) {
266  $status = $this->newGood();
267  foreach ( (array)$doZones as $zone ) {
268  $root = $this->getZonePath( $zone );
269  if ( $root === null ) {
270  throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
271  }
272  }
273 
274  return $status;
275  }
276 
283  public static function isVirtualUrl( $url ) {
284  return substr( $url, 0, 9 ) == 'mwrepo://';
285  }
286 
295  public function getVirtualUrl( $suffix = false ) {
296  $path = 'mwrepo://' . $this->name;
297  if ( $suffix !== false ) {
298  $path .= '/' . rawurlencode( $suffix );
299  }
300 
301  return $path;
302  }
303 
311  public function getZoneUrl( $zone, $ext = null ) {
312  if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
313  // standard public zones
314  if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
315  // custom URL for extension/zone
316  return $this->zones[$zone]['urlsByExt'][$ext];
317  } elseif ( isset( $this->zones[$zone]['url'] ) ) {
318  // custom URL for zone
319  return $this->zones[$zone]['url'];
320  }
321  }
322  switch ( $zone ) {
323  case 'public':
324  return $this->url;
325  case 'temp':
326  case 'deleted':
327  return false; // no public URL
328  case 'thumb':
329  return $this->thumbUrl;
330  case 'transcoded':
331  return "{$this->url}/transcoded";
332  default:
333  return false;
334  }
335  }
336 
340  public function backendSupportsUnicodePaths() {
341  return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
342  }
343 
352  public function resolveVirtualUrl( $url ) {
353  if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
354  throw new MWException( __METHOD__ . ': unknown protocol' );
355  }
356  $bits = explode( '/', substr( $url, 9 ), 3 );
357  if ( count( $bits ) != 3 ) {
358  throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
359  }
360  list( $repo, $zone, $rel ) = $bits;
361  if ( $repo !== $this->name ) {
362  throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
363  }
364  $base = $this->getZonePath( $zone );
365  if ( !$base ) {
366  throw new MWException( __METHOD__ . ": invalid zone: $zone" );
367  }
368 
369  return $base . '/' . rawurldecode( $rel );
370  }
371 
378  protected function getZoneLocation( $zone ) {
379  if ( !isset( $this->zones[$zone] ) ) {
380  return [ null, null ]; // bogus
381  }
382 
383  return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
384  }
385 
392  public function getZonePath( $zone ) {
393  list( $container, $base ) = $this->getZoneLocation( $zone );
394  if ( $container === null || $base === null ) {
395  return null;
396  }
397  $backendName = $this->backend->getName();
398  if ( $base != '' ) { // may not be set
399  $base = "/{$base}";
400  }
401 
402  return "mwstore://$backendName/{$container}{$base}";
403  }
404 
416  public function newFile( $title, $time = false ) {
418  if ( !$title ) {
419  return null;
420  }
421  if ( $time ) {
422  if ( $this->oldFileFactory ) {
423  return call_user_func( $this->oldFileFactory, $title, $this, $time );
424  } else {
425  return null;
426  }
427  } else {
428  return call_user_func( $this->fileFactory, $title, $this );
429  }
430  }
431 
450  public function findFile( $title, $options = [] ) {
451  if ( !empty( $options['private'] ) && !( $options['private'] instanceof User ) ) {
452  throw new InvalidArgumentException(
453  __METHOD__ . ' called with the `private` option set to something ' .
454  'other than a User object'
455  );
456  }
457 
459  if ( !$title ) {
460  return false;
461  }
462  if ( isset( $options['bypassCache'] ) ) {
463  $options['latest'] = $options['bypassCache']; // b/c
464  }
465  $time = $options['time'] ?? false;
466  $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
467  # First try the current version of the file to see if it precedes the timestamp
468  $img = $this->newFile( $title );
469  if ( !$img ) {
470  return false;
471  }
472  $img->load( $flags );
473  if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
474  return $img;
475  }
476  # Now try an old version of the file
477  if ( $time !== false ) {
478  $img = $this->newFile( $title, $time );
479  if ( $img ) {
480  $img->load( $flags );
481  if ( $img->exists() ) {
482  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
483  return $img; // always OK
484  } elseif (
485  // If its not empty, its a User object
486  !empty( $options['private'] ) &&
487  $img->userCan( File::DELETED_FILE, $options['private'] )
488  ) {
489  return $img;
490  }
491  }
492  }
493  }
494 
495  # Now try redirects
496  if ( !empty( $options['ignoreRedirect'] ) ) {
497  return false;
498  }
499  $redir = $this->checkRedirect( $title );
500  if ( $redir && $title->getNamespace() === NS_FILE ) {
501  $img = $this->newFile( $redir );
502  if ( !$img ) {
503  return false;
504  }
505  $img->load( $flags );
506  if ( $img->exists() ) {
507  $img->redirectedFrom( $title->getDBkey() );
508 
509  return $img;
510  }
511  }
512 
513  return false;
514  }
515 
533  public function findFiles( array $items, $flags = 0 ) {
534  $result = [];
535  foreach ( $items as $item ) {
536  if ( is_array( $item ) ) {
537  $title = $item['title'];
538  $options = $item;
539  unset( $options['title'] );
540 
541  if (
542  !empty( $options['private'] ) &&
543  !( $options['private'] instanceof User )
544  ) {
545  $options['private'] = RequestContext::getMain()->getUser();
546  }
547  } else {
548  $title = $item;
549  $options = [];
550  }
551  $file = $this->findFile( $title, $options );
552  if ( $file ) {
553  $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
554  if ( $flags & self::NAME_AND_TIME_ONLY ) {
555  $result[$searchName] = [
556  'title' => $file->getTitle()->getDBkey(),
557  'timestamp' => $file->getTimestamp()
558  ];
559  } else {
560  $result[$searchName] = $file;
561  }
562  }
563  }
564 
565  return $result;
566  }
567 
578  public function findFileFromKey( $sha1, $options = [] ) {
579  if ( !empty( $options['private'] ) && !( $options['private'] instanceof User ) ) {
580  throw new InvalidArgumentException(
581  __METHOD__ . ' called with the `private` option set to something ' .
582  'other than a User object'
583  );
584  }
585 
586  $time = $options['time'] ?? false;
587  # First try to find a matching current version of a file...
588  if ( !$this->fileFactoryKey ) {
589  return false; // find-by-sha1 not supported
590  }
591  $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
592  if ( $img && $img->exists() ) {
593  return $img;
594  }
595  # Now try to find a matching old version of a file...
596  if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
597  $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
598  if ( $img && $img->exists() ) {
599  if ( !$img->isDeleted( File::DELETED_FILE ) ) {
600  return $img; // always OK
601  } elseif (
602  // If its not empty, its a User object
603  !empty( $options['private'] ) &&
604  $img->userCan( File::DELETED_FILE, $options['private'] )
605  ) {
606  return $img;
607  }
608  }
609  }
610 
611  return false;
612  }
613 
622  public function findBySha1( $hash ) {
623  return [];
624  }
625 
633  public function findBySha1s( array $hashes ) {
634  $result = [];
635  foreach ( $hashes as $hash ) {
636  $files = $this->findBySha1( $hash );
637  if ( count( $files ) ) {
638  $result[$hash] = $files;
639  }
640  }
641 
642  return $result;
643  }
644 
653  public function findFilesByPrefix( $prefix, $limit ) {
654  return [];
655  }
656 
662  public function getThumbScriptUrl() {
663  return $this->thumbScriptUrl;
664  }
665 
671  public function getThumbProxyUrl() {
672  return $this->thumbProxyUrl;
673  }
674 
680  public function getThumbProxySecret() {
682  }
683 
689  public function canTransformVia404() {
690  return $this->transformVia404;
691  }
692 
699  public function getNameFromTitle( Title $title ) {
700  if (
701  $this->initialCapital !=
702  MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
703  ) {
704  $name = $title->getDBkey();
705  if ( $this->initialCapital ) {
706  $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
707  }
708  } else {
709  $name = $title->getDBkey();
710  }
711 
712  return $name;
713  }
714 
720  public function getRootDirectory() {
721  return $this->getZonePath( 'public' );
722  }
723 
731  public function getHashPath( $name ) {
732  return self::getHashPathForLevel( $name, $this->hashLevels );
733  }
734 
742  public function getTempHashPath( $suffix ) {
743  $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
744  $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
745  return self::getHashPathForLevel( $name, $this->hashLevels );
746  }
747 
753  protected static function getHashPathForLevel( $name, $levels ) {
754  if ( $levels == 0 ) {
755  return '';
756  } else {
757  $hash = md5( $name );
758  $path = '';
759  for ( $i = 1; $i <= $levels; $i++ ) {
760  $path .= substr( $hash, 0, $i ) . '/';
761  }
762 
763  return $path;
764  }
765  }
766 
772  public function getHashLevels() {
773  return $this->hashLevels;
774  }
775 
781  public function getName() {
782  return $this->name;
783  }
784 
792  public function makeUrl( $query = '', $entry = 'index' ) {
793  if ( isset( $this->scriptDirUrl ) ) {
794  return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
795  }
796 
797  return false;
798  }
799 
812  public function getDescriptionUrl( $name ) {
813  $encName = wfUrlencode( $name );
814  if ( $this->descBaseUrl !== null ) {
815  # "http://example.com/wiki/File:"
816  return $this->descBaseUrl . $encName;
817  }
818  if ( $this->articleUrl !== null ) {
819  # "http://example.com/wiki/$1"
820  # We use "Image:" as the canonical namespace for
821  # compatibility across all MediaWiki versions.
822  return str_replace( '$1',
823  "Image:$encName", $this->articleUrl );
824  }
825  if ( $this->scriptDirUrl !== null ) {
826  # "http://example.com/w"
827  # We use "Image:" as the canonical namespace for
828  # compatibility across all MediaWiki versions,
829  # and just sort of hope index.php is right. ;)
830  return $this->makeUrl( "title=Image:$encName" );
831  }
832 
833  return false;
834  }
835 
846  public function getDescriptionRenderUrl( $name, $lang = null ) {
847  $query = 'action=render';
848  if ( $lang !== null ) {
849  $query .= '&uselang=' . urlencode( $lang );
850  }
851  if ( isset( $this->scriptDirUrl ) ) {
852  return $this->makeUrl(
853  'title=' .
854  wfUrlencode( 'Image:' . $name ) .
855  "&$query" );
856  } else {
857  $descUrl = $this->getDescriptionUrl( $name );
858  if ( $descUrl ) {
859  return wfAppendQuery( $descUrl, $query );
860  } else {
861  return false;
862  }
863  }
864  }
865 
871  public function getDescriptionStylesheetUrl() {
872  if ( isset( $this->scriptDirUrl ) ) {
873  // Must match canonical query parameter order for optimum caching
874  // See Title::getCdnUrls
875  return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
876  }
877 
878  return false;
879  }
880 
898  public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
899  $this->assertWritableRepo(); // fail out if read-only
900 
901  $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
902  if ( $status->successCount == 0 ) {
903  $status->setOK( false );
904  }
905 
906  return $status;
907  }
908 
923  public function storeBatch( array $triplets, $flags = 0 ) {
924  $this->assertWritableRepo(); // fail out if read-only
925 
926  if ( $flags & self::DELETE_SOURCE ) {
927  throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
928  }
929 
930  $status = $this->newGood();
931  $backend = $this->backend; // convenience
932 
933  $operations = [];
934  // Validate each triplet and get the store operation...
935  foreach ( $triplets as $triplet ) {
936  list( $src, $dstZone, $dstRel ) = $triplet;
937  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
938  wfDebug( __METHOD__
939  . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
940  );
941  // Resolve source path
942  if ( $src instanceof FSFile ) {
943  $op = 'store';
944  } else {
945  $src = $this->resolveToStoragePathIfVirtual( $src );
946  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
947  }
948  // Resolve destination path
949  $root = $this->getZonePath( $dstZone );
950  if ( !$root ) {
951  throw new MWException( "Invalid zone: $dstZone" );
952  }
953  if ( !$this->validateFilename( $dstRel ) ) {
954  throw new MWException( 'Validation error in $dstRel' );
955  }
956  $dstPath = "$root/$dstRel";
957  $dstDir = dirname( $dstPath );
958  // Create destination directories for this triplet
959  if ( !$this->initDirectory( $dstDir )->isOK() ) {
960  return $this->newFatal( 'directorycreateerror', $dstDir );
961  }
962 
963  // Copy the source file to the destination
964  $operations[] = [
965  'op' => $op,
966  'src' => $src, // storage path (copy) or local file path (store)
967  'dst' => $dstPath,
968  'overwrite' => ( $flags & self::OVERWRITE ) ? true : false,
969  'overwriteSame' => ( $flags & self::OVERWRITE_SAME ) ? true : false,
970  ];
971  }
972 
973  // Execute the store operation for each triplet
974  $opts = [ 'force' => true ];
975  if ( $flags & self::SKIP_LOCKING ) {
976  $opts['nonLocking'] = true;
977  }
978  $status->merge( $backend->doOperations( $operations, $opts ) );
979 
980  return $status;
981  }
982 
993  public function cleanupBatch( array $files, $flags = 0 ) {
994  $this->assertWritableRepo(); // fail out if read-only
995 
996  $status = $this->newGood();
997 
998  $operations = [];
999  foreach ( $files as $path ) {
1000  if ( is_array( $path ) ) {
1001  // This is a pair, extract it
1002  list( $zone, $rel ) = $path;
1003  $path = $this->getZonePath( $zone ) . "/$rel";
1004  } else {
1005  // Resolve source to a storage path if virtual
1006  $path = $this->resolveToStoragePathIfVirtual( $path );
1007  }
1008  $operations[] = [ 'op' => 'delete', 'src' => $path ];
1009  }
1010  // Actually delete files from storage...
1011  $opts = [ 'force' => true ];
1012  if ( $flags & self::SKIP_LOCKING ) {
1013  $opts['nonLocking'] = true;
1014  }
1015  $status->merge( $this->backend->doOperations( $operations, $opts ) );
1016 
1017  return $status;
1018  }
1019 
1037  final public function quickImport( $src, $dst, $options = null ) {
1038  return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1039  }
1040 
1055  public function quickImportBatch( array $triples ) {
1056  $status = $this->newGood();
1057  $operations = [];
1058  foreach ( $triples as $triple ) {
1059  list( $src, $dst ) = $triple;
1060  if ( $src instanceof FSFile ) {
1061  $op = 'store';
1062  } else {
1063  $src = $this->resolveToStoragePathIfVirtual( $src );
1064  $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1065  }
1066  $dst = $this->resolveToStoragePathIfVirtual( $dst );
1067 
1068  if ( !isset( $triple[2] ) ) {
1069  $headers = [];
1070  } elseif ( is_string( $triple[2] ) ) {
1071  // back-compat
1072  $headers = [ 'Content-Disposition' => $triple[2] ];
1073  } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1074  $headers = $triple[2]['headers'];
1075  } else {
1076  $headers = [];
1077  }
1078 
1079  $operations[] = [
1080  'op' => $op,
1081  'src' => $src, // storage path (copy) or local path/FSFile (store)
1082  'dst' => $dst,
1083  'headers' => $headers
1084  ];
1085  $status->merge( $this->initDirectory( dirname( $dst ) ) );
1086  }
1087  $status->merge( $this->backend->doQuickOperations( $operations ) );
1088 
1089  return $status;
1090  }
1091 
1100  final public function quickPurge( $path ) {
1101  return $this->quickPurgeBatch( [ $path ] );
1102  }
1103 
1111  public function quickCleanDir( $dir ) {
1112  $status = $this->newGood();
1113  $status->merge( $this->backend->clean(
1114  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1115 
1116  return $status;
1117  }
1118 
1127  public function quickPurgeBatch( array $paths ) {
1128  $status = $this->newGood();
1129  $operations = [];
1130  foreach ( $paths as $path ) {
1131  $operations[] = [
1132  'op' => 'delete',
1133  'src' => $this->resolveToStoragePathIfVirtual( $path ),
1134  'ignoreMissingSource' => true
1135  ];
1136  }
1137  $status->merge( $this->backend->doQuickOperations( $operations ) );
1138 
1139  return $status;
1140  }
1141 
1152  public function storeTemp( $originalName, $srcPath ) {
1153  $this->assertWritableRepo(); // fail out if read-only
1154 
1155  $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1156  $hashPath = $this->getHashPath( $originalName );
1157  $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1158  $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1159 
1160  $result = $this->quickImport( $srcPath, $virtualUrl );
1161  $result->value = $virtualUrl;
1162 
1163  return $result;
1164  }
1165 
1172  public function freeTemp( $virtualUrl ) {
1173  $this->assertWritableRepo(); // fail out if read-only
1174 
1175  $temp = $this->getVirtualUrl( 'temp' );
1176  if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1177  wfDebug( __METHOD__ . ": Invalid temp virtual URL" );
1178 
1179  return false;
1180  }
1181 
1182  return $this->quickPurge( $virtualUrl )->isOK();
1183  }
1184 
1194  public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1195  $this->assertWritableRepo(); // fail out if read-only
1196 
1197  $status = $this->newGood();
1198 
1199  $sources = [];
1200  foreach ( $srcPaths as $srcPath ) {
1201  // Resolve source to a storage path if virtual
1202  $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1203  $sources[] = $source; // chunk to merge
1204  }
1205 
1206  // Concatenate the chunks into one FS file
1207  $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1208  $status->merge( $this->backend->concatenate( $params ) );
1209  if ( !$status->isOK() ) {
1210  return $status;
1211  }
1212 
1213  // Delete the sources if required
1214  if ( $flags & self::DELETE_SOURCE ) {
1215  $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1216  }
1217 
1218  // Make sure status is OK, despite any quickPurgeBatch() fatals
1219  $status->setResult( true );
1220 
1221  return $status;
1222  }
1223 
1247  public function publish(
1248  $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1249  ) {
1250  $this->assertWritableRepo(); // fail out if read-only
1251 
1252  $status = $this->publishBatch(
1253  [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1254  if ( $status->successCount == 0 ) {
1255  $status->setOK( false );
1256  }
1257  $status->value = $status->value[0] ?? false;
1258 
1259  return $status;
1260  }
1261 
1274  public function publishBatch( array $ntuples, $flags = 0 ) {
1275  $this->assertWritableRepo(); // fail out if read-only
1276 
1277  $backend = $this->backend; // convenience
1278  // Try creating directories
1279  $status = $this->initZones( 'public' );
1280  if ( !$status->isOK() ) {
1281  return $status;
1282  }
1283 
1284  $status = $this->newGood( [] );
1285 
1286  $operations = [];
1287  $sourceFSFilesToDelete = []; // cleanup for disk source files
1288  // Validate each triplet and get the store operation...
1289  foreach ( $ntuples as $ntuple ) {
1290  list( $src, $dstRel, $archiveRel ) = $ntuple;
1291  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1292 
1293  $options = $ntuple[3] ?? [];
1294  // Resolve source to a storage path if virtual
1295  $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1296  if ( !$this->validateFilename( $dstRel ) ) {
1297  throw new MWException( 'Validation error in $dstRel' );
1298  }
1299  if ( !$this->validateFilename( $archiveRel ) ) {
1300  throw new MWException( 'Validation error in $archiveRel' );
1301  }
1302 
1303  $publicRoot = $this->getZonePath( 'public' );
1304  $dstPath = "$publicRoot/$dstRel";
1305  $archivePath = "$publicRoot/$archiveRel";
1306 
1307  $dstDir = dirname( $dstPath );
1308  $archiveDir = dirname( $archivePath );
1309  // Abort immediately on directory creation errors since they're likely to be repetitive
1310  if ( !$this->initDirectory( $dstDir )->isOK() ) {
1311  return $this->newFatal( 'directorycreateerror', $dstDir );
1312  }
1313  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1314  return $this->newFatal( 'directorycreateerror', $archiveDir );
1315  }
1316 
1317  // Set any desired headers to be use in GET/HEAD responses
1318  $headers = $options['headers'] ?? [];
1319 
1320  // Archive destination file if it exists.
1321  // This will check if the archive file also exists and fail if does.
1322  // This is a sanity check to avoid data loss. On Windows and Linux,
1323  // copy() will overwrite, so the existence check is vulnerable to
1324  // race conditions unless a functioning LockManager is used.
1325  // LocalFile also uses SELECT FOR UPDATE for synchronization.
1326  $operations[] = [
1327  'op' => 'copy',
1328  'src' => $dstPath,
1329  'dst' => $archivePath,
1330  'ignoreMissingSource' => true
1331  ];
1332 
1333  // Copy (or move) the source file to the destination
1334  if ( FileBackend::isStoragePath( $srcPath ) ) {
1335  $operations[] = [
1336  'op' => ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy',
1337  'src' => $srcPath,
1338  'dst' => $dstPath,
1339  'overwrite' => true, // replace current
1340  'headers' => $headers
1341  ];
1342  } else {
1343  $operations[] = [
1344  'op' => 'store',
1345  'src' => $src, // storage path (copy) or local path/FSFile (store)
1346  'dst' => $dstPath,
1347  'overwrite' => true, // replace current
1348  'headers' => $headers
1349  ];
1350  if ( $flags & self::DELETE_SOURCE ) {
1351  $sourceFSFilesToDelete[] = $srcPath;
1352  }
1353  }
1354  }
1355 
1356  // Execute the operations for each triplet
1357  $status->merge( $backend->doOperations( $operations ) );
1358  // Find out which files were archived...
1359  foreach ( $ntuples as $i => $ntuple ) {
1360  list( , , $archiveRel ) = $ntuple;
1361  $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1362  if ( $this->fileExists( $archivePath ) ) {
1363  $status->value[$i] = 'archived';
1364  } else {
1365  $status->value[$i] = 'new';
1366  }
1367  }
1368  // Cleanup for disk source files...
1369  foreach ( $sourceFSFilesToDelete as $file ) {
1370  Wikimedia\suppressWarnings();
1371  unlink( $file ); // FS cleanup
1372  Wikimedia\restoreWarnings();
1373  }
1374 
1375  return $status;
1376  }
1377 
1385  protected function initDirectory( $dir ) {
1386  $path = $this->resolveToStoragePathIfVirtual( $dir );
1387  list( , $container, ) = FileBackend::splitStoragePath( $path );
1388 
1389  $params = [ 'dir' => $path ];
1390  if ( $this->isPrivate
1391  || $container === $this->zones['deleted']['container']
1392  || $container === $this->zones['temp']['container']
1393  ) {
1394  # Take all available measures to prevent web accessibility of new deleted
1395  # directories, in case the user has not configured offline storage
1396  $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1397  }
1398 
1399  $status = $this->newGood();
1400  $status->merge( $this->backend->prepare( $params ) );
1401 
1402  return $status;
1403  }
1404 
1411  public function cleanDir( $dir ) {
1412  $this->assertWritableRepo(); // fail out if read-only
1413 
1414  $status = $this->newGood();
1415  $status->merge( $this->backend->clean(
1416  [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1417 
1418  return $status;
1419  }
1420 
1427  public function fileExists( $file ) {
1428  $result = $this->fileExistsBatch( [ $file ] );
1429 
1430  return $result[0];
1431  }
1432 
1439  public function fileExistsBatch( array $files ) {
1440  $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1441  $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1442 
1443  $result = [];
1444  foreach ( $files as $key => $file ) {
1446  $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1447  }
1448 
1449  return $result;
1450  }
1451 
1462  public function delete( $srcRel, $archiveRel ) {
1463  $this->assertWritableRepo(); // fail out if read-only
1464 
1465  return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1466  }
1467 
1485  public function deleteBatch( array $sourceDestPairs ) {
1486  $this->assertWritableRepo(); // fail out if read-only
1487 
1488  // Try creating directories
1489  $status = $this->initZones( [ 'public', 'deleted' ] );
1490  if ( !$status->isOK() ) {
1491  return $status;
1492  }
1493 
1494  $status = $this->newGood();
1495 
1496  $backend = $this->backend; // convenience
1497  $operations = [];
1498  // Validate filenames and create archive directories
1499  foreach ( $sourceDestPairs as $pair ) {
1500  list( $srcRel, $archiveRel ) = $pair;
1501  if ( !$this->validateFilename( $srcRel ) ) {
1502  throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1503  } elseif ( !$this->validateFilename( $archiveRel ) ) {
1504  throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1505  }
1506 
1507  $publicRoot = $this->getZonePath( 'public' );
1508  $srcPath = "{$publicRoot}/$srcRel";
1509 
1510  $deletedRoot = $this->getZonePath( 'deleted' );
1511  $archivePath = "{$deletedRoot}/{$archiveRel}";
1512  $archiveDir = dirname( $archivePath ); // does not touch FS
1513 
1514  // Create destination directories
1515  if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1516  return $this->newFatal( 'directorycreateerror', $archiveDir );
1517  }
1518 
1519  $operations[] = [
1520  'op' => 'move',
1521  'src' => $srcPath,
1522  'dst' => $archivePath,
1523  // We may have 2+ identical files being deleted,
1524  // all of which will map to the same destination file
1525  'overwriteSame' => true // also see T33792
1526  ];
1527  }
1528 
1529  // Move the files by execute the operations for each pair.
1530  // We're now committed to returning an OK result, which will
1531  // lead to the files being moved in the DB also.
1532  $opts = [ 'force' => true ];
1533  $status->merge( $backend->doOperations( $operations, $opts ) );
1534 
1535  return $status;
1536  }
1537 
1544  public function cleanupDeletedBatch( array $storageKeys ) {
1545  $this->assertWritableRepo();
1546  }
1547 
1556  public function getDeletedHashPath( $key ) {
1557  if ( strlen( $key ) < 31 ) {
1558  throw new MWException( "Invalid storage key '$key'." );
1559  }
1560  $path = '';
1561  for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1562  $path .= $key[$i] . '/';
1563  }
1564 
1565  return $path;
1566  }
1567 
1576  protected function resolveToStoragePathIfVirtual( $path ) {
1577  if ( self::isVirtualUrl( $path ) ) {
1578  return $this->resolveVirtualUrl( $path );
1579  }
1580 
1581  return $path;
1582  }
1583 
1591  public function getLocalCopy( $virtualUrl ) {
1592  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1593 
1594  return $this->backend->getLocalCopy( [ 'src' => $path ] );
1595  }
1596 
1605  public function getLocalReference( $virtualUrl ) {
1606  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1607 
1608  return $this->backend->getLocalReference( [ 'src' => $path ] );
1609  }
1610 
1618  public function getFileProps( $virtualUrl ) {
1619  $fsFile = $this->getLocalReference( $virtualUrl );
1620  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1621  if ( $fsFile ) {
1622  $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1623  } else {
1624  $props = $mwProps->newPlaceholderProps();
1625  }
1626 
1627  return $props;
1628  }
1629 
1636  public function getFileTimestamp( $virtualUrl ) {
1637  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1638 
1639  return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1640  }
1641 
1648  public function getFileSize( $virtualUrl ) {
1649  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1650 
1651  return $this->backend->getFileSize( [ 'src' => $path ] );
1652  }
1653 
1660  public function getFileSha1( $virtualUrl ) {
1661  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1662 
1663  return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1664  }
1665 
1675  public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1676  $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1677  $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1678 
1679  // T172851: HHVM does not flush the output properly, causing OOM
1680  ob_start( null, 1048576 );
1681  ob_implicit_flush( true );
1682 
1683  $status = $this->newGood();
1684  $status->merge( $this->backend->streamFile( $params ) );
1685 
1686  // T186565: Close the buffer, unless it has already been closed
1687  // in HTTPFileStreamer::resetOutputBuffers().
1688  if ( ob_get_status() ) {
1689  ob_end_flush();
1690  }
1691 
1692  return $status;
1693  }
1694 
1703  public function enumFiles( $callback ) {
1704  $this->enumFilesInStorage( $callback );
1705  }
1706 
1714  protected function enumFilesInStorage( $callback ) {
1715  $publicRoot = $this->getZonePath( 'public' );
1716  $numDirs = 1 << ( $this->hashLevels * 4 );
1717  // Use a priori assumptions about directory structure
1718  // to reduce the tree height of the scanning process.
1719  for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1720  $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1721  $path = $publicRoot;
1722  for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1723  $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1724  }
1725  $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1726  if ( $iterator === null ) {
1727  throw new MWException( __METHOD__ . ': could not get file listing for ' . $path );
1728  }
1729  foreach ( $iterator as $name ) {
1730  // Each item returned is a public file
1731  call_user_func( $callback, "{$path}/{$name}" );
1732  }
1733  }
1734  }
1735 
1742  public function validateFilename( $filename ) {
1743  if ( strval( $filename ) == '' ) {
1744  return false;
1745  }
1746 
1747  return FileBackend::isPathTraversalFree( $filename );
1748  }
1749 
1755  private function getErrorCleanupFunction() {
1756  switch ( $this->pathDisclosureProtection ) {
1757  case 'none':
1758  case 'simple': // b/c
1759  $callback = [ $this, 'passThrough' ];
1760  break;
1761  default: // 'paranoid'
1762  $callback = [ $this, 'paranoidClean' ];
1763  }
1764  return $callback;
1765  }
1766 
1773  public function paranoidClean( $param ) {
1774  return '[hidden]';
1775  }
1776 
1783  public function passThrough( $param ) {
1784  return $param;
1785  }
1786 
1794  public function newFatal( $message, ...$parameters ) {
1795  $status = Status::newFatal( $message, ...$parameters );
1796  $status->cleanCallback = $this->getErrorCleanupFunction();
1797 
1798  return $status;
1799  }
1800 
1807  public function newGood( $value = null ) {
1808  $status = Status::newGood( $value );
1809  $status->cleanCallback = $this->getErrorCleanupFunction();
1810 
1811  return $status;
1812  }
1813 
1822  public function checkRedirect( Title $title ) {
1823  return false;
1824  }
1825 
1833  public function invalidateImageRedirect( Title $title ) {
1834  }
1835 
1841  public function getDisplayName() {
1842  global $wgSitename;
1843 
1844  if ( $this->isLocal() ) {
1845  return $wgSitename;
1846  }
1847 
1848  // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1849  return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1850  }
1851 
1859  public function nameForThumb( $name ) {
1860  if ( strlen( $name ) > $this->abbrvThreshold ) {
1862  $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1863  }
1864 
1865  return $name;
1866  }
1867 
1873  public function isLocal() {
1874  return $this->getName() == 'local';
1875  }
1876 
1886  public function getSharedCacheKey( ...$args ) {
1887  return false;
1888  }
1889 
1898  public function getLocalCacheKey( ...$args ) {
1899  array_unshift( $args, 'filerepo', $this->getName() );
1900 
1901  return $this->wanCache->makeKey( ...$args );
1902  }
1903 
1912  public function getTempRepo() {
1913  return new TempFileRepo( [
1914  'name' => "{$this->name}-temp",
1915  'backend' => $this->backend,
1916  'zones' => [
1917  'public' => [
1918  // Same place storeTemp() uses in the base repo, though
1919  // the path hashing is mismatched, which is annoying.
1920  'container' => $this->zones['temp']['container'],
1921  'directory' => $this->zones['temp']['directory']
1922  ],
1923  'thumb' => [
1924  'container' => $this->zones['temp']['container'],
1925  'directory' => $this->zones['temp']['directory'] == ''
1926  ? 'thumb'
1927  : $this->zones['temp']['directory'] . '/thumb'
1928  ],
1929  'transcoded' => [
1930  'container' => $this->zones['temp']['container'],
1931  'directory' => $this->zones['temp']['directory'] == ''
1932  ? 'transcoded'
1933  : $this->zones['temp']['directory'] . '/transcoded'
1934  ]
1935  ],
1936  'hashLevels' => $this->hashLevels, // performance
1937  'isPrivate' => true // all in temp zone
1938  ] );
1939  }
1940 
1947  public function getUploadStash( User $user = null ) {
1948  return new UploadStash( $this, $user );
1949  }
1950 
1958  protected function assertWritableRepo() {
1959  }
1960 
1967  public function getInfo() {
1968  $ret = [
1969  'name' => $this->getName(),
1970  'displayname' => $this->getDisplayName(),
1971  'rootUrl' => $this->getZoneUrl( 'public' ),
1972  'local' => $this->isLocal(),
1973  ];
1974 
1975  $optionalSettings = [
1976  'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1977  'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1978  ];
1979  foreach ( $optionalSettings as $k ) {
1980  if ( isset( $this->$k ) ) {
1981  $ret[$k] = $this->$k;
1982  }
1983  }
1984 
1985  return $ret;
1986  }
1987 
1992  public function hasSha1Storage() {
1993  return $this->hasSha1Storage;
1994  }
1995 
2000  public function supportsSha1URLs() {
2001  return $this->supportsSha1URLs;
2002  }
2003 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1540
FileBackend\doOperations
doOperations(array $ops, array $opts=[])
This is the main entry point into the backend for write operations.
Definition: FileBackend.php:468
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:254
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:265
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1243
FileRepo\$hasSha1Storage
bool $hasSha1Storage
Definition: FileRepo.php:58
FileRepo\passThrough
passThrough( $param)
Path disclosure protection function.
Definition: FileRepo.php:1783
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:622
FileRepo\getThumbScriptUrl
getThumbScriptUrl()
Get the URL of thumb.php.
Definition: FileRepo.php:662
FileRepo\newGood
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1807
FileRepo\getDescriptionRenderUrl
getDescriptionRenderUrl( $name, $lang=null)
Get the URL of the content-only fragment of the description page.
Definition: FileRepo.php:846
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:114
FileRepo\enumFilesInStorage
enumFilesInStorage( $callback)
Call a callback function for every public file in the repository.
Definition: FileRepo.php:1714
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:1742
FileRepo\getRootDirectory
getRootDirectory()
Get the public zone root storage directory of the repository.
Definition: FileRepo.php:720
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:162
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
FileRepo\OVERWRITE
const OVERWRITE
Definition: FileRepo.php:43
FileRepo\getVirtualUrl
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:295
FileRepo\makeUrl
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition: FileRepo.php:792
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:923
FileRepo\$pathDisclosureProtection
string $pathDisclosureProtection
May be 'paranoid' to remove all parameters from error messages, 'none' to leave the paths in unchange...
Definition: FileRepo.php:102
true
return true
Definition: router.php:90
FileRepo\streamFileWithStatus
streamFileWithStatus( $virtualUrl, $headers=[], $optHeaders=[])
Attempt to stream a file with the given virtual URL/storage path.
Definition: FileRepo.php:1675
FileRepo\getTempRepo
getTempRepo()
Get a temporary private FileRepo associated with this repo.
Definition: FileRepo.php:1912
FileRepo\resolveToStoragePathIfVirtual
resolveToStoragePathIfVirtual( $path)
If a path is a virtual URL, resolve it to a storage path.
Definition: FileRepo.php:1576
FileRepo\getInfo
getInfo()
Return information about the repository.
Definition: FileRepo.php:1967
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:781
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:308
FileRepo\quickImportBatch
quickImportBatch(array $triples)
Import a batch of files from the local file system into the repo.
Definition: FileRepo.php:1055
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1602
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
FileRepo\getHashPathForLevel
static getHashPathForLevel( $name, $levels)
Definition: FileRepo.php:753
FileRepo\getZoneUrl
getZoneUrl( $zone, $ext=null)
Get the URL corresponding to one of the four basic zones.
Definition: FileRepo.php:311
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:392
FileRepo\getLocalReference
getLocalReference( $virtualUrl)
Get a local FS file with a given virtual URL/storage path.
Definition: FileRepo.php:1605
FileRepo\getZoneLocation
getZoneLocation( $zone)
The storage container and base path of a zone.
Definition: FileRepo.php:378
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:199
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:1247
FileRepo\getDescriptionStylesheetUrl
getDescriptionStylesheetUrl()
Get the URL of the stylesheet to apply to description pages.
Definition: FileRepo.php:871
FileRepo\fileExistsBatch
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1439
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:438
WANObjectCache\newEmpty
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Definition: WANObjectCache.php:348
FileRepo\freeTemp
freeTemp( $virtualUrl)
Remove a temporary file or mark it for garbage collection.
Definition: FileRepo.php:1172
FileRepo\findFiles
findFiles(array $items, $flags=0)
Find many files at once.
Definition: FileRepo.php:533
FileRepo\quickPurge
quickPurge( $path)
Purge a file from the repo.
Definition: FileRepo.php:1100
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1992
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:578
FileRepo\newFile
newFile( $title, $time=false)
Create a new File object from the local repository.
Definition: FileRepo.php:416
MWException
MediaWiki exception.
Definition: MWException.php:29
FileRepo\getLocalCacheKey
getLocalCacheKey(... $args)
Get a key for this repo in the local cache domain.
Definition: FileRepo.php:1898
FileRepo\enumFiles
enumFiles( $callback)
Call a callback function for every public regular file in the repository.
Definition: FileRepo.php:1703
FileRepo\checkRedirect
checkRedirect(Title $title)
Checks if there is a redirect named as $title.
Definition: FileRepo.php:1822
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1037
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1528
FileRepo\getUploadStash
getUploadStash(User $user=null)
Get an UploadStash associated with this repo.
Definition: FileRepo.php:1947
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:653
FileRepo\$zones
array $zones
Map of zones to config.
Definition: FileRepo.php:67
FileRepo\paranoidClean
paranoidClean( $param)
Path disclosure protection function.
Definition: FileRepo.php:1773
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:812
FileRepo\getThumbProxySecret
getThumbProxySecret()
Get the secret key for the proxied thumb service.
Definition: FileRepo.php:680
$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:898
MWTimestamp\getInstance
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:41
$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:1859
FileRepo\invalidateImageRedirect
invalidateImageRedirect(Title $title)
Invalidates image redirect cache related to that image Doesn't do anything for repositories that don'...
Definition: FileRepo.php:1833
FileRepo\getThumbProxyUrl
getThumbProxyUrl()
Get the URL thumb.php requests are being proxied to.
Definition: FileRepo.php:671
FileRepo\getLocalCopy
getLocalCopy( $virtualUrl)
Get a local FS copy of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1591
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:993
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:910
FileRepo\fileExists
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1427
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1660
FileRepo\backendSupportsUnicodePaths
backendSupportsUnicodePaths()
Definition: FileRepo.php:340
FileRepo\newFatal
newFatal( $message,... $parameters)
Create a new fatal error.
Definition: FileRepo.php:1794
FileRepo\getNameFromTitle
getNameFromTitle(Title $title)
Get the name of a file from its title object.
Definition: FileRepo.php:699
FileRepo\getDisplayName
getDisplayName()
Get the human-readable name of the repo.
Definition: FileRepo.php:1841
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:450
FileRepo\SKIP_LOCKING
const SKIP_LOCKING
Definition: FileRepo.php:45
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:1152
FileRepo\publishBatch
publishBatch(array $ntuples, $flags=0)
Publish a batch of files.
Definition: FileRepo.php:1274
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:125
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:80
FileRepo\$scriptDirUrl
string $scriptDirUrl
URL of the MediaWiki installation, equivalent to $wgScriptPath, e.g.
Definition: FileRepo.php:85
FileRepo\$articleUrl
string $articleUrl
Equivalent to $wgArticlePath, e.g.
Definition: FileRepo.php:88
FileRepo\getHashLevels
getHashLevels()
Get the number of hash directory levels.
Definition: FileRepo.php:772
FileRepo\initDirectory
initDirectory( $dir)
Creates a directory with the appropriate zone permissions.
Definition: FileRepo.php:1385
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:244
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
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:1127
FileRepo\getFileSize
getFileSize( $virtualUrl)
Get the size of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1648
FileRepo\isLocal
isLocal()
Returns true if this the local file repository.
Definition: FileRepo.php:1873
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:731
FileRepo\$name
string $name
Definition: FileRepo.php:152
FileRepo\getErrorCleanupFunction
getErrorCleanupFunction()
Get a callback function to use for cleaning error message parameters.
Definition: FileRepo.php:1755
Title
Represents a title within MediaWiki.
Definition: Title.php:41
FileRepo\__construct
__construct(array $info=null)
Definition: FileRepo.php:160
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:633
FileRepo\getSharedCacheKey
getSharedCacheKey(... $args)
Get a key on the primary cache for this repository.
Definition: FileRepo.php:1886
FileRepo\getTempHashPath
getTempHashPath( $suffix)
Get a relative path including trailing slash, e.g.
Definition: FileRepo.php:742
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:1111
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:283
FileRepo\getFileTimestamp
getFileTimestamp( $virtualUrl)
Get the timestamp of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1636
FileRepo\concatenate
concatenate(array $srcPaths, $dstPath, $flags=0)
Concatenate a list of temporary files into a target file location.
Definition: FileRepo.php:1194
FileRepo\deleteBatch
deleteBatch(array $sourceDestPairs)
Move a group of files to the deletion archive.
Definition: FileRepo.php:1485
FileRepo\resolveVirtualUrl
resolveVirtualUrl( $url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:352
$source
$source
Definition: mwdoc-filter.php:34
FileBackend\isPathTraversalFree
static isPathTraversalFree( $path)
Check if a relative path has no directory traversals.
Definition: FileBackend.php:1624
FileRepo\cleanDir
cleanDir( $dir)
Deletes a directory if empty.
Definition: FileRepo.php:1411
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
$hashes
$hashes
Definition: testCompression.php:71
FileRepo\DELETE_SOURCE
const DELETE_SOURCE
Definition: FileRepo.php:42
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:67
FileRepo\getFileProps
getFileProps( $virtualUrl)
Get properties of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1618
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:56
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:2000
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:1556
FileRepo\assertWritableRepo
assertWritableRepo()
Throw an exception if this repo is read-only by design.
Definition: FileRepo.php:1958
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:1544
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:689
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