3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
10 use MediaWiki\MediaWikiServices
;
13 * Base code for file repositories.
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License along
26 * with this program; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 * http://www.gnu.org/copyleft/gpl.html
35 * Base class for file repositories
40 const DELETE_SOURCE
= 1;
42 const OVERWRITE_SAME
= 4;
43 const SKIP_LOCKING
= 8;
45 const NAME_AND_TIME_ONLY
= 1;
47 /** @var bool Whether to fetch commons image description pages and display
48 * them on the local wiki */
49 public $fetchDescription;
52 public $descriptionCacheExpiry;
55 protected $hasSha1Storage = false;
58 protected $supportsSha1URLs = false;
60 /** @var FileBackend */
63 /** @var array Map of zones to config */
64 protected $zones = [];
66 /** @var string URL of thumb.php */
67 protected $thumbScriptUrl;
69 /** @var bool Whether to skip media file transformation on parse and rely
70 * on a 404 handler instead. */
71 protected $transformVia404;
73 /** @var string URL of image description pages, e.g.
74 * https://en.wikipedia.org/wiki/File:
76 protected $descBaseUrl;
78 /** @var string URL of the MediaWiki installation, equivalent to
79 * $wgScriptPath, e.g. https://en.wikipedia.org/w
81 protected $scriptDirUrl;
83 /** @var string Equivalent to $wgArticlePath, e.g. https://en.wikipedia.org/wiki/$1 */
84 protected $articleUrl;
86 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
87 * determines whether filenames implicitly start with a capital letter.
88 * The current implementation may give incorrect description page links
89 * when the local $wgCapitalLinks and initialCapital are mismatched.
91 protected $initialCapital;
93 /** @var string May be 'paranoid' to remove all parameters from error
94 * messages, 'none' to leave the paths in unchanged, or 'simple' to
95 * replace paths with placeholders. Default for LocalRepo is
98 protected $pathDisclosureProtection = 'simple';
100 /** @var string|false Public zone URL. */
103 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
106 /** @var int The number of directory levels for hash-based division of files */
107 protected $hashLevels;
109 /** @var int The number of directory levels for hash-based division of deleted files */
110 protected $deletedHashLevels;
112 /** @var int File names over this size will use the short form of thumbnail
113 * names. Short thumbnail names only have the width, parameters, and the
116 protected $abbrvThreshold;
118 /** @var string The URL of the repo's favicon, if any */
121 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
122 protected $isPrivate;
124 /** @var array callable Override these in the base class */
125 protected $fileFactory = [ UnregisteredLocalFile
::class, 'newFromTitle' ];
126 /** @var array callable|bool Override these in the base class */
127 protected $oldFileFactory = false;
128 /** @var array callable|bool Override these in the base class */
129 protected $fileFactoryKey = false;
130 /** @var array callable|bool Override these in the base class */
131 protected $oldFileFactoryKey = false;
133 /** @var string URL of where to proxy thumb.php requests to.
134 * Example: http://127.0.0.1:8888/wiki/dev/thumb/
136 protected $thumbProxyUrl;
137 /** @var string Secret key to pass as an X-Swift-Secret header to the proxied thumb service */
138 protected $thumbProxySecret;
141 * @param array|null $info
142 * @throws MWException
144 public function __construct( array $info = null ) {
145 // Verify required settings presence
148 ||
!array_key_exists( 'name', $info )
149 ||
!array_key_exists( 'backend', $info )
151 throw new MWException( __CLASS__
.
152 " requires an array of options having both 'name' and 'backend' keys.\n" );
156 $this->name
= $info['name'];
157 if ( $info['backend'] instanceof FileBackend
) {
158 $this->backend
= $info['backend']; // useful for testing
160 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
163 // Optional settings that can have no value
164 $optionalSettings = [
165 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
166 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
167 'favicon', 'thumbProxyUrl', 'thumbProxySecret',
169 foreach ( $optionalSettings as $var ) {
170 if ( isset( $info[$var] ) ) {
171 $this->$var = $info[$var];
175 // Optional settings that have a default
176 $this->initialCapital
= $info['initialCapital'] ?? MWNamespace
::isCapitalized( NS_FILE
);
177 $this->url
= $info['url'] ??
false; // a subclass may set the URL (e.g. ForeignAPIRepo)
178 if ( isset( $info['thumbUrl'] ) ) {
179 $this->thumbUrl
= $info['thumbUrl'];
181 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
183 $this->hashLevels
= $info['hashLevels'] ??
2;
184 $this->deletedHashLevels
= $info['deletedHashLevels'] ??
$this->hashLevels
;
185 $this->transformVia404
= !empty( $info['transformVia404'] );
186 $this->abbrvThreshold
= $info['abbrvThreshold'] ??
255;
187 $this->isPrivate
= !empty( $info['isPrivate'] );
188 // Give defaults for the basic zones...
189 $this->zones
= $info['zones'] ??
[];
190 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
191 if ( !isset( $this->zones
[$zone]['container'] ) ) {
192 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
194 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
195 $this->zones
[$zone]['directory'] = '';
197 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
198 $this->zones
[$zone]['urlsByExt'] = [];
202 $this->supportsSha1URLs
= !empty( $info['supportsSha1URLs'] );
206 * Get the file backend instance. Use this function wisely.
208 * @return FileBackend
210 public function getBackend() {
211 return $this->backend
;
215 * Get an explanatory message if this repo is read-only.
216 * This checks if an administrator disabled writes to the backend.
218 * @return string|bool Returns false if the repo is not read-only
220 public function getReadOnlyReason() {
221 return $this->backend
->getReadOnlyReason();
225 * Check if a single zone or list of zones is defined for usage
227 * @param array $doZones Only do a particular zones
228 * @throws MWException
231 protected function initZones( $doZones = [] ) {
232 $status = $this->newGood();
233 foreach ( (array)$doZones as $zone ) {
234 $root = $this->getZonePath( $zone );
235 if ( $root === null ) {
236 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
244 * Determine if a string is an mwrepo:// URL
249 public static function isVirtualUrl( $url ) {
250 return substr( $url, 0, 9 ) == 'mwrepo://';
254 * Get a URL referring to this repository, with the private mwrepo protocol.
255 * The suffix, if supplied, is considered to be unencoded, and will be
256 * URL-encoded before being returned.
258 * @param string|bool $suffix
261 public function getVirtualUrl( $suffix = false ) {
262 $path = 'mwrepo://' . $this->name
;
263 if ( $suffix !== false ) {
264 $path .= '/' . rawurlencode( $suffix );
271 * Get the URL corresponding to one of the four basic zones
273 * @param string $zone One of: public, deleted, temp, thumb
274 * @param string|null $ext Optional file extension
275 * @return string|bool
277 public function getZoneUrl( $zone, $ext = null ) {
278 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
279 // standard public zones
280 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
281 // custom URL for extension/zone
282 return $this->zones
[$zone]['urlsByExt'][$ext];
283 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
284 // custom URL for zone
285 return $this->zones
[$zone]['url'];
293 return false; // no public URL
295 return $this->thumbUrl
;
297 return "{$this->url}/transcoded";
304 * @return bool Whether non-ASCII path characters are allowed
306 public function backendSupportsUnicodePaths() {
307 return (bool)( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
311 * Get the backend storage path corresponding to a virtual URL.
312 * Use this function wisely.
315 * @throws MWException
318 public function resolveVirtualUrl( $url ) {
319 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
320 throw new MWException( __METHOD__
. ': unknown protocol' );
322 $bits = explode( '/', substr( $url, 9 ), 3 );
323 if ( count( $bits ) != 3 ) {
324 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
326 list( $repo, $zone, $rel ) = $bits;
327 if ( $repo !== $this->name
) {
328 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
330 $base = $this->getZonePath( $zone );
332 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
335 return $base . '/' . rawurldecode( $rel );
339 * The the storage container and base path of a zone
341 * @param string $zone
342 * @return array (container, base path) or (null, null)
344 protected function getZoneLocation( $zone ) {
345 if ( !isset( $this->zones
[$zone] ) ) {
346 return [ null, null ]; // bogus
349 return [ $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] ];
353 * Get the storage path corresponding to one of the zones
355 * @param string $zone
356 * @return string|null Returns null if the zone is not defined
358 public function getZonePath( $zone ) {
359 list( $container, $base ) = $this->getZoneLocation( $zone );
360 if ( $container === null ||
$base === null ) {
363 $backendName = $this->backend
->getName();
364 if ( $base != '' ) { // may not be set
368 return "mwstore://$backendName/{$container}{$base}";
372 * Create a new File object from the local repository
374 * @param Title|string $title Title object or string
375 * @param bool|string $time Time at which the image was uploaded. If this
376 * is specified, the returned object will be an instance of the
377 * repository's old file class instead of a current file. Repositories
378 * not supporting version control should return false if this parameter
380 * @return File|null A File, or null if passed an invalid Title
382 public function newFile( $title, $time = false ) {
383 $title = File
::normalizeTitle( $title );
388 if ( $this->oldFileFactory
) {
389 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
394 return call_user_func( $this->fileFactory
, $title, $this );
399 * Find an instance of the named file created at the specified time
400 * Returns false if the file does not exist. Repositories not supporting
401 * version control should return false if the time is specified.
403 * @param Title|string $title Title object or string
404 * @param array $options Associative array of options:
405 * time: requested time for a specific file version, or false for the
406 * current version. An image object will be returned which was
407 * created at the specified time (which may be archived or current).
408 * ignoreRedirect: If true, do not follow file redirects
409 * private: If true, return restricted (deleted) files if the current
410 * user is allowed to view them. Otherwise, such files will not
411 * be found. If a User object, use that user instead of the current.
412 * latest: If true, load from the latest available data into File objects
413 * @return File|bool False on failure
415 public function findFile( $title, $options = [] ) {
416 $title = File
::normalizeTitle( $title );
420 if ( isset( $options['bypassCache'] ) ) {
421 $options['latest'] = $options['bypassCache']; // b/c
423 $time = $options['time'] ??
false;
424 $flags = !empty( $options['latest'] ) ? File
::READ_LATEST
: 0;
425 # First try the current version of the file to see if it precedes the timestamp
426 $img = $this->newFile( $title );
430 $img->load( $flags );
431 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
434 # Now try an old version of the file
435 if ( $time !== false ) {
436 $img = $this->newFile( $title, $time );
438 $img->load( $flags );
439 if ( $img->exists() ) {
440 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
441 return $img; // always OK
442 } elseif ( !empty( $options['private'] ) &&
443 $img->userCan( File
::DELETED_FILE
,
444 $options['private'] instanceof User ?
$options['private'] : null
454 if ( !empty( $options['ignoreRedirect'] ) ) {
457 $redir = $this->checkRedirect( $title );
458 if ( $redir && $title->getNamespace() == NS_FILE
) {
459 $img = $this->newFile( $redir );
463 $img->load( $flags );
464 if ( $img->exists() ) {
465 $img->redirectedFrom( $title->getDBkey() );
475 * Find many files at once.
477 * @param array $items An array of titles, or an array of findFile() options with
478 * the "title" option giving the title. Example:
480 * $findItem = [ 'title' => $title, 'private' => true ];
481 * $findBatch = [ $findItem ];
482 * $repo->findFiles( $findBatch );
484 * No title should appear in $items twice, as the result use titles as keys
485 * @param int $flags Supports:
486 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
487 * The search title uses the input titles; the other is the final post-redirect title.
488 * All titles are returned as string DB keys and the inner array is associative.
489 * @return array Map of (file name => File objects) for matches
491 public function findFiles( array $items, $flags = 0 ) {
493 foreach ( $items as $item ) {
494 if ( is_array( $item ) ) {
495 $title = $item['title'];
497 unset( $options['title'] );
502 $file = $this->findFile( $title, $options );
504 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
505 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
506 $result[$searchName] = [
507 'title' => $file->getTitle()->getDBkey(),
508 'timestamp' => $file->getTimestamp()
511 $result[$searchName] = $file;
520 * Find an instance of the file with this key, created at the specified time
521 * Returns false if the file does not exist. Repositories not supporting
522 * version control should return false if the time is specified.
524 * @param string $sha1 Base 36 SHA-1 hash
525 * @param array $options Option array, same as findFile().
526 * @return File|bool False on failure
528 public function findFileFromKey( $sha1, $options = [] ) {
529 $time = $options['time'] ??
false;
530 # First try to find a matching current version of a file...
531 if ( !$this->fileFactoryKey
) {
532 return false; // find-by-sha1 not supported
534 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
535 if ( $img && $img->exists() ) {
538 # Now try to find a matching old version of a file...
539 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
540 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
541 if ( $img && $img->exists() ) {
542 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
543 return $img; // always OK
544 } elseif ( !empty( $options['private'] ) &&
545 $img->userCan( File
::DELETED_FILE
,
546 $options['private'] instanceof User ?
$options['private'] : null
558 * Get an array or iterator of file objects for files that have a given
559 * SHA-1 content hash.
562 * @param string $hash SHA-1 hash
565 public function findBySha1( $hash ) {
570 * Get an array of arrays or iterators of file objects for files that
571 * have the given SHA-1 content hashes.
573 * @param string[] $hashes An array of hashes
574 * @return array[] An Array of arrays or iterators of file objects and the hash as key
576 public function findBySha1s( array $hashes ) {
578 foreach ( $hashes as $hash ) {
579 $files = $this->findBySha1( $hash );
580 if ( count( $files ) ) {
581 $result[$hash] = $files;
589 * Return an array of files where the name starts with $prefix.
592 * @param string $prefix The prefix to search for
593 * @param int $limit The maximum amount of files to return
594 * @return LocalFile[]
596 public function findFilesByPrefix( $prefix, $limit ) {
601 * Get the URL of thumb.php
605 public function getThumbScriptUrl() {
606 return $this->thumbScriptUrl
;
610 * Get the URL thumb.php requests are being proxied to
614 public function getThumbProxyUrl() {
615 return $this->thumbProxyUrl
;
619 * Get the secret key for the proxied thumb service
623 public function getThumbProxySecret() {
624 return $this->thumbProxySecret
;
628 * Returns true if the repository can transform files via a 404 handler
632 public function canTransformVia404() {
633 return $this->transformVia404
;
637 * Get the name of a file from its title object
639 * @param Title $title
642 public function getNameFromTitle( Title
$title ) {
643 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
644 $name = $title->getUserCaseDBKey();
645 if ( $this->initialCapital
) {
646 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
649 $name = $title->getDBkey();
656 * Get the public zone root storage directory of the repository
660 public function getRootDirectory() {
661 return $this->getZonePath( 'public' );
665 * Get a relative path including trailing slash, e.g. f/fa/
666 * If the repo is not hashed, returns an empty string
668 * @param string $name Name of file
671 public function getHashPath( $name ) {
672 return self
::getHashPathForLevel( $name, $this->hashLevels
);
676 * Get a relative path including trailing slash, e.g. f/fa/
677 * If the repo is not hashed, returns an empty string
679 * @param string $suffix Basename of file from FileRepo::storeTemp()
682 public function getTempHashPath( $suffix ) {
683 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
684 $name = $parts[1] ??
$suffix; // hash path is not based on timestamp
685 return self
::getHashPathForLevel( $name, $this->hashLevels
);
689 * @param string $name
693 protected static function getHashPathForLevel( $name, $levels ) {
694 if ( $levels == 0 ) {
697 $hash = md5( $name );
699 for ( $i = 1; $i <= $levels; $i++
) {
700 $path .= substr( $hash, 0, $i ) . '/';
708 * Get the number of hash directory levels
712 public function getHashLevels() {
713 return $this->hashLevels
;
717 * Get the name of this repository, as specified by $info['name]' to the constructor
721 public function getName() {
726 * Make an url to this repo
728 * @param string $query Query string to append
729 * @param string $entry Entry point; defaults to index
730 * @return string|bool False on failure
732 public function makeUrl( $query = '', $entry = 'index' ) {
733 if ( isset( $this->scriptDirUrl
) ) {
734 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
741 * Get the URL of an image description page. May return false if it is
742 * unknown or not applicable. In general this should only be called by the
743 * File class, since it may return invalid results for certain kinds of
744 * repositories. Use File::getDescriptionUrl() in user code.
746 * In particular, it uses the article paths as specified to the repository
747 * constructor, whereas local repositories use the local Title functions.
749 * @param string $name
750 * @return string|false
752 public function getDescriptionUrl( $name ) {
753 $encName = wfUrlencode( $name );
754 if ( !is_null( $this->descBaseUrl
) ) {
755 # "http://example.com/wiki/File:"
756 return $this->descBaseUrl
. $encName;
758 if ( !is_null( $this->articleUrl
) ) {
759 # "http://example.com/wiki/$1"
760 # We use "Image:" as the canonical namespace for
761 # compatibility across all MediaWiki versions.
762 return str_replace( '$1',
763 "Image:$encName", $this->articleUrl
);
765 if ( !is_null( $this->scriptDirUrl
) ) {
766 # "http://example.com/w"
767 # We use "Image:" as the canonical namespace for
768 # compatibility across all MediaWiki versions,
769 # and just sort of hope index.php is right. ;)
770 return $this->makeUrl( "title=Image:$encName" );
777 * Get the URL of the content-only fragment of the description page. For
778 * MediaWiki this means action=render. This should only be called by the
779 * repository's file class, since it may return invalid results. User code
780 * should use File::getDescriptionText().
782 * @param string $name Name of image to fetch
783 * @param string|null $lang Language to fetch it in, if any.
784 * @return string|false
786 public function getDescriptionRenderUrl( $name, $lang = null ) {
787 $query = 'action=render';
788 if ( !is_null( $lang ) ) {
789 $query .= '&uselang=' . urlencode( $lang );
791 if ( isset( $this->scriptDirUrl
) ) {
792 return $this->makeUrl(
794 wfUrlencode( 'Image:' . $name ) .
797 $descUrl = $this->getDescriptionUrl( $name );
799 return wfAppendQuery( $descUrl, $query );
807 * Get the URL of the stylesheet to apply to description pages
809 * @return string|bool False on failure
811 public function getDescriptionStylesheetUrl() {
812 if ( isset( $this->scriptDirUrl
) ) {
813 // Must match canonical query parameter order for optimum caching
814 // See Title::getCdnUrls
815 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
822 * Store a file to a given destination.
824 * @param string $srcPath Source file system path, storage path, or virtual URL
825 * @param string $dstZone Destination zone
826 * @param string $dstRel Destination relative path
827 * @param int $flags Bitwise combination of the following flags:
828 * self::OVERWRITE Overwrite an existing destination file instead of failing
829 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
830 * same contents as the source
831 * self::SKIP_LOCKING Skip any file locking when doing the store
834 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
835 $this->assertWritableRepo(); // fail out if read-only
837 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
838 if ( $status->successCount
== 0 ) {
839 $status->setOK( false );
846 * Store a batch of files
848 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
849 * @param int $flags Bitwise combination of the following flags:
850 * self::OVERWRITE Overwrite an existing destination file instead of failing
851 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
852 * same contents as the source
853 * self::SKIP_LOCKING Skip any file locking when doing the store
854 * @throws MWException
857 public function storeBatch( array $triplets, $flags = 0 ) {
858 $this->assertWritableRepo(); // fail out if read-only
860 if ( $flags & self
::DELETE_SOURCE
) {
861 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__
);
864 $status = $this->newGood();
865 $backend = $this->backend
; // convenience
868 // Validate each triplet and get the store operation...
869 foreach ( $triplets as $triplet ) {
870 list( $srcPath, $dstZone, $dstRel ) = $triplet;
872 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
875 // Resolve destination path
876 $root = $this->getZonePath( $dstZone );
878 throw new MWException( "Invalid zone: $dstZone" );
880 if ( !$this->validateFilename( $dstRel ) ) {
881 throw new MWException( 'Validation error in $dstRel' );
883 $dstPath = "$root/$dstRel";
884 $dstDir = dirname( $dstPath );
885 // Create destination directories for this triplet
886 if ( !$this->initDirectory( $dstDir )->isOK() ) {
887 return $this->newFatal( 'directorycreateerror', $dstDir );
890 // Resolve source to a storage path if virtual
891 $srcPath = $this->resolveToStoragePath( $srcPath );
893 // Get the appropriate file operation
894 if ( FileBackend
::isStoragePath( $srcPath ) ) {
903 'overwrite' => $flags & self
::OVERWRITE
,
904 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
908 // Execute the store operation for each triplet
909 $opts = [ 'force' => true ];
910 if ( $flags & self
::SKIP_LOCKING
) {
911 $opts['nonLocking'] = true;
913 $status->merge( $backend->doOperations( $operations, $opts ) );
919 * Deletes a batch of files.
920 * Each file can be a (zone, rel) pair, virtual url, storage path.
921 * It will try to delete each file, but ignores any errors that may occur.
923 * @param string[] $files List of files to delete
924 * @param int $flags Bitwise combination of the following flags:
925 * self::SKIP_LOCKING Skip any file locking when doing the deletions
928 public function cleanupBatch( array $files, $flags = 0 ) {
929 $this->assertWritableRepo(); // fail out if read-only
931 $status = $this->newGood();
934 foreach ( $files as $path ) {
935 if ( is_array( $path ) ) {
936 // This is a pair, extract it
937 list( $zone, $rel ) = $path;
938 $path = $this->getZonePath( $zone ) . "/$rel";
940 // Resolve source to a storage path if virtual
941 $path = $this->resolveToStoragePath( $path );
943 $operations[] = [ 'op' => 'delete', 'src' => $path ];
945 // Actually delete files from storage...
946 $opts = [ 'force' => true ];
947 if ( $flags & self
::SKIP_LOCKING
) {
948 $opts['nonLocking'] = true;
950 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
956 * Import a file from the local file system into the repo.
957 * This does no locking nor journaling and overrides existing files.
958 * This function can be used to write to otherwise read-only foreign repos.
959 * This is intended for copying generated thumbnails into the repo.
961 * @param string|FSFile $src Source file system path, storage path, or virtual URL
962 * @param string $dst Virtual URL or storage path
963 * @param array|string|null $options An array consisting of a key named headers
964 * listing extra headers. If a string, taken as content-disposition header.
965 * (Support for array of options new in 1.23)
968 final public function quickImport( $src, $dst, $options = null ) {
969 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
973 * Purge a file from the repo. This does no locking nor journaling.
974 * This function can be used to write to otherwise read-only foreign repos.
975 * This is intended for purging thumbnails.
977 * @param string $path Virtual URL or storage path
980 final public function quickPurge( $path ) {
981 return $this->quickPurgeBatch( [ $path ] );
985 * Deletes a directory if empty.
986 * This function can be used to write to otherwise read-only foreign repos.
988 * @param string $dir Virtual URL (or storage path) of directory to clean
991 public function quickCleanDir( $dir ) {
992 $status = $this->newGood();
993 $status->merge( $this->backend
->clean(
994 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1000 * Import a batch of files from the local file system into the repo.
1001 * This does no locking nor journaling and overrides existing files.
1002 * This function can be used to write to otherwise read-only foreign repos.
1003 * This is intended for copying generated thumbnails into the repo.
1005 * All path parameters may be a file system path, storage path, or virtual URL.
1006 * When "headers" are given they are used as HTTP headers if supported.
1008 * @param array $triples List of (source path or FSFile, destination path, disposition)
1011 public function quickImportBatch( array $triples ) {
1012 $status = $this->newGood();
1014 foreach ( $triples as $triple ) {
1015 list( $src, $dst ) = $triple;
1016 if ( $src instanceof FSFile
) {
1019 $src = $this->resolveToStoragePath( $src );
1020 $op = FileBackend
::isStoragePath( $src ) ?
'copy' : 'store';
1022 $dst = $this->resolveToStoragePath( $dst );
1024 if ( !isset( $triple[2] ) ) {
1026 } elseif ( is_string( $triple[2] ) ) {
1028 $headers = [ 'Content-Disposition' => $triple[2] ];
1029 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1030 $headers = $triple[2]['headers'];
1039 'headers' => $headers
1041 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1043 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1049 * Purge a batch of files from the repo.
1050 * This function can be used to write to otherwise read-only foreign repos.
1051 * This does no locking nor journaling and is intended for purging thumbnails.
1053 * @param array $paths List of virtual URLs or storage paths
1056 public function quickPurgeBatch( array $paths ) {
1057 $status = $this->newGood();
1059 foreach ( $paths as $path ) {
1062 'src' => $this->resolveToStoragePath( $path ),
1063 'ignoreMissingSource' => true
1066 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1072 * Pick a random name in the temp zone and store a file to it.
1073 * Returns a Status object with the file Virtual URL in the value,
1074 * file can later be disposed using FileRepo::freeTemp().
1076 * @param string $originalName The base name of the file as specified
1077 * by the user. The file extension will be maintained.
1078 * @param string $srcPath The current location of the file.
1079 * @return Status Object with the URL in the value.
1081 public function storeTemp( $originalName, $srcPath ) {
1082 $this->assertWritableRepo(); // fail out if read-only
1084 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1085 $hashPath = $this->getHashPath( $originalName );
1086 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1087 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1089 $result = $this->quickImport( $srcPath, $virtualUrl );
1090 $result->value
= $virtualUrl;
1096 * Remove a temporary file or mark it for garbage collection
1098 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1099 * @return bool True on success, false on failure
1101 public function freeTemp( $virtualUrl ) {
1102 $this->assertWritableRepo(); // fail out if read-only
1104 $temp = $this->getVirtualUrl( 'temp' );
1105 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1106 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1111 return $this->quickPurge( $virtualUrl )->isOK();
1115 * Concatenate a list of temporary files into a target file location.
1117 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1118 * @param string $dstPath Target file system path
1119 * @param int $flags Bitwise combination of the following flags:
1120 * self::DELETE_SOURCE Delete the source files on success
1123 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1124 $this->assertWritableRepo(); // fail out if read-only
1126 $status = $this->newGood();
1129 foreach ( $srcPaths as $srcPath ) {
1130 // Resolve source to a storage path if virtual
1131 $source = $this->resolveToStoragePath( $srcPath );
1132 $sources[] = $source; // chunk to merge
1135 // Concatenate the chunks into one FS file
1136 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1137 $status->merge( $this->backend
->concatenate( $params ) );
1138 if ( !$status->isOK() ) {
1142 // Delete the sources if required
1143 if ( $flags & self
::DELETE_SOURCE
) {
1144 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1147 // Make sure status is OK, despite any quickPurgeBatch() fatals
1148 $status->setResult( true );
1154 * Copy or move a file either from a storage path, virtual URL,
1155 * or file system path, into this repository at the specified destination location.
1157 * Returns a Status object. On success, the value contains "new" or
1158 * "archived", to indicate whether the file was new with that name.
1160 * Options to $options include:
1161 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1163 * @param string|FSFile $src The source file system path, storage path, or URL
1164 * @param string $dstRel The destination relative path
1165 * @param string $archiveRel The relative path where the existing file is to
1166 * be archived, if there is one. Relative to the public zone root.
1167 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1168 * that the source file should be deleted if possible
1169 * @param array $options Optional additional parameters
1172 public function publish(
1173 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1175 $this->assertWritableRepo(); // fail out if read-only
1177 $status = $this->publishBatch(
1178 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1179 if ( $status->successCount
== 0 ) {
1180 $status->setOK( false );
1182 $status->value
= $status->value
[0] ??
false;
1188 * Publish a batch of files
1190 * @param array $ntuples (source, dest, archive) triplets or
1191 * (source, dest, archive, options) 4-tuples as per publish().
1192 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1193 * that the source files should be deleted if possible
1194 * @throws MWException
1197 public function publishBatch( array $ntuples, $flags = 0 ) {
1198 $this->assertWritableRepo(); // fail out if read-only
1200 $backend = $this->backend
; // convenience
1201 // Try creating directories
1202 $status = $this->initZones( 'public' );
1203 if ( !$status->isOK() ) {
1207 $status = $this->newGood( [] );
1210 $sourceFSFilesToDelete = []; // cleanup for disk source files
1211 // Validate each triplet and get the store operation...
1212 foreach ( $ntuples as $ntuple ) {
1213 list( $src, $dstRel, $archiveRel ) = $ntuple;
1214 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1216 $options = $ntuple[3] ??
[];
1217 // Resolve source to a storage path if virtual
1218 $srcPath = $this->resolveToStoragePath( $srcPath );
1219 if ( !$this->validateFilename( $dstRel ) ) {
1220 throw new MWException( 'Validation error in $dstRel' );
1222 if ( !$this->validateFilename( $archiveRel ) ) {
1223 throw new MWException( 'Validation error in $archiveRel' );
1226 $publicRoot = $this->getZonePath( 'public' );
1227 $dstPath = "$publicRoot/$dstRel";
1228 $archivePath = "$publicRoot/$archiveRel";
1230 $dstDir = dirname( $dstPath );
1231 $archiveDir = dirname( $archivePath );
1232 // Abort immediately on directory creation errors since they're likely to be repetitive
1233 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1234 return $this->newFatal( 'directorycreateerror', $dstDir );
1236 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1237 return $this->newFatal( 'directorycreateerror', $archiveDir );
1240 // Set any desired headers to be use in GET/HEAD responses
1241 $headers = $options['headers'] ??
[];
1243 // Archive destination file if it exists.
1244 // This will check if the archive file also exists and fail if does.
1245 // This is a sanity check to avoid data loss. On Windows and Linux,
1246 // copy() will overwrite, so the existence check is vulnerable to
1247 // race conditions unless a functioning LockManager is used.
1248 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1252 'dst' => $archivePath,
1253 'ignoreMissingSource' => true
1256 // Copy (or move) the source file to the destination
1257 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1258 if ( $flags & self
::DELETE_SOURCE
) {
1263 'overwrite' => true, // replace current
1264 'headers' => $headers
1271 'overwrite' => true, // replace current
1272 'headers' => $headers
1275 } else { // FS source path
1278 'src' => $src, // prefer FSFile objects
1280 'overwrite' => true, // replace current
1281 'headers' => $headers
1283 if ( $flags & self
::DELETE_SOURCE
) {
1284 $sourceFSFilesToDelete[] = $srcPath;
1289 // Execute the operations for each triplet
1290 $status->merge( $backend->doOperations( $operations ) );
1291 // Find out which files were archived...
1292 foreach ( $ntuples as $i => $ntuple ) {
1293 list( , , $archiveRel ) = $ntuple;
1294 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1295 if ( $this->fileExists( $archivePath ) ) {
1296 $status->value
[$i] = 'archived';
1298 $status->value
[$i] = 'new';
1301 // Cleanup for disk source files...
1302 foreach ( $sourceFSFilesToDelete as $file ) {
1303 Wikimedia\
suppressWarnings();
1304 unlink( $file ); // FS cleanup
1305 Wikimedia\restoreWarnings
();
1312 * Creates a directory with the appropriate zone permissions.
1313 * Callers are responsible for doing read-only and "writable repo" checks.
1315 * @param string $dir Virtual URL (or storage path) of directory to clean
1318 protected function initDirectory( $dir ) {
1319 $path = $this->resolveToStoragePath( $dir );
1320 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1322 $params = [ 'dir' => $path ];
1323 if ( $this->isPrivate
1324 ||
$container === $this->zones
['deleted']['container']
1325 ||
$container === $this->zones
['temp']['container']
1327 # Take all available measures to prevent web accessibility of new deleted
1328 # directories, in case the user has not configured offline storage
1329 $params = [ 'noAccess' => true, 'noListing' => true ] +
$params;
1332 $status = $this->newGood();
1333 $status->merge( $this->backend
->prepare( $params ) );
1339 * Deletes a directory if empty.
1341 * @param string $dir Virtual URL (or storage path) of directory to clean
1344 public function cleanDir( $dir ) {
1345 $this->assertWritableRepo(); // fail out if read-only
1347 $status = $this->newGood();
1348 $status->merge( $this->backend
->clean(
1349 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1355 * Checks existence of a file
1357 * @param string $file Virtual URL (or storage path) of file to check
1360 public function fileExists( $file ) {
1361 $result = $this->fileExistsBatch( [ $file ] );
1367 * Checks existence of an array of files.
1369 * @param string[] $files Virtual URLs (or storage paths) of files to check
1370 * @return array Map of files and existence flags, or false
1372 public function fileExistsBatch( array $files ) {
1373 $paths = array_map( [ $this, 'resolveToStoragePath' ], $files );
1374 $this->backend
->preloadFileStat( [ 'srcs' => $paths ] );
1377 foreach ( $files as $key => $file ) {
1378 $path = $this->resolveToStoragePath( $file );
1379 $result[$key] = $this->backend
->fileExists( [ 'src' => $path ] );
1386 * Move a file to the deletion archive.
1387 * If no valid deletion archive exists, this may either delete the file
1388 * or throw an exception, depending on the preference of the repository
1390 * @param mixed $srcRel Relative path for the file to be deleted
1391 * @param mixed $archiveRel Relative path for the archive location.
1392 * Relative to a private archive directory.
1395 public function delete( $srcRel, $archiveRel ) {
1396 $this->assertWritableRepo(); // fail out if read-only
1398 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1402 * Move a group of files to the deletion archive.
1404 * If no valid deletion archive is configured, this may either delete the
1405 * file or throw an exception, depending on the preference of the repository.
1407 * The overwrite policy is determined by the repository -- currently LocalRepo
1408 * assumes a naming scheme in the deleted zone based on content hash, as
1409 * opposed to the public zone which is assumed to be unique.
1411 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1412 * is a two-element array containing the source file path relative to the
1413 * public root in the first element, and the archive file path relative
1414 * to the deleted zone root in the second element.
1415 * @throws MWException
1418 public function deleteBatch( array $sourceDestPairs ) {
1419 $this->assertWritableRepo(); // fail out if read-only
1421 // Try creating directories
1422 $status = $this->initZones( [ 'public', 'deleted' ] );
1423 if ( !$status->isOK() ) {
1427 $status = $this->newGood();
1429 $backend = $this->backend
; // convenience
1431 // Validate filenames and create archive directories
1432 foreach ( $sourceDestPairs as $pair ) {
1433 list( $srcRel, $archiveRel ) = $pair;
1434 if ( !$this->validateFilename( $srcRel ) ) {
1435 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1436 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1437 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1440 $publicRoot = $this->getZonePath( 'public' );
1441 $srcPath = "{$publicRoot}/$srcRel";
1443 $deletedRoot = $this->getZonePath( 'deleted' );
1444 $archivePath = "{$deletedRoot}/{$archiveRel}";
1445 $archiveDir = dirname( $archivePath ); // does not touch FS
1447 // Create destination directories
1448 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1449 return $this->newFatal( 'directorycreateerror', $archiveDir );
1455 'dst' => $archivePath,
1456 // We may have 2+ identical files being deleted,
1457 // all of which will map to the same destination file
1458 'overwriteSame' => true // also see T33792
1462 // Move the files by execute the operations for each pair.
1463 // We're now committed to returning an OK result, which will
1464 // lead to the files being moved in the DB also.
1465 $opts = [ 'force' => true ];
1466 $status->merge( $backend->doOperations( $operations, $opts ) );
1472 * Delete files in the deleted directory if they are not referenced in the filearchive table
1475 * @param string[] $storageKeys
1477 public function cleanupDeletedBatch( array $storageKeys ) {
1478 $this->assertWritableRepo();
1482 * Get a relative path for a deletion archive key,
1483 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1485 * @param string $key
1486 * @throws MWException
1489 public function getDeletedHashPath( $key ) {
1490 if ( strlen( $key ) < 31 ) {
1491 throw new MWException( "Invalid storage key '$key'." );
1494 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1495 $path .= $key[$i] . '/';
1502 * If a path is a virtual URL, resolve it to a storage path.
1503 * Otherwise, just return the path as it is.
1505 * @param string $path
1507 * @throws MWException
1509 protected function resolveToStoragePath( $path ) {
1510 if ( $this->isVirtualUrl( $path ) ) {
1511 return $this->resolveVirtualUrl( $path );
1518 * Get a local FS copy of a file with a given virtual URL/storage path.
1519 * Temporary files may be purged when the file object falls out of scope.
1521 * @param string $virtualUrl
1522 * @return TempFSFile|null Returns null on failure
1524 public function getLocalCopy( $virtualUrl ) {
1525 $path = $this->resolveToStoragePath( $virtualUrl );
1527 return $this->backend
->getLocalCopy( [ 'src' => $path ] );
1531 * Get a local FS file with a given virtual URL/storage path.
1532 * The file is either an original or a copy. It should not be changed.
1533 * Temporary files may be purged when the file object falls out of scope.
1535 * @param string $virtualUrl
1536 * @return FSFile|null Returns null on failure.
1538 public function getLocalReference( $virtualUrl ) {
1539 $path = $this->resolveToStoragePath( $virtualUrl );
1541 return $this->backend
->getLocalReference( [ 'src' => $path ] );
1545 * Get properties of a file with a given virtual URL/storage path.
1546 * Properties should ultimately be obtained via FSFile::getProps().
1548 * @param string $virtualUrl
1551 public function getFileProps( $virtualUrl ) {
1552 $fsFile = $this->getLocalReference( $virtualUrl );
1553 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1555 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1557 $props = $mwProps->newPlaceholderProps();
1564 * Get the timestamp of a file with a given virtual URL/storage path
1566 * @param string $virtualUrl
1567 * @return string|bool False on failure
1569 public function getFileTimestamp( $virtualUrl ) {
1570 $path = $this->resolveToStoragePath( $virtualUrl );
1572 return $this->backend
->getFileTimestamp( [ 'src' => $path ] );
1576 * Get the size of a file with a given virtual URL/storage path
1578 * @param string $virtualUrl
1579 * @return int|bool False on failure
1581 public function getFileSize( $virtualUrl ) {
1582 $path = $this->resolveToStoragePath( $virtualUrl );
1584 return $this->backend
->getFileSize( [ 'src' => $path ] );
1588 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1590 * @param string $virtualUrl
1591 * @return string|bool
1593 public function getFileSha1( $virtualUrl ) {
1594 $path = $this->resolveToStoragePath( $virtualUrl );
1596 return $this->backend
->getFileSha1Base36( [ 'src' => $path ] );
1600 * Attempt to stream a file with the given virtual URL/storage path
1602 * @param string $virtualUrl
1603 * @param array $headers Additional HTTP headers to send on success
1604 * @param array $optHeaders HTTP request headers (if-modified-since, range, ...)
1608 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1609 $path = $this->resolveToStoragePath( $virtualUrl );
1610 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1612 // T172851: HHVM does not flush the output properly, causing OOM
1613 ob_start( null, 1048576 );
1614 ob_implicit_flush( true );
1616 $status = $this->newGood();
1617 $status->merge( $this->backend
->streamFile( $params ) );
1619 // T186565: Close the buffer, unless it has already been closed
1620 // in HTTPFileStreamer::resetOutputBuffers().
1621 if ( ob_get_status() ) {
1629 * Attempt to stream a file with the given virtual URL/storage path
1631 * @deprecated since 1.26, use streamFileWithStatus
1632 * @param string $virtualUrl
1633 * @param array $headers Additional HTTP headers to send on success
1634 * @return bool Success
1636 public function streamFile( $virtualUrl, $headers = [] ) {
1637 return $this->streamFileWithStatus( $virtualUrl, $headers )->isOK();
1641 * Call a callback function for every public regular file in the repository.
1642 * This only acts on the current version of files, not any old versions.
1643 * May use either the database or the filesystem.
1645 * @param callable $callback
1648 public function enumFiles( $callback ) {
1649 $this->enumFilesInStorage( $callback );
1653 * Call a callback function for every public file in the repository.
1654 * May use either the database or the filesystem.
1656 * @param callable $callback
1659 protected function enumFilesInStorage( $callback ) {
1660 $publicRoot = $this->getZonePath( 'public' );
1661 $numDirs = 1 << ( $this->hashLevels
* 4 );
1662 // Use a priori assumptions about directory structure
1663 // to reduce the tree height of the scanning process.
1664 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1665 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1666 $path = $publicRoot;
1667 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1668 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1670 $iterator = $this->backend
->getFileList( [ 'dir' => $path ] );
1671 foreach ( $iterator as $name ) {
1672 // Each item returned is a public file
1673 call_user_func( $callback, "{$path}/{$name}" );
1679 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1681 * @param string $filename
1684 public function validateFilename( $filename ) {
1685 if ( strval( $filename ) == '' ) {
1689 return FileBackend
::isPathTraversalFree( $filename );
1693 * Get a callback function to use for cleaning error message parameters
1697 function getErrorCleanupFunction() {
1698 switch ( $this->pathDisclosureProtection
) {
1700 case 'simple': // b/c
1701 $callback = [ $this, 'passThrough' ];
1703 default: // 'paranoid'
1704 $callback = [ $this, 'paranoidClean' ];
1710 * Path disclosure protection function
1712 * @param string $param
1715 function paranoidClean( $param ) {
1720 * Path disclosure protection function
1722 * @param string $param
1725 function passThrough( $param ) {
1730 * Create a new fatal error
1732 * @param string $message
1735 public function newFatal( $message /*, parameters...*/ ) {
1736 $status = Status
::newFatal( ...func_get_args() );
1737 $status->cleanCallback
= $this->getErrorCleanupFunction();
1743 * Create a new good result
1745 * @param null|string $value
1748 public function newGood( $value = null ) {
1749 $status = Status
::newGood( $value );
1750 $status->cleanCallback
= $this->getErrorCleanupFunction();
1756 * Checks if there is a redirect named as $title. If there is, return the
1757 * title object. If not, return false.
1760 * @param Title $title Title of image
1763 public function checkRedirect( Title
$title ) {
1768 * Invalidates image redirect cache related to that image
1769 * Doesn't do anything for repositories that don't support image redirects.
1772 * @param Title $title Title of image
1774 public function invalidateImageRedirect( Title
$title ) {
1778 * Get the human-readable name of the repo
1782 public function getDisplayName() {
1785 if ( $this->isLocal() ) {
1789 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1790 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1794 * Get the portion of the file that contains the origin file name.
1795 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1797 * @param string $name
1800 public function nameForThumb( $name ) {
1801 if ( strlen( $name ) > $this->abbrvThreshold
) {
1802 $ext = FileBackend
::extensionFromPath( $name );
1803 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1810 * Returns true if this the local file repository.
1814 public function isLocal() {
1815 return $this->getName() == 'local';
1819 * Get a key on the primary cache for this repository.
1820 * Returns false if the repository's cache is not accessible at this site.
1821 * The parameters are the parts of the key, as for wfMemcKey().
1826 public function getSharedCacheKey( /*...*/ ) {
1831 * Get a key for this repo in the local cache domain. These cache keys are
1832 * not shared with remote instances of the repo.
1833 * The parameters are the parts of the key, as for wfMemcKey().
1837 public function getLocalCacheKey( /*...*/ ) {
1838 $args = func_get_args();
1839 array_unshift( $args, 'filerepo', $this->getName() );
1841 return wfMemcKey( ...$args );
1845 * Get a temporary private FileRepo associated with this repo.
1847 * Files will be created in the temp zone of this repo.
1848 * It will have the same backend as this repo.
1850 * @return TempFileRepo
1852 public function getTempRepo() {
1853 return new TempFileRepo( [
1854 'name' => "{$this->name}-temp",
1855 'backend' => $this->backend
,
1858 // Same place storeTemp() uses in the base repo, though
1859 // the path hashing is mismatched, which is annoying.
1860 'container' => $this->zones
['temp']['container'],
1861 'directory' => $this->zones
['temp']['directory']
1864 'container' => $this->zones
['temp']['container'],
1865 'directory' => $this->zones
['temp']['directory'] == ''
1867 : $this->zones
['temp']['directory'] . '/thumb'
1870 'container' => $this->zones
['temp']['container'],
1871 'directory' => $this->zones
['temp']['directory'] == ''
1873 : $this->zones
['temp']['directory'] . '/transcoded'
1876 'hashLevels' => $this->hashLevels
, // performance
1877 'isPrivate' => true // all in temp zone
1882 * Get an UploadStash associated with this repo.
1884 * @param User|null $user
1885 * @return UploadStash
1887 public function getUploadStash( User
$user = null ) {
1888 return new UploadStash( $this, $user );
1892 * Throw an exception if this repo is read-only by design.
1893 * This does not and should not check getReadOnlyReason().
1896 * @throws MWException
1898 protected function assertWritableRepo() {
1902 * Return information about the repository.
1907 public function getInfo() {
1909 'name' => $this->getName(),
1910 'displayname' => $this->getDisplayName(),
1911 'rootUrl' => $this->getZoneUrl( 'public' ),
1912 'local' => $this->isLocal(),
1915 $optionalSettings = [
1916 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1917 'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1919 foreach ( $optionalSettings as $k ) {
1920 if ( isset( $this->$k ) ) {
1921 $ret[$k] = $this->$k;
1929 * Returns whether or not storage is SHA-1 based
1932 public function hasSha1Storage() {
1933 return $this->hasSha1Storage
;
1937 * Returns whether or not repo supports having originals SHA-1s in the thumb URLs
1940 public function supportsSha1URLs() {
1941 return $this->supportsSha1URLs
;