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
50 public $fetchDescription;
53 public $descriptionCacheExpiry;
56 protected $hasSha1Storage = false;
59 protected $supportsSha1URLs = false;
61 /** @var FileBackend */
64 /** @var array Map of zones to config */
65 protected $zones = [];
67 /** @var string URL of thumb.php */
68 protected $thumbScriptUrl;
70 /** @var bool Whether to skip media file transformation on parse and rely
71 * on a 404 handler instead.
73 protected $transformVia404;
75 /** @var string URL of image description pages, e.g.
76 * https://en.wikipedia.org/wiki/File:
78 protected $descBaseUrl;
80 /** @var string URL of the MediaWiki installation, equivalent to
81 * $wgScriptPath, e.g. https://en.wikipedia.org/w
83 protected $scriptDirUrl;
85 /** @var string Equivalent to $wgArticlePath, e.g. https://en.wikipedia.org/wiki/$1 */
86 protected $articleUrl;
88 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
89 * determines whether filenames implicitly start with a capital letter.
90 * The current implementation may give incorrect description page links
91 * when the local $wgCapitalLinks and initialCapital are mismatched.
93 protected $initialCapital;
95 /** @var string May be 'paranoid' to remove all parameters from error
96 * messages, 'none' to leave the paths in unchanged, or 'simple' to
97 * replace paths with placeholders. Default for LocalRepo is
100 protected $pathDisclosureProtection = 'simple';
102 /** @var string|false Public zone URL. */
105 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
108 /** @var int The number of directory levels for hash-based division of files */
109 protected $hashLevels;
111 /** @var int The number of directory levels for hash-based division of deleted files */
112 protected $deletedHashLevels;
114 /** @var int File names over this size will use the short form of thumbnail
115 * names. Short thumbnail names only have the width, parameters, and the
118 protected $abbrvThreshold;
120 /** @var string The URL of the repo's favicon, if any */
123 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
124 protected $isPrivate;
126 /** @var callable Override these in the base class */
127 protected $fileFactory = [ UnregisteredLocalFile
::class, 'newFromTitle' ];
128 /** @var callable|false Override these in the base class */
129 protected $oldFileFactory = false;
130 /** @var callable|false Override these in the base class */
131 protected $fileFactoryKey = false;
132 /** @var callable|false Override these in the base class */
133 protected $oldFileFactoryKey = false;
135 /** @var string URL of where to proxy thumb.php requests to.
136 * Example: http://127.0.0.1:8888/wiki/dev/thumb/
138 protected $thumbProxyUrl;
139 /** @var string Secret key to pass as an X-Swift-Secret header to the proxied thumb service */
140 protected $thumbProxySecret;
142 /** @var WANObjectCache */
147 * @protected Use $this->getName(). Public for back-compat only
152 * @param array|null $info
153 * @throws MWException
155 public function __construct( array $info = null ) {
156 // Verify required settings presence
159 ||
!array_key_exists( 'name', $info )
160 ||
!array_key_exists( 'backend', $info )
162 throw new MWException( __CLASS__
.
163 " requires an array of options having both 'name' and 'backend' keys.\n" );
167 $this->name
= $info['name'];
168 if ( $info['backend'] instanceof FileBackend
) {
169 $this->backend
= $info['backend']; // useful for testing
171 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
174 // Optional settings that can have no value
175 $optionalSettings = [
176 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
177 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
178 'favicon', 'thumbProxyUrl', 'thumbProxySecret',
180 foreach ( $optionalSettings as $var ) {
181 if ( isset( $info[$var] ) ) {
182 $this->$var = $info[$var];
186 // Optional settings that have a default
187 $this->initialCapital
= $info['initialCapital'] ??
188 MediaWikiServices
::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE
);
189 $this->url
= $info['url'] ??
false; // a subclass may set the URL (e.g. ForeignAPIRepo)
190 if ( isset( $info['thumbUrl'] ) ) {
191 $this->thumbUrl
= $info['thumbUrl'];
193 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
195 $this->hashLevels
= $info['hashLevels'] ??
2;
196 $this->deletedHashLevels
= $info['deletedHashLevels'] ??
$this->hashLevels
;
197 $this->transformVia404
= !empty( $info['transformVia404'] );
198 $this->abbrvThreshold
= $info['abbrvThreshold'] ??
255;
199 $this->isPrivate
= !empty( $info['isPrivate'] );
200 // Give defaults for the basic zones...
201 $this->zones
= $info['zones'] ??
[];
202 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
203 if ( !isset( $this->zones
[$zone]['container'] ) ) {
204 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
206 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
207 $this->zones
[$zone]['directory'] = '';
209 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
210 $this->zones
[$zone]['urlsByExt'] = [];
214 $this->supportsSha1URLs
= !empty( $info['supportsSha1URLs'] );
216 $this->wanCache
= $info['wanCache'] ?? WANObjectCache
::newEmpty();
220 * Get the file backend instance. Use this function wisely.
222 * @return FileBackend
224 public function getBackend() {
225 return $this->backend
;
229 * Get an explanatory message if this repo is read-only.
230 * This checks if an administrator disabled writes to the backend.
232 * @return string|bool Returns false if the repo is not read-only
234 public function getReadOnlyReason() {
235 return $this->backend
->getReadOnlyReason();
239 * Check if a single zone or list of zones is defined for usage
241 * @param string[]|string $doZones Only do a particular zones
242 * @throws MWException
245 protected function initZones( $doZones = [] ) {
246 $status = $this->newGood();
247 foreach ( (array)$doZones as $zone ) {
248 $root = $this->getZonePath( $zone );
249 if ( $root === null ) {
250 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
258 * Determine if a string is an mwrepo:// URL
263 public static function isVirtualUrl( $url ) {
264 return substr( $url, 0, 9 ) == 'mwrepo://';
268 * Get a URL referring to this repository, with the private mwrepo protocol.
269 * The suffix, if supplied, is considered to be unencoded, and will be
270 * URL-encoded before being returned.
272 * @param string|bool $suffix
275 public function getVirtualUrl( $suffix = false ) {
276 $path = 'mwrepo://' . $this->name
;
277 if ( $suffix !== false ) {
278 $path .= '/' . rawurlencode( $suffix );
285 * Get the URL corresponding to one of the four basic zones
287 * @param string $zone One of: public, deleted, temp, thumb
288 * @param string|null $ext Optional file extension
289 * @return string|bool
291 public function getZoneUrl( $zone, $ext = null ) {
292 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
293 // standard public zones
294 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
295 // custom URL for extension/zone
296 return $this->zones
[$zone]['urlsByExt'][$ext];
297 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
298 // custom URL for zone
299 return $this->zones
[$zone]['url'];
307 return false; // no public URL
309 return $this->thumbUrl
;
311 return "{$this->url}/transcoded";
318 * @return bool Whether non-ASCII path characters are allowed
320 public function backendSupportsUnicodePaths() {
321 return (bool)( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
325 * Get the backend storage path corresponding to a virtual URL.
326 * Use this function wisely.
329 * @throws MWException
332 public function resolveVirtualUrl( $url ) {
333 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
334 throw new MWException( __METHOD__
. ': unknown protocol' );
336 $bits = explode( '/', substr( $url, 9 ), 3 );
337 if ( count( $bits ) != 3 ) {
338 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
340 list( $repo, $zone, $rel ) = $bits;
341 if ( $repo !== $this->name
) {
342 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
344 $base = $this->getZonePath( $zone );
346 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
349 return $base . '/' . rawurldecode( $rel );
353 * The the storage container and base path of a zone
355 * @param string $zone
356 * @return array (container, base path) or (null, null)
358 protected function getZoneLocation( $zone ) {
359 if ( !isset( $this->zones
[$zone] ) ) {
360 return [ null, null ]; // bogus
363 return [ $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] ];
367 * Get the storage path corresponding to one of the zones
369 * @param string $zone
370 * @return string|null Returns null if the zone is not defined
372 public function getZonePath( $zone ) {
373 list( $container, $base ) = $this->getZoneLocation( $zone );
374 if ( $container === null ||
$base === null ) {
377 $backendName = $this->backend
->getName();
378 if ( $base != '' ) { // may not be set
382 return "mwstore://$backendName/{$container}{$base}";
386 * Create a new File object from the local repository
388 * @param Title|string $title Title object or string
389 * @param bool|string $time Time at which the image was uploaded. If this
390 * is specified, the returned object will be an instance of the
391 * repository's old file class instead of a current file. Repositories
392 * not supporting version control should return false if this parameter
394 * @return File|null A File, or null if passed an invalid Title
396 public function newFile( $title, $time = false ) {
397 $title = File
::normalizeTitle( $title );
402 if ( $this->oldFileFactory
) {
403 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
408 return call_user_func( $this->fileFactory
, $title, $this );
413 * Find an instance of the named file created at the specified time
414 * Returns false if the file does not exist. Repositories not supporting
415 * version control should return false if the time is specified.
417 * @param Title|string $title Title object or string
418 * @param array $options Associative array of options:
419 * time: requested time for a specific file version, or false for the
420 * current version. An image object will be returned which was
421 * created at the specified time (which may be archived or current).
422 * ignoreRedirect: If true, do not follow file redirects
423 * private: If true, return restricted (deleted) files if the current
424 * user is allowed to view them. Otherwise, such files will not
425 * be found. If a User object, use that user instead of the current.
426 * latest: If true, load from the latest available data into File objects
427 * @return File|bool False on failure
429 public function findFile( $title, $options = [] ) {
430 $title = File
::normalizeTitle( $title );
434 if ( isset( $options['bypassCache'] ) ) {
435 $options['latest'] = $options['bypassCache']; // b/c
437 $time = $options['time'] ??
false;
438 $flags = !empty( $options['latest'] ) ? File
::READ_LATEST
: 0;
439 # First try the current version of the file to see if it precedes the timestamp
440 $img = $this->newFile( $title );
444 $img->load( $flags );
445 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
448 # Now try an old version of the file
449 if ( $time !== false ) {
450 $img = $this->newFile( $title, $time );
452 $img->load( $flags );
453 if ( $img->exists() ) {
454 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
455 return $img; // always OK
456 } elseif ( !empty( $options['private'] ) &&
457 $img->userCan( File
::DELETED_FILE
,
458 $options['private'] instanceof User ?
$options['private'] : null
468 if ( !empty( $options['ignoreRedirect'] ) ) {
471 $redir = $this->checkRedirect( $title );
472 if ( $redir && $title->getNamespace() == NS_FILE
) {
473 $img = $this->newFile( $redir );
477 $img->load( $flags );
478 if ( $img->exists() ) {
479 $img->redirectedFrom( $title->getDBkey() );
489 * Find many files at once.
491 * @param array $items An array of titles, or an array of findFile() options with
492 * the "title" option giving the title. Example:
494 * $findItem = [ 'title' => $title, 'private' => true ];
495 * $findBatch = [ $findItem ];
496 * $repo->findFiles( $findBatch );
498 * No title should appear in $items twice, as the result use titles as keys
499 * @param int $flags Supports:
500 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
501 * The search title uses the input titles; the other is the final post-redirect title.
502 * All titles are returned as string DB keys and the inner array is associative.
503 * @return array Map of (file name => File objects) for matches
505 public function findFiles( array $items, $flags = 0 ) {
507 foreach ( $items as $item ) {
508 if ( is_array( $item ) ) {
509 $title = $item['title'];
511 unset( $options['title'] );
516 $file = $this->findFile( $title, $options );
518 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
519 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
520 $result[$searchName] = [
521 'title' => $file->getTitle()->getDBkey(),
522 'timestamp' => $file->getTimestamp()
525 $result[$searchName] = $file;
534 * Find an instance of the file with this key, created at the specified time
535 * Returns false if the file does not exist. Repositories not supporting
536 * version control should return false if the time is specified.
538 * @param string $sha1 Base 36 SHA-1 hash
539 * @param array $options Option array, same as findFile().
540 * @return File|bool False on failure
542 public function findFileFromKey( $sha1, $options = [] ) {
543 $time = $options['time'] ??
false;
544 # First try to find a matching current version of a file...
545 if ( !$this->fileFactoryKey
) {
546 return false; // find-by-sha1 not supported
548 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
549 if ( $img && $img->exists() ) {
552 # Now try to find a matching old version of a file...
553 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
554 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
555 if ( $img && $img->exists() ) {
556 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
557 return $img; // always OK
558 } elseif ( !empty( $options['private'] ) &&
559 $img->userCan( File
::DELETED_FILE
,
560 $options['private'] instanceof User ?
$options['private'] : null
572 * Get an array or iterator of file objects for files that have a given
573 * SHA-1 content hash.
576 * @param string $hash SHA-1 hash
579 public function findBySha1( $hash ) {
584 * Get an array of arrays or iterators of file objects for files that
585 * have the given SHA-1 content hashes.
587 * @param string[] $hashes An array of hashes
588 * @return array[] An Array of arrays or iterators of file objects and the hash as key
590 public function findBySha1s( array $hashes ) {
592 foreach ( $hashes as $hash ) {
593 $files = $this->findBySha1( $hash );
594 if ( count( $files ) ) {
595 $result[$hash] = $files;
603 * Return an array of files where the name starts with $prefix.
606 * @param string $prefix The prefix to search for
607 * @param int $limit The maximum amount of files to return
608 * @return LocalFile[]
610 public function findFilesByPrefix( $prefix, $limit ) {
615 * Get the URL of thumb.php
619 public function getThumbScriptUrl() {
620 return $this->thumbScriptUrl
;
624 * Get the URL thumb.php requests are being proxied to
628 public function getThumbProxyUrl() {
629 return $this->thumbProxyUrl
;
633 * Get the secret key for the proxied thumb service
637 public function getThumbProxySecret() {
638 return $this->thumbProxySecret
;
642 * Returns true if the repository can transform files via a 404 handler
646 public function canTransformVia404() {
647 return $this->transformVia404
;
651 * Get the name of a file from its title object
653 * @param Title $title
656 public function getNameFromTitle( Title
$title ) {
658 $this->initialCapital
!=
659 MediaWikiServices
::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE
)
661 $name = $title->getUserCaseDBKey();
662 if ( $this->initialCapital
) {
663 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
666 $name = $title->getDBkey();
673 * Get the public zone root storage directory of the repository
677 public function getRootDirectory() {
678 return $this->getZonePath( 'public' );
682 * Get a relative path including trailing slash, e.g. f/fa/
683 * If the repo is not hashed, returns an empty string
685 * @param string $name Name of file
688 public function getHashPath( $name ) {
689 return self
::getHashPathForLevel( $name, $this->hashLevels
);
693 * Get a relative path including trailing slash, e.g. f/fa/
694 * If the repo is not hashed, returns an empty string
696 * @param string $suffix Basename of file from FileRepo::storeTemp()
699 public function getTempHashPath( $suffix ) {
700 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
701 $name = $parts[1] ??
$suffix; // hash path is not based on timestamp
702 return self
::getHashPathForLevel( $name, $this->hashLevels
);
706 * @param string $name
710 protected static function getHashPathForLevel( $name, $levels ) {
711 if ( $levels == 0 ) {
714 $hash = md5( $name );
716 for ( $i = 1; $i <= $levels; $i++
) {
717 $path .= substr( $hash, 0, $i ) . '/';
725 * Get the number of hash directory levels
729 public function getHashLevels() {
730 return $this->hashLevels
;
734 * Get the name of this repository, as specified by $info['name]' to the constructor
738 public function getName() {
743 * Make an url to this repo
745 * @param string|string[] $query Query string to append
746 * @param string $entry Entry point; defaults to index
747 * @return string|bool False on failure
749 public function makeUrl( $query = '', $entry = 'index' ) {
750 if ( isset( $this->scriptDirUrl
) ) {
751 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
758 * Get the URL of an image description page. May return false if it is
759 * unknown or not applicable. In general this should only be called by the
760 * File class, since it may return invalid results for certain kinds of
761 * repositories. Use File::getDescriptionUrl() in user code.
763 * In particular, it uses the article paths as specified to the repository
764 * constructor, whereas local repositories use the local Title functions.
766 * @param string $name
767 * @return string|false
769 public function getDescriptionUrl( $name ) {
770 $encName = wfUrlencode( $name );
771 if ( !is_null( $this->descBaseUrl
) ) {
772 # "http://example.com/wiki/File:"
773 return $this->descBaseUrl
. $encName;
775 if ( !is_null( $this->articleUrl
) ) {
776 # "http://example.com/wiki/$1"
777 # We use "Image:" as the canonical namespace for
778 # compatibility across all MediaWiki versions.
779 return str_replace( '$1',
780 "Image:$encName", $this->articleUrl
);
782 if ( !is_null( $this->scriptDirUrl
) ) {
783 # "http://example.com/w"
784 # We use "Image:" as the canonical namespace for
785 # compatibility across all MediaWiki versions,
786 # and just sort of hope index.php is right. ;)
787 return $this->makeUrl( "title=Image:$encName" );
794 * Get the URL of the content-only fragment of the description page. For
795 * MediaWiki this means action=render. This should only be called by the
796 * repository's file class, since it may return invalid results. User code
797 * should use File::getDescriptionText().
799 * @param string $name Name of image to fetch
800 * @param string|null $lang Language to fetch it in, if any.
801 * @return string|false
803 public function getDescriptionRenderUrl( $name, $lang = null ) {
804 $query = 'action=render';
805 if ( !is_null( $lang ) ) {
806 $query .= '&uselang=' . urlencode( $lang );
808 if ( isset( $this->scriptDirUrl
) ) {
809 return $this->makeUrl(
811 wfUrlencode( 'Image:' . $name ) .
814 $descUrl = $this->getDescriptionUrl( $name );
816 return wfAppendQuery( $descUrl, $query );
824 * Get the URL of the stylesheet to apply to description pages
826 * @return string|bool False on failure
828 public function getDescriptionStylesheetUrl() {
829 if ( isset( $this->scriptDirUrl
) ) {
830 // Must match canonical query parameter order for optimum caching
831 // See Title::getCdnUrls
832 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
839 * Store a file to a given destination.
841 * @param string $srcPath Source file system path, storage path, or virtual URL
842 * @param string $dstZone Destination zone
843 * @param string $dstRel Destination relative path
844 * @param int $flags Bitwise combination of the following flags:
845 * self::OVERWRITE Overwrite an existing destination file instead of failing
846 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
847 * same contents as the source
848 * self::SKIP_LOCKING Skip any file locking when doing the store
851 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
852 $this->assertWritableRepo(); // fail out if read-only
854 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
855 if ( $status->successCount
== 0 ) {
856 $status->setOK( false );
863 * Store a batch of files
865 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
866 * @param int $flags Bitwise combination of the following flags:
867 * self::OVERWRITE Overwrite an existing destination file instead of failing
868 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
869 * same contents as the source
870 * self::SKIP_LOCKING Skip any file locking when doing the store
871 * @throws MWException
874 public function storeBatch( array $triplets, $flags = 0 ) {
875 $this->assertWritableRepo(); // fail out if read-only
877 if ( $flags & self
::DELETE_SOURCE
) {
878 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__
);
881 $status = $this->newGood();
882 $backend = $this->backend
; // convenience
885 // Validate each triplet and get the store operation...
886 foreach ( $triplets as $triplet ) {
887 list( $srcPath, $dstZone, $dstRel ) = $triplet;
889 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
892 // Resolve destination path
893 $root = $this->getZonePath( $dstZone );
895 throw new MWException( "Invalid zone: $dstZone" );
897 if ( !$this->validateFilename( $dstRel ) ) {
898 throw new MWException( 'Validation error in $dstRel' );
900 $dstPath = "$root/$dstRel";
901 $dstDir = dirname( $dstPath );
902 // Create destination directories for this triplet
903 if ( !$this->initDirectory( $dstDir )->isOK() ) {
904 return $this->newFatal( 'directorycreateerror', $dstDir );
907 // Resolve source to a storage path if virtual
908 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
910 // Copy the source file to the destination
912 'op' => FileBackend
::isStoragePath( $srcPath ) ?
'copy' : 'store',
913 'src' => $srcPath, // storage path (copy) or local file path (store)
915 'overwrite' => ( $flags & self
::OVERWRITE
) ?
true : false,
916 'overwriteSame' => ( $flags & self
::OVERWRITE_SAME
) ?
true : false,
920 // Execute the store operation for each triplet
921 $opts = [ 'force' => true ];
922 if ( $flags & self
::SKIP_LOCKING
) {
923 $opts['nonLocking'] = true;
925 $status->merge( $backend->doOperations( $operations, $opts ) );
931 * Deletes a batch of files.
932 * Each file can be a (zone, rel) pair, virtual url, storage path.
933 * It will try to delete each file, but ignores any errors that may occur.
935 * @param string[] $files List of files to delete
936 * @param int $flags Bitwise combination of the following flags:
937 * self::SKIP_LOCKING Skip any file locking when doing the deletions
940 public function cleanupBatch( array $files, $flags = 0 ) {
941 $this->assertWritableRepo(); // fail out if read-only
943 $status = $this->newGood();
946 foreach ( $files as $path ) {
947 if ( is_array( $path ) ) {
948 // This is a pair, extract it
949 list( $zone, $rel ) = $path;
950 $path = $this->getZonePath( $zone ) . "/$rel";
952 // Resolve source to a storage path if virtual
953 $path = $this->resolveToStoragePathIfVirtual( $path );
955 $operations[] = [ 'op' => 'delete', 'src' => $path ];
957 // Actually delete files from storage...
958 $opts = [ 'force' => true ];
959 if ( $flags & self
::SKIP_LOCKING
) {
960 $opts['nonLocking'] = true;
962 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
968 * Import a file from the local file system into the repo.
969 * This does no locking nor journaling and overrides existing files.
970 * This function can be used to write to otherwise read-only foreign repos.
971 * This is intended for copying generated thumbnails into the repo.
973 * @param string|FSFile $src Source file system path, storage path, or virtual URL
974 * @param string $dst Virtual URL or storage path
975 * @param array|string|null $options An array consisting of a key named headers
976 * listing extra headers. If a string, taken as content-disposition header.
977 * (Support for array of options new in 1.23)
980 final public function quickImport( $src, $dst, $options = null ) {
981 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
985 * Purge a file from the repo. This does no locking nor journaling.
986 * This function can be used to write to otherwise read-only foreign repos.
987 * This is intended for purging thumbnails.
989 * @param string $path Virtual URL or storage path
992 final public function quickPurge( $path ) {
993 return $this->quickPurgeBatch( [ $path ] );
997 * Deletes a directory if empty.
998 * This function can be used to write to otherwise read-only foreign repos.
1000 * @param string $dir Virtual URL (or storage path) of directory to clean
1003 public function quickCleanDir( $dir ) {
1004 $status = $this->newGood();
1005 $status->merge( $this->backend
->clean(
1006 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1012 * Import a batch of files from the local file system into the repo.
1013 * This does no locking nor journaling and overrides existing files.
1014 * This function can be used to write to otherwise read-only foreign repos.
1015 * This is intended for copying generated thumbnails into the repo.
1017 * All path parameters may be a file system path, storage path, or virtual URL.
1018 * When "headers" are given they are used as HTTP headers if supported.
1020 * @param array $triples List of (source path or FSFile, destination path, disposition)
1023 public function quickImportBatch( array $triples ) {
1024 $status = $this->newGood();
1026 foreach ( $triples as $triple ) {
1027 list( $src, $dst ) = $triple;
1028 if ( $src instanceof FSFile
) {
1031 $src = $this->resolveToStoragePathIfVirtual( $src );
1032 $op = FileBackend
::isStoragePath( $src ) ?
'copy' : 'store';
1034 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1036 if ( !isset( $triple[2] ) ) {
1038 } elseif ( is_string( $triple[2] ) ) {
1040 $headers = [ 'Content-Disposition' => $triple[2] ];
1041 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1042 $headers = $triple[2]['headers'];
1051 'headers' => $headers
1053 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1055 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1061 * Purge a batch of files from the repo.
1062 * This function can be used to write to otherwise read-only foreign repos.
1063 * This does no locking nor journaling and is intended for purging thumbnails.
1065 * @param array $paths List of virtual URLs or storage paths
1068 public function quickPurgeBatch( array $paths ) {
1069 $status = $this->newGood();
1071 foreach ( $paths as $path ) {
1074 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1075 'ignoreMissingSource' => true
1078 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1084 * Pick a random name in the temp zone and store a file to it.
1085 * Returns a Status object with the file Virtual URL in the value,
1086 * file can later be disposed using FileRepo::freeTemp().
1088 * @param string $originalName The base name of the file as specified
1089 * by the user. The file extension will be maintained.
1090 * @param string $srcPath The current location of the file.
1091 * @return Status Object with the URL in the value.
1093 public function storeTemp( $originalName, $srcPath ) {
1094 $this->assertWritableRepo(); // fail out if read-only
1096 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1097 $hashPath = $this->getHashPath( $originalName );
1098 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1099 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1101 $result = $this->quickImport( $srcPath, $virtualUrl );
1102 $result->value
= $virtualUrl;
1108 * Remove a temporary file or mark it for garbage collection
1110 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1111 * @return bool True on success, false on failure
1113 public function freeTemp( $virtualUrl ) {
1114 $this->assertWritableRepo(); // fail out if read-only
1116 $temp = $this->getVirtualUrl( 'temp' );
1117 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1118 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1123 return $this->quickPurge( $virtualUrl )->isOK();
1127 * Concatenate a list of temporary files into a target file location.
1129 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1130 * @param string $dstPath Target file system path
1131 * @param int $flags Bitwise combination of the following flags:
1132 * self::DELETE_SOURCE Delete the source files on success
1135 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1136 $this->assertWritableRepo(); // fail out if read-only
1138 $status = $this->newGood();
1141 foreach ( $srcPaths as $srcPath ) {
1142 // Resolve source to a storage path if virtual
1143 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1144 $sources[] = $source; // chunk to merge
1147 // Concatenate the chunks into one FS file
1148 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1149 $status->merge( $this->backend
->concatenate( $params ) );
1150 if ( !$status->isOK() ) {
1154 // Delete the sources if required
1155 if ( $flags & self
::DELETE_SOURCE
) {
1156 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1159 // Make sure status is OK, despite any quickPurgeBatch() fatals
1160 $status->setResult( true );
1166 * Copy or move a file either from a storage path, virtual URL,
1167 * or file system path, into this repository at the specified destination location.
1169 * Returns a Status object. On success, the value contains "new" or
1170 * "archived", to indicate whether the file was new with that name.
1172 * Options to $options include:
1173 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1175 * @param string|FSFile $src The source file system path, storage path, or URL
1176 * @param string $dstRel The destination relative path
1177 * @param string $archiveRel The relative path where the existing file is to
1178 * be archived, if there is one. Relative to the public zone root.
1179 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1180 * that the source file should be deleted if possible
1181 * @param array $options Optional additional parameters
1184 public function publish(
1185 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1187 $this->assertWritableRepo(); // fail out if read-only
1189 $status = $this->publishBatch(
1190 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1191 if ( $status->successCount
== 0 ) {
1192 $status->setOK( false );
1194 $status->value
= $status->value
[0] ??
false;
1200 * Publish a batch of files
1202 * @param array $ntuples (source, dest, archive) triplets or
1203 * (source, dest, archive, options) 4-tuples as per publish().
1204 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1205 * that the source files should be deleted if possible
1206 * @throws MWException
1209 public function publishBatch( array $ntuples, $flags = 0 ) {
1210 $this->assertWritableRepo(); // fail out if read-only
1212 $backend = $this->backend
; // convenience
1213 // Try creating directories
1214 $status = $this->initZones( 'public' );
1215 if ( !$status->isOK() ) {
1219 $status = $this->newGood( [] );
1222 $sourceFSFilesToDelete = []; // cleanup for disk source files
1223 // Validate each triplet and get the store operation...
1224 foreach ( $ntuples as $ntuple ) {
1225 list( $src, $dstRel, $archiveRel ) = $ntuple;
1226 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1228 $options = $ntuple[3] ??
[];
1229 // Resolve source to a storage path if virtual
1230 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1231 if ( !$this->validateFilename( $dstRel ) ) {
1232 throw new MWException( 'Validation error in $dstRel' );
1234 if ( !$this->validateFilename( $archiveRel ) ) {
1235 throw new MWException( 'Validation error in $archiveRel' );
1238 $publicRoot = $this->getZonePath( 'public' );
1239 $dstPath = "$publicRoot/$dstRel";
1240 $archivePath = "$publicRoot/$archiveRel";
1242 $dstDir = dirname( $dstPath );
1243 $archiveDir = dirname( $archivePath );
1244 // Abort immediately on directory creation errors since they're likely to be repetitive
1245 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1246 return $this->newFatal( 'directorycreateerror', $dstDir );
1248 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1249 return $this->newFatal( 'directorycreateerror', $archiveDir );
1252 // Set any desired headers to be use in GET/HEAD responses
1253 $headers = $options['headers'] ??
[];
1255 // Archive destination file if it exists.
1256 // This will check if the archive file also exists and fail if does.
1257 // This is a sanity check to avoid data loss. On Windows and Linux,
1258 // copy() will overwrite, so the existence check is vulnerable to
1259 // race conditions unless a functioning LockManager is used.
1260 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1264 'dst' => $archivePath,
1265 'ignoreMissingSource' => true
1268 // Copy (or move) the source file to the destination
1269 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1271 'op' => ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy',
1274 'overwrite' => true, // replace current
1275 'headers' => $headers
1280 'src' => $src, // FSFile (preferred) or local file path
1282 'overwrite' => true, // replace current
1283 'headers' => $headers
1285 if ( $flags & self
::DELETE_SOURCE
) {
1286 $sourceFSFilesToDelete[] = $srcPath;
1291 // Execute the operations for each triplet
1292 $status->merge( $backend->doOperations( $operations ) );
1293 // Find out which files were archived...
1294 foreach ( $ntuples as $i => $ntuple ) {
1295 list( , , $archiveRel ) = $ntuple;
1296 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1297 if ( $this->fileExists( $archivePath ) ) {
1298 $status->value
[$i] = 'archived';
1300 $status->value
[$i] = 'new';
1303 // Cleanup for disk source files...
1304 foreach ( $sourceFSFilesToDelete as $file ) {
1305 Wikimedia\
suppressWarnings();
1306 unlink( $file ); // FS cleanup
1307 Wikimedia\restoreWarnings
();
1314 * Creates a directory with the appropriate zone permissions.
1315 * Callers are responsible for doing read-only and "writable repo" checks.
1317 * @param string $dir Virtual URL (or storage path) of directory to clean
1320 protected function initDirectory( $dir ) {
1321 $path = $this->resolveToStoragePathIfVirtual( $dir );
1322 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1324 $params = [ 'dir' => $path ];
1325 if ( $this->isPrivate
1326 ||
$container === $this->zones
['deleted']['container']
1327 ||
$container === $this->zones
['temp']['container']
1329 # Take all available measures to prevent web accessibility of new deleted
1330 # directories, in case the user has not configured offline storage
1331 $params = [ 'noAccess' => true, 'noListing' => true ] +
$params;
1334 $status = $this->newGood();
1335 $status->merge( $this->backend
->prepare( $params ) );
1341 * Deletes a directory if empty.
1343 * @param string $dir Virtual URL (or storage path) of directory to clean
1346 public function cleanDir( $dir ) {
1347 $this->assertWritableRepo(); // fail out if read-only
1349 $status = $this->newGood();
1350 $status->merge( $this->backend
->clean(
1351 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ] ) );
1357 * Checks existence of a file
1359 * @param string $file Virtual URL (or storage path) of file to check
1362 public function fileExists( $file ) {
1363 $result = $this->fileExistsBatch( [ $file ] );
1369 * Checks existence of an array of files.
1371 * @param string[] $files Virtual URLs (or storage paths) of files to check
1372 * @return array Map of files and existence flags, or false
1374 public function fileExistsBatch( array $files ) {
1375 $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1376 $this->backend
->preloadFileStat( [ 'srcs' => $paths ] );
1379 foreach ( $files as $key => $file ) {
1380 $path = $this->resolveToStoragePathIfVirtual( $file );
1381 $result[$key] = $this->backend
->fileExists( [ 'src' => $path ] );
1388 * Move a file to the deletion archive.
1389 * If no valid deletion archive exists, this may either delete the file
1390 * or throw an exception, depending on the preference of the repository
1392 * @param mixed $srcRel Relative path for the file to be deleted
1393 * @param mixed $archiveRel Relative path for the archive location.
1394 * Relative to a private archive directory.
1397 public function delete( $srcRel, $archiveRel ) {
1398 $this->assertWritableRepo(); // fail out if read-only
1400 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1404 * Move a group of files to the deletion archive.
1406 * If no valid deletion archive is configured, this may either delete the
1407 * file or throw an exception, depending on the preference of the repository.
1409 * The overwrite policy is determined by the repository -- currently LocalRepo
1410 * assumes a naming scheme in the deleted zone based on content hash, as
1411 * opposed to the public zone which is assumed to be unique.
1413 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1414 * is a two-element array containing the source file path relative to the
1415 * public root in the first element, and the archive file path relative
1416 * to the deleted zone root in the second element.
1417 * @throws MWException
1420 public function deleteBatch( array $sourceDestPairs ) {
1421 $this->assertWritableRepo(); // fail out if read-only
1423 // Try creating directories
1424 $status = $this->initZones( [ 'public', 'deleted' ] );
1425 if ( !$status->isOK() ) {
1429 $status = $this->newGood();
1431 $backend = $this->backend
; // convenience
1433 // Validate filenames and create archive directories
1434 foreach ( $sourceDestPairs as $pair ) {
1435 list( $srcRel, $archiveRel ) = $pair;
1436 if ( !$this->validateFilename( $srcRel ) ) {
1437 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1438 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1439 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1442 $publicRoot = $this->getZonePath( 'public' );
1443 $srcPath = "{$publicRoot}/$srcRel";
1445 $deletedRoot = $this->getZonePath( 'deleted' );
1446 $archivePath = "{$deletedRoot}/{$archiveRel}";
1447 $archiveDir = dirname( $archivePath ); // does not touch FS
1449 // Create destination directories
1450 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1451 return $this->newFatal( 'directorycreateerror', $archiveDir );
1457 'dst' => $archivePath,
1458 // We may have 2+ identical files being deleted,
1459 // all of which will map to the same destination file
1460 'overwriteSame' => true // also see T33792
1464 // Move the files by execute the operations for each pair.
1465 // We're now committed to returning an OK result, which will
1466 // lead to the files being moved in the DB also.
1467 $opts = [ 'force' => true ];
1468 $status->merge( $backend->doOperations( $operations, $opts ) );
1474 * Delete files in the deleted directory if they are not referenced in the filearchive table
1477 * @param string[] $storageKeys
1479 public function cleanupDeletedBatch( array $storageKeys ) {
1480 $this->assertWritableRepo();
1484 * Get a relative path for a deletion archive key,
1485 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1487 * @param string $key
1488 * @throws MWException
1491 public function getDeletedHashPath( $key ) {
1492 if ( strlen( $key ) < 31 ) {
1493 throw new MWException( "Invalid storage key '$key'." );
1496 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1497 $path .= $key[$i] . '/';
1504 * If a path is a virtual URL, resolve it to a storage path.
1505 * Otherwise, just return the path as it is.
1507 * @param string $path
1509 * @throws MWException
1511 protected function resolveToStoragePathIfVirtual( $path ) {
1512 if ( self
::isVirtualUrl( $path ) ) {
1513 return $this->resolveVirtualUrl( $path );
1520 * Get a local FS copy of a file with a given virtual URL/storage path.
1521 * Temporary files may be purged when the file object falls out of scope.
1523 * @param string $virtualUrl
1524 * @return TempFSFile|null Returns null on failure
1526 public function getLocalCopy( $virtualUrl ) {
1527 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1529 return $this->backend
->getLocalCopy( [ 'src' => $path ] );
1533 * Get a local FS file with a given virtual URL/storage path.
1534 * The file is either an original or a copy. It should not be changed.
1535 * Temporary files may be purged when the file object falls out of scope.
1537 * @param string $virtualUrl
1538 * @return FSFile|null Returns null on failure.
1540 public function getLocalReference( $virtualUrl ) {
1541 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1543 return $this->backend
->getLocalReference( [ 'src' => $path ] );
1547 * Get properties of a file with a given virtual URL/storage path.
1548 * Properties should ultimately be obtained via FSFile::getProps().
1550 * @param string $virtualUrl
1553 public function getFileProps( $virtualUrl ) {
1554 $fsFile = $this->getLocalReference( $virtualUrl );
1555 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1557 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1559 $props = $mwProps->newPlaceholderProps();
1566 * Get the timestamp of a file with a given virtual URL/storage path
1568 * @param string $virtualUrl
1569 * @return string|bool False on failure
1571 public function getFileTimestamp( $virtualUrl ) {
1572 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1574 return $this->backend
->getFileTimestamp( [ 'src' => $path ] );
1578 * Get the size of a file with a given virtual URL/storage path
1580 * @param string $virtualUrl
1581 * @return int|bool False on failure
1583 public function getFileSize( $virtualUrl ) {
1584 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1586 return $this->backend
->getFileSize( [ 'src' => $path ] );
1590 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1592 * @param string $virtualUrl
1593 * @return string|bool
1595 public function getFileSha1( $virtualUrl ) {
1596 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1598 return $this->backend
->getFileSha1Base36( [ 'src' => $path ] );
1602 * Attempt to stream a file with the given virtual URL/storage path
1604 * @param string $virtualUrl
1605 * @param array $headers Additional HTTP headers to send on success
1606 * @param array $optHeaders HTTP request headers (if-modified-since, range, ...)
1610 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1611 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1612 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1614 // T172851: HHVM does not flush the output properly, causing OOM
1615 ob_start( null, 1048576 );
1616 ob_implicit_flush( true );
1618 $status = $this->newGood();
1619 $status->merge( $this->backend
->streamFile( $params ) );
1621 // T186565: Close the buffer, unless it has already been closed
1622 // in HTTPFileStreamer::resetOutputBuffers().
1623 if ( ob_get_status() ) {
1631 * Call a callback function for every public regular file in the repository.
1632 * This only acts on the current version of files, not any old versions.
1633 * May use either the database or the filesystem.
1635 * @param callable $callback
1638 public function enumFiles( $callback ) {
1639 $this->enumFilesInStorage( $callback );
1643 * Call a callback function for every public file in the repository.
1644 * May use either the database or the filesystem.
1646 * @param callable $callback
1649 protected function enumFilesInStorage( $callback ) {
1650 $publicRoot = $this->getZonePath( 'public' );
1651 $numDirs = 1 << ( $this->hashLevels
* 4 );
1652 // Use a priori assumptions about directory structure
1653 // to reduce the tree height of the scanning process.
1654 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1655 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1656 $path = $publicRoot;
1657 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1658 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1660 $iterator = $this->backend
->getFileList( [ 'dir' => $path ] );
1661 foreach ( $iterator as $name ) {
1662 // Each item returned is a public file
1663 call_user_func( $callback, "{$path}/{$name}" );
1669 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1671 * @param string $filename
1674 public function validateFilename( $filename ) {
1675 if ( strval( $filename ) == '' ) {
1679 return FileBackend
::isPathTraversalFree( $filename );
1683 * Get a callback function to use for cleaning error message parameters
1687 function getErrorCleanupFunction() {
1688 switch ( $this->pathDisclosureProtection
) {
1690 case 'simple': // b/c
1691 $callback = [ $this, 'passThrough' ];
1693 default: // 'paranoid'
1694 $callback = [ $this, 'paranoidClean' ];
1700 * Path disclosure protection function
1702 * @param string $param
1705 function paranoidClean( $param ) {
1710 * Path disclosure protection function
1712 * @param string $param
1715 function passThrough( $param ) {
1720 * Create a new fatal error
1722 * @param string $message
1725 public function newFatal( $message /*, parameters...*/ ) {
1726 $status = Status
::newFatal( ...func_get_args() );
1727 $status->cleanCallback
= $this->getErrorCleanupFunction();
1733 * Create a new good result
1735 * @param null|mixed $value
1738 public function newGood( $value = null ) {
1739 $status = Status
::newGood( $value );
1740 $status->cleanCallback
= $this->getErrorCleanupFunction();
1746 * Checks if there is a redirect named as $title. If there is, return the
1747 * title object. If not, return false.
1750 * @param Title $title Title of image
1753 public function checkRedirect( Title
$title ) {
1758 * Invalidates image redirect cache related to that image
1759 * Doesn't do anything for repositories that don't support image redirects.
1762 * @param Title $title Title of image
1764 public function invalidateImageRedirect( Title
$title ) {
1768 * Get the human-readable name of the repo
1772 public function getDisplayName() {
1775 if ( $this->isLocal() ) {
1779 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1780 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1784 * Get the portion of the file that contains the origin file name.
1785 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1787 * @param string $name
1790 public function nameForThumb( $name ) {
1791 if ( strlen( $name ) > $this->abbrvThreshold
) {
1792 $ext = FileBackend
::extensionFromPath( $name );
1793 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1800 * Returns true if this the local file repository.
1804 public function isLocal() {
1805 return $this->getName() == 'local';
1809 * Get a key on the primary cache for this repository.
1810 * Returns false if the repository's cache is not accessible at this site.
1811 * The parameters are the parts of the key.
1816 public function getSharedCacheKey( /*...*/ ) {
1821 * Get a key for this repo in the local cache domain. These cache keys are
1822 * not shared with remote instances of the repo.
1823 * The parameters are the parts of the key.
1827 public function getLocalCacheKey( /*...*/ ) {
1828 $args = func_get_args();
1829 array_unshift( $args, 'filerepo', $this->getName() );
1831 return $this->wanCache
->makeKey( ...$args );
1835 * Get a temporary private FileRepo associated with this repo.
1837 * Files will be created in the temp zone of this repo.
1838 * It will have the same backend as this repo.
1840 * @return TempFileRepo
1842 public function getTempRepo() {
1843 return new TempFileRepo( [
1844 'name' => "{$this->name}-temp",
1845 'backend' => $this->backend
,
1848 // Same place storeTemp() uses in the base repo, though
1849 // the path hashing is mismatched, which is annoying.
1850 'container' => $this->zones
['temp']['container'],
1851 'directory' => $this->zones
['temp']['directory']
1854 'container' => $this->zones
['temp']['container'],
1855 'directory' => $this->zones
['temp']['directory'] == ''
1857 : $this->zones
['temp']['directory'] . '/thumb'
1860 'container' => $this->zones
['temp']['container'],
1861 'directory' => $this->zones
['temp']['directory'] == ''
1863 : $this->zones
['temp']['directory'] . '/transcoded'
1866 'hashLevels' => $this->hashLevels
, // performance
1867 'isPrivate' => true // all in temp zone
1872 * Get an UploadStash associated with this repo.
1874 * @param User|null $user
1875 * @return UploadStash
1877 public function getUploadStash( User
$user = null ) {
1878 return new UploadStash( $this, $user );
1882 * Throw an exception if this repo is read-only by design.
1883 * This does not and should not check getReadOnlyReason().
1886 * @throws MWException
1888 protected function assertWritableRepo() {
1892 * Return information about the repository.
1897 public function getInfo() {
1899 'name' => $this->getName(),
1900 'displayname' => $this->getDisplayName(),
1901 'rootUrl' => $this->getZoneUrl( 'public' ),
1902 'local' => $this->isLocal(),
1905 $optionalSettings = [
1906 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1907 'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1909 foreach ( $optionalSettings as $k ) {
1910 if ( isset( $this->$k ) ) {
1911 $ret[$k] = $this->$k;
1919 * Returns whether or not storage is SHA-1 based
1922 public function hasSha1Storage() {
1923 return $this->hasSha1Storage
;
1927 * Returns whether or not repo supports having originals SHA-1s in the thumb URLs
1930 public function supportsSha1URLs() {
1931 return $this->supportsSha1URLs
;