3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
33 * Base class for file repositories
38 const DELETE_SOURCE
= 1;
40 const OVERWRITE_SAME
= 4;
41 const SKIP_LOCKING
= 8;
43 const NAME_AND_TIME_ONLY
= 1;
45 /** @var bool Whether to fetch commons image description pages and display
46 * them on the local wiki */
47 public $fetchDescription;
50 public $descriptionCacheExpiry;
53 protected $hasSha1Storage = false;
56 protected $supportsSha1URLs = false;
58 /** @var FileBackend */
61 /** @var array Map of zones to config */
62 protected $zones = [];
64 /** @var string URL of thumb.php */
65 protected $thumbScriptUrl;
67 /** @var bool Whether to skip media file transformation on parse and rely
68 * on a 404 handler instead. */
69 protected $transformVia404;
71 /** @var string URL of image description pages, e.g.
72 * https://en.wikipedia.org/wiki/File:
74 protected $descBaseUrl;
76 /** @var string URL of the MediaWiki installation, equivalent to
77 * $wgScriptPath, e.g. https://en.wikipedia.org/w
79 protected $scriptDirUrl;
81 /** @var string Script extension of the MediaWiki installation, equivalent
82 * to the old $wgScriptExtension, e.g. .php5 defaults to .php */
83 protected $scriptExtension;
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 array callable Override these in the base class */
127 protected $fileFactory = [ UnregisteredLocalFile
::class, 'newFromTitle' ];
128 /** @var array callable|bool Override these in the base class */
129 protected $oldFileFactory = false;
130 /** @var array callable|bool Override these in the base class */
131 protected $fileFactoryKey = false;
132 /** @var array callable|bool 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;
143 * @param array|null $info
144 * @throws MWException
146 public function __construct( array $info = null ) {
147 // Verify required settings presence
150 ||
!array_key_exists( 'name', $info )
151 ||
!array_key_exists( 'backend', $info )
153 throw new MWException( __CLASS__
.
154 " requires an array of options having both 'name' and 'backend' keys.\n" );
158 $this->name
= $info['name'];
159 if ( $info['backend'] instanceof FileBackend
) {
160 $this->backend
= $info['backend']; // useful for testing
162 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
165 // Optional settings that can have no value
166 $optionalSettings = [
167 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
168 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
169 'scriptExtension', 'favicon', 'thumbProxyUrl', 'thumbProxySecret'
171 foreach ( $optionalSettings as $var ) {
172 if ( isset( $info[$var] ) ) {
173 $this->$var = $info[$var];
177 // Optional settings that have a default
178 $this->initialCapital
= isset( $info['initialCapital'] )
179 ?
$info['initialCapital']
180 : MWNamespace
::isCapitalized( NS_FILE
);
181 $this->url
= isset( $info['url'] )
183 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
184 if ( isset( $info['thumbUrl'] ) ) {
185 $this->thumbUrl
= $info['thumbUrl'];
187 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
189 $this->hashLevels
= isset( $info['hashLevels'] )
190 ?
$info['hashLevels']
192 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
193 ?
$info['deletedHashLevels']
195 $this->transformVia404
= !empty( $info['transformVia404'] );
196 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
197 ?
$info['abbrvThreshold']
199 $this->isPrivate
= !empty( $info['isPrivate'] );
200 // Give defaults for the basic zones...
201 $this->zones
= isset( $info['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'] );
218 * Get the file backend instance. Use this function wisely.
220 * @return FileBackend
222 public function getBackend() {
223 return $this->backend
;
227 * Get an explanatory message if this repo is read-only.
228 * This checks if an administrator disabled writes to the backend.
230 * @return string|bool Returns false if the repo is not read-only
232 public function getReadOnlyReason() {
233 return $this->backend
->getReadOnlyReason();
237 * Check if a single zone or list of zones is defined for usage
239 * @param array $doZones Only do a particular zones
240 * @throws MWException
243 protected function initZones( $doZones = [] ) {
244 $status = $this->newGood();
245 foreach ( (array)$doZones as $zone ) {
246 $root = $this->getZonePath( $zone );
247 if ( $root === null ) {
248 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
256 * Determine if a string is an mwrepo:// URL
261 public static function isVirtualUrl( $url ) {
262 return substr( $url, 0, 9 ) == 'mwrepo://';
266 * Get a URL referring to this repository, with the private mwrepo protocol.
267 * The suffix, if supplied, is considered to be unencoded, and will be
268 * URL-encoded before being returned.
270 * @param string|bool $suffix
273 public function getVirtualUrl( $suffix = false ) {
274 $path = 'mwrepo://' . $this->name
;
275 if ( $suffix !== false ) {
276 $path .= '/' . rawurlencode( $suffix );
283 * Get the URL corresponding to one of the four basic zones
285 * @param string $zone One of: public, deleted, temp, thumb
286 * @param string|null $ext Optional file extension
287 * @return string|bool
289 public function getZoneUrl( $zone, $ext = null ) {
290 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
291 // standard public zones
292 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
293 // custom URL for extension/zone
294 return $this->zones
[$zone]['urlsByExt'][$ext];
295 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
296 // custom URL for zone
297 return $this->zones
[$zone]['url'];
305 return false; // no public URL
307 return $this->thumbUrl
;
309 return "{$this->url}/transcoded";
316 * @return bool Whether non-ASCII path characters are allowed
318 public function backendSupportsUnicodePaths() {
319 return (bool)( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
323 * Get the backend storage path corresponding to a virtual URL.
324 * Use this function wisely.
327 * @throws MWException
330 public function resolveVirtualUrl( $url ) {
331 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
332 throw new MWException( __METHOD__
. ': unknown protocol' );
334 $bits = explode( '/', substr( $url, 9 ), 3 );
335 if ( count( $bits ) != 3 ) {
336 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
338 list( $repo, $zone, $rel ) = $bits;
339 if ( $repo !== $this->name
) {
340 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
342 $base = $this->getZonePath( $zone );
344 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
347 return $base . '/' . rawurldecode( $rel );
351 * The the storage container and base path of a zone
353 * @param string $zone
354 * @return array (container, base path) or (null, null)
356 protected function getZoneLocation( $zone ) {
357 if ( !isset( $this->zones
[$zone] ) ) {
358 return [ null, null ]; // bogus
361 return [ $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] ];
365 * Get the storage path corresponding to one of the zones
367 * @param string $zone
368 * @return string|null Returns null if the zone is not defined
370 public function getZonePath( $zone ) {
371 list( $container, $base ) = $this->getZoneLocation( $zone );
372 if ( $container === null ||
$base === null ) {
375 $backendName = $this->backend
->getName();
376 if ( $base != '' ) { // may not be set
380 return "mwstore://$backendName/{$container}{$base}";
384 * Create a new File object from the local repository
386 * @param Title|string $title Title object or string
387 * @param bool|string $time Time at which the image was uploaded. If this
388 * is specified, the returned object will be an instance of the
389 * repository's old file class instead of a current file. Repositories
390 * not supporting version control should return false if this parameter
392 * @return File|null A File, or null if passed an invalid Title
394 public function newFile( $title, $time = false ) {
395 $title = File
::normalizeTitle( $title );
400 if ( $this->oldFileFactory
) {
401 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
406 return call_user_func( $this->fileFactory
, $title, $this );
411 * Find an instance of the named file created at the specified time
412 * Returns false if the file does not exist. Repositories not supporting
413 * version control should return false if the time is specified.
415 * @param Title|string $title Title object or string
416 * @param array $options Associative array of options:
417 * time: requested time for a specific file version, or false for the
418 * current version. An image object will be returned which was
419 * created at the specified time (which may be archived or current).
420 * ignoreRedirect: If true, do not follow file redirects
421 * private: If true, return restricted (deleted) files if the current
422 * user is allowed to view them. Otherwise, such files will not
423 * be found. If a User object, use that user instead of the current.
424 * latest: If true, load from the latest available data into File objects
425 * @return File|bool False on failure
427 public function findFile( $title, $options = [] ) {
428 $title = File
::normalizeTitle( $title );
432 if ( isset( $options['bypassCache'] ) ) {
433 $options['latest'] = $options['bypassCache']; // b/c
435 $time = isset( $options['time'] ) ?
$options['time'] : false;
436 $flags = !empty( $options['latest'] ) ? File
::READ_LATEST
: 0;
437 # First try the current version of the file to see if it precedes the timestamp
438 $img = $this->newFile( $title );
442 $img->load( $flags );
443 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
446 # Now try an old version of the file
447 if ( $time !== false ) {
448 $img = $this->newFile( $title, $time );
450 $img->load( $flags );
451 if ( $img->exists() ) {
452 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
453 return $img; // always OK
454 } elseif ( !empty( $options['private'] ) &&
455 $img->userCan( File
::DELETED_FILE
,
456 $options['private'] instanceof User ?
$options['private'] : null
466 if ( !empty( $options['ignoreRedirect'] ) ) {
469 $redir = $this->checkRedirect( $title );
470 if ( $redir && $title->getNamespace() == NS_FILE
) {
471 $img = $this->newFile( $redir );
475 $img->load( $flags );
476 if ( $img->exists() ) {
477 $img->redirectedFrom( $title->getDBkey() );
487 * Find many files at once.
489 * @param array $items An array of titles, or an array of findFile() options with
490 * the "title" option giving the title. Example:
492 * $findItem = [ 'title' => $title, 'private' => true ];
493 * $findBatch = [ $findItem ];
494 * $repo->findFiles( $findBatch );
496 * No title should appear in $items twice, as the result use titles as keys
497 * @param int $flags Supports:
498 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
499 * The search title uses the input titles; the other is the final post-redirect title.
500 * All titles are returned as string DB keys and the inner array is associative.
501 * @return array Map of (file name => File objects) for matches
503 public function findFiles( array $items, $flags = 0 ) {
505 foreach ( $items as $item ) {
506 if ( is_array( $item ) ) {
507 $title = $item['title'];
509 unset( $options['title'] );
514 $file = $this->findFile( $title, $options );
516 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
517 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
518 $result[$searchName] = [
519 'title' => $file->getTitle()->getDBkey(),
520 'timestamp' => $file->getTimestamp()
523 $result[$searchName] = $file;
532 * Find an instance of the file with this key, created at the specified time
533 * Returns false if the file does not exist. Repositories not supporting
534 * version control should return false if the time is specified.
536 * @param string $sha1 Base 36 SHA-1 hash
537 * @param array $options Option array, same as findFile().
538 * @return File|bool False on failure
540 public function findFileFromKey( $sha1, $options = [] ) {
541 $time = isset( $options['time'] ) ?
$options['time'] : false;
542 # First try to find a matching current version of a file...
543 if ( !$this->fileFactoryKey
) {
544 return false; // find-by-sha1 not supported
546 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
547 if ( $img && $img->exists() ) {
550 # Now try to find a matching old version of a file...
551 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
552 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
553 if ( $img && $img->exists() ) {
554 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
555 return $img; // always OK
556 } elseif ( !empty( $options['private'] ) &&
557 $img->userCan( File
::DELETED_FILE
,
558 $options['private'] instanceof User ?
$options['private'] : null
570 * Get an array or iterator of file objects for files that have a given
571 * SHA-1 content hash.
574 * @param string $hash SHA-1 hash
577 public function findBySha1( $hash ) {
582 * Get an array of arrays or iterators of file objects for files that
583 * have the given SHA-1 content hashes.
585 * @param array $hashes An array of hashes
586 * @return array An Array of arrays or iterators of file objects and the hash as key
588 public function findBySha1s( array $hashes ) {
590 foreach ( $hashes as $hash ) {
591 $files = $this->findBySha1( $hash );
592 if ( count( $files ) ) {
593 $result[$hash] = $files;
601 * Return an array of files where the name starts with $prefix.
604 * @param string $prefix The prefix to search for
605 * @param int $limit The maximum amount of files to return
608 public function findFilesByPrefix( $prefix, $limit ) {
613 * Get the URL of thumb.php
617 public function getThumbScriptUrl() {
618 return $this->thumbScriptUrl
;
622 * Get the URL thumb.php requests are being proxied to
626 public function getThumbProxyUrl() {
627 return $this->thumbProxyUrl
;
631 * Get the secret key for the proxied thumb service
635 public function getThumbProxySecret() {
636 return $this->thumbProxySecret
;
640 * Returns true if the repository can transform files via a 404 handler
644 public function canTransformVia404() {
645 return $this->transformVia404
;
649 * Get the name of a file from its title object
651 * @param Title $title
654 public function getNameFromTitle( Title
$title ) {
656 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
657 $name = $title->getUserCaseDBKey();
658 if ( $this->initialCapital
) {
659 $name = $wgContLang->ucfirst( $name );
662 $name = $title->getDBkey();
669 * Get the public zone root storage directory of the repository
673 public function getRootDirectory() {
674 return $this->getZonePath( 'public' );
678 * Get a relative path including trailing slash, e.g. f/fa/
679 * If the repo is not hashed, returns an empty string
681 * @param string $name Name of file
684 public function getHashPath( $name ) {
685 return self
::getHashPathForLevel( $name, $this->hashLevels
);
689 * Get a relative path including trailing slash, e.g. f/fa/
690 * If the repo is not hashed, returns an empty string
692 * @param string $suffix Basename of file from FileRepo::storeTemp()
695 public function getTempHashPath( $suffix ) {
696 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
697 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
698 return self
::getHashPathForLevel( $name, $this->hashLevels
);
702 * @param string $name
706 protected static function getHashPathForLevel( $name, $levels ) {
707 if ( $levels == 0 ) {
710 $hash = md5( $name );
712 for ( $i = 1; $i <= $levels; $i++
) {
713 $path .= substr( $hash, 0, $i ) . '/';
721 * Get the number of hash directory levels
725 public function getHashLevels() {
726 return $this->hashLevels
;
730 * Get the name of this repository, as specified by $info['name]' to the constructor
734 public function getName() {
739 * Make an url to this repo
741 * @param string $query Query string to append
742 * @param string $entry Entry point; defaults to index
743 * @return string|bool False on failure
745 public function makeUrl( $query = '', $entry = 'index' ) {
746 if ( isset( $this->scriptDirUrl
) ) {
747 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
749 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
756 * Get the URL of an image description page. May return false if it is
757 * unknown or not applicable. In general this should only be called by the
758 * File class, since it may return invalid results for certain kinds of
759 * repositories. Use File::getDescriptionUrl() in user code.
761 * In particular, it uses the article paths as specified to the repository
762 * constructor, whereas local repositories use the local Title functions.
764 * @param string $name
765 * @return string|false
767 public function getDescriptionUrl( $name ) {
768 $encName = wfUrlencode( $name );
769 if ( !is_null( $this->descBaseUrl
) ) {
770 # "http://example.com/wiki/File:"
771 return $this->descBaseUrl
. $encName;
773 if ( !is_null( $this->articleUrl
) ) {
774 # "http://example.com/wiki/$1"
775 # We use "Image:" as the canonical namespace for
776 # compatibility across all MediaWiki versions.
777 return str_replace( '$1',
778 "Image:$encName", $this->articleUrl
);
780 if ( !is_null( $this->scriptDirUrl
) ) {
781 # "http://example.com/w"
782 # We use "Image:" as the canonical namespace for
783 # compatibility across all MediaWiki versions,
784 # and just sort of hope index.php is right. ;)
785 return $this->makeUrl( "title=Image:$encName" );
792 * Get the URL of the content-only fragment of the description page. For
793 * MediaWiki this means action=render. This should only be called by the
794 * repository's file class, since it may return invalid results. User code
795 * should use File::getDescriptionText().
797 * @param string $name Name of image to fetch
798 * @param string $lang Language to fetch it in, if any.
799 * @return string|false
801 public function getDescriptionRenderUrl( $name, $lang = null ) {
802 $query = 'action=render';
803 if ( !is_null( $lang ) ) {
804 $query .= '&uselang=' . urlencode( $lang );
806 if ( isset( $this->scriptDirUrl
) ) {
807 return $this->makeUrl(
809 wfUrlencode( 'Image:' . $name ) .
812 $descUrl = $this->getDescriptionUrl( $name );
814 return wfAppendQuery( $descUrl, $query );
822 * Get the URL of the stylesheet to apply to description pages
824 * @return string|bool False on failure
826 public function getDescriptionStylesheetUrl() {
827 if ( isset( $this->scriptDirUrl
) ) {
828 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
829 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
836 * Store a file to a given destination.
838 * @param string $srcPath Source file system path, storage path, or virtual URL
839 * @param string $dstZone Destination zone
840 * @param string $dstRel Destination relative path
841 * @param int $flags Bitwise combination of the following flags:
842 * self::OVERWRITE Overwrite an existing destination file instead of failing
843 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
844 * same contents as the source
845 * self::SKIP_LOCKING Skip any file locking when doing the store
848 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
849 $this->assertWritableRepo(); // fail out if read-only
851 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
852 if ( $status->successCount
== 0 ) {
853 $status->setOK( false );
860 * Store a batch of files
862 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
863 * @param int $flags Bitwise combination of the following flags:
864 * self::OVERWRITE Overwrite an existing destination file instead of failing
865 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
866 * same contents as the source
867 * self::SKIP_LOCKING Skip any file locking when doing the store
868 * @throws MWException
871 public function storeBatch( array $triplets, $flags = 0 ) {
872 $this->assertWritableRepo(); // fail out if read-only
874 if ( $flags & self
::DELETE_SOURCE
) {
875 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__
);
878 $status = $this->newGood();
879 $backend = $this->backend
; // convenience
882 // Validate each triplet and get the store operation...
883 foreach ( $triplets as $triplet ) {
884 list( $srcPath, $dstZone, $dstRel ) = $triplet;
886 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
889 // Resolve destination path
890 $root = $this->getZonePath( $dstZone );
892 throw new MWException( "Invalid zone: $dstZone" );
894 if ( !$this->validateFilename( $dstRel ) ) {
895 throw new MWException( 'Validation error in $dstRel' );
897 $dstPath = "$root/$dstRel";
898 $dstDir = dirname( $dstPath );
899 // Create destination directories for this triplet
900 if ( !$this->initDirectory( $dstDir )->isOK() ) {
901 return $this->newFatal( 'directorycreateerror', $dstDir );
904 // Resolve source to a storage path if virtual
905 $srcPath = $this->resolveToStoragePath( $srcPath );
907 // Get the appropriate file operation
908 if ( FileBackend
::isStoragePath( $srcPath ) ) {
917 'overwrite' => $flags & self
::OVERWRITE
,
918 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
922 // Execute the store operation for each triplet
923 $opts = [ 'force' => true ];
924 if ( $flags & self
::SKIP_LOCKING
) {
925 $opts['nonLocking'] = true;
927 $status->merge( $backend->doOperations( $operations, $opts ) );
933 * Deletes a batch of files.
934 * Each file can be a (zone, rel) pair, virtual url, storage path.
935 * It will try to delete each file, but ignores any errors that may occur.
937 * @param array $files List of files to delete
938 * @param int $flags Bitwise combination of the following flags:
939 * self::SKIP_LOCKING Skip any file locking when doing the deletions
942 public function cleanupBatch( array $files, $flags = 0 ) {
943 $this->assertWritableRepo(); // fail out if read-only
945 $status = $this->newGood();
948 foreach ( $files as $path ) {
949 if ( is_array( $path ) ) {
950 // This is a pair, extract it
951 list( $zone, $rel ) = $path;
952 $path = $this->getZonePath( $zone ) . "/$rel";
954 // Resolve source to a storage path if virtual
955 $path = $this->resolveToStoragePath( $path );
957 $operations[] = [ 'op' => 'delete', 'src' => $path ];
959 // Actually delete files from storage...
960 $opts = [ 'force' => true ];
961 if ( $flags & self
::SKIP_LOCKING
) {
962 $opts['nonLocking'] = true;
964 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
970 * Import a file from the local file system into the repo.
971 * This does no locking nor journaling and overrides existing files.
972 * This function can be used to write to otherwise read-only foreign repos.
973 * This is intended for copying generated thumbnails into the repo.
975 * @param string|FSFile $src Source file system path, storage path, or virtual URL
976 * @param string $dst Virtual URL or storage path
977 * @param array|string|null $options An array consisting of a key named headers
978 * listing extra headers. If a string, taken as content-disposition header.
979 * (Support for array of options new in 1.23)
982 final public function quickImport( $src, $dst, $options = null ) {
983 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
987 * Purge a file from the repo. This does no locking nor journaling.
988 * This function can be used to write to otherwise read-only foreign repos.
989 * This is intended for purging thumbnails.
991 * @param string $path Virtual URL or storage path
994 final public function quickPurge( $path ) {
995 return $this->quickPurgeBatch( [ $path ] );
999 * Deletes a directory if empty.
1000 * This function can be used to write to otherwise read-only foreign repos.
1002 * @param string $dir Virtual URL (or storage path) of directory to clean
1005 public function quickCleanDir( $dir ) {
1006 $status = $this->newGood();
1007 $status->merge( $this->backend
->clean(
1008 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1014 * Import a batch of files from the local file system into the repo.
1015 * This does no locking nor journaling and overrides existing files.
1016 * This function can be used to write to otherwise read-only foreign repos.
1017 * This is intended for copying generated thumbnails into the repo.
1019 * All path parameters may be a file system path, storage path, or virtual URL.
1020 * When "headers" are given they are used as HTTP headers if supported.
1022 * @param array $triples List of (source path or FSFile, destination path, disposition)
1025 public function quickImportBatch( array $triples ) {
1026 $status = $this->newGood();
1028 foreach ( $triples as $triple ) {
1029 list( $src, $dst ) = $triple;
1030 if ( $src instanceof FSFile
) {
1033 $src = $this->resolveToStoragePath( $src );
1034 $op = FileBackend
::isStoragePath( $src ) ?
'copy' : 'store';
1036 $dst = $this->resolveToStoragePath( $dst );
1038 if ( !isset( $triple[2] ) ) {
1040 } elseif ( is_string( $triple[2] ) ) {
1042 $headers = [ 'Content-Disposition' => $triple[2] ];
1043 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1044 $headers = $triple[2]['headers'];
1053 'headers' => $headers
1055 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1057 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1063 * Purge a batch of files from the repo.
1064 * This function can be used to write to otherwise read-only foreign repos.
1065 * This does no locking nor journaling and is intended for purging thumbnails.
1067 * @param array $paths List of virtual URLs or storage paths
1070 public function quickPurgeBatch( array $paths ) {
1071 $status = $this->newGood();
1073 foreach ( $paths as $path ) {
1076 'src' => $this->resolveToStoragePath( $path ),
1077 'ignoreMissingSource' => true
1080 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1086 * Pick a random name in the temp zone and store a file to it.
1087 * Returns a Status object with the file Virtual URL in the value,
1088 * file can later be disposed using FileRepo::freeTemp().
1090 * @param string $originalName The base name of the file as specified
1091 * by the user. The file extension will be maintained.
1092 * @param string $srcPath The current location of the file.
1093 * @return Status Object with the URL in the value.
1095 public function storeTemp( $originalName, $srcPath ) {
1096 $this->assertWritableRepo(); // fail out if read-only
1098 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1099 $hashPath = $this->getHashPath( $originalName );
1100 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1101 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1103 $result = $this->quickImport( $srcPath, $virtualUrl );
1104 $result->value
= $virtualUrl;
1110 * Remove a temporary file or mark it for garbage collection
1112 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1113 * @return bool True on success, false on failure
1115 public function freeTemp( $virtualUrl ) {
1116 $this->assertWritableRepo(); // fail out if read-only
1118 $temp = $this->getVirtualUrl( 'temp' );
1119 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1120 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1125 return $this->quickPurge( $virtualUrl )->isOK();
1129 * Concatenate a list of temporary files into a target file location.
1131 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1132 * @param string $dstPath Target file system path
1133 * @param int $flags Bitwise combination of the following flags:
1134 * self::DELETE_SOURCE Delete the source files on success
1137 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1138 $this->assertWritableRepo(); // fail out if read-only
1140 $status = $this->newGood();
1143 foreach ( $srcPaths as $srcPath ) {
1144 // Resolve source to a storage path if virtual
1145 $source = $this->resolveToStoragePath( $srcPath );
1146 $sources[] = $source; // chunk to merge
1149 // Concatenate the chunks into one FS file
1150 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1151 $status->merge( $this->backend
->concatenate( $params ) );
1152 if ( !$status->isOK() ) {
1156 // Delete the sources if required
1157 if ( $flags & self
::DELETE_SOURCE
) {
1158 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1161 // Make sure status is OK, despite any quickPurgeBatch() fatals
1162 $status->setResult( true );
1168 * Copy or move a file either from a storage path, virtual URL,
1169 * or file system path, into this repository at the specified destination location.
1171 * Returns a Status object. On success, the value contains "new" or
1172 * "archived", to indicate whether the file was new with that name.
1174 * Options to $options include:
1175 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1177 * @param string|FSFile $src The source file system path, storage path, or URL
1178 * @param string $dstRel The destination relative path
1179 * @param string $archiveRel The relative path where the existing file is to
1180 * be archived, if there is one. Relative to the public zone root.
1181 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1182 * that the source file should be deleted if possible
1183 * @param array $options Optional additional parameters
1186 public function publish(
1187 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1189 $this->assertWritableRepo(); // fail out if read-only
1191 $status = $this->publishBatch(
1192 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1193 if ( $status->successCount
== 0 ) {
1194 $status->setOK( false );
1196 if ( isset( $status->value
[0] ) ) {
1197 $status->value
= $status->value
[0];
1199 $status->value
= false;
1206 * Publish a batch of files
1208 * @param array $ntuples (source, dest, archive) triplets or
1209 * (source, dest, archive, options) 4-tuples as per publish().
1210 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1211 * that the source files should be deleted if possible
1212 * @throws MWException
1215 public function publishBatch( array $ntuples, $flags = 0 ) {
1216 $this->assertWritableRepo(); // fail out if read-only
1218 $backend = $this->backend
; // convenience
1219 // Try creating directories
1220 $status = $this->initZones( 'public' );
1221 if ( !$status->isOK() ) {
1225 $status = $this->newGood( [] );
1228 $sourceFSFilesToDelete = []; // cleanup for disk source files
1229 // Validate each triplet and get the store operation...
1230 foreach ( $ntuples as $ntuple ) {
1231 list( $src, $dstRel, $archiveRel ) = $ntuple;
1232 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1234 $options = isset( $ntuple[3] ) ?
$ntuple[3] : [];
1235 // Resolve source to a storage path if virtual
1236 $srcPath = $this->resolveToStoragePath( $srcPath );
1237 if ( !$this->validateFilename( $dstRel ) ) {
1238 throw new MWException( 'Validation error in $dstRel' );
1240 if ( !$this->validateFilename( $archiveRel ) ) {
1241 throw new MWException( 'Validation error in $archiveRel' );
1244 $publicRoot = $this->getZonePath( 'public' );
1245 $dstPath = "$publicRoot/$dstRel";
1246 $archivePath = "$publicRoot/$archiveRel";
1248 $dstDir = dirname( $dstPath );
1249 $archiveDir = dirname( $archivePath );
1250 // Abort immediately on directory creation errors since they're likely to be repetitive
1251 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1252 return $this->newFatal( 'directorycreateerror', $dstDir );
1254 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1255 return $this->newFatal( 'directorycreateerror', $archiveDir );
1258 // Set any desired headers to be use in GET/HEAD responses
1259 $headers = isset( $options['headers'] ) ?
$options['headers'] : [];
1261 // Archive destination file if it exists.
1262 // This will check if the archive file also exists and fail if does.
1263 // This is a sanity check to avoid data loss. On Windows and Linux,
1264 // copy() will overwrite, so the existence check is vulnerable to
1265 // race conditions unless a functioning LockManager is used.
1266 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1270 'dst' => $archivePath,
1271 'ignoreMissingSource' => true
1274 // Copy (or move) the source file to the destination
1275 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1276 if ( $flags & self
::DELETE_SOURCE
) {
1281 'overwrite' => true, // replace current
1282 'headers' => $headers
1289 'overwrite' => true, // replace current
1290 'headers' => $headers
1293 } else { // FS source path
1296 'src' => $src, // prefer FSFile objects
1298 'overwrite' => true, // replace current
1299 'headers' => $headers
1301 if ( $flags & self
::DELETE_SOURCE
) {
1302 $sourceFSFilesToDelete[] = $srcPath;
1307 // Execute the operations for each triplet
1308 $status->merge( $backend->doOperations( $operations ) );
1309 // Find out which files were archived...
1310 foreach ( $ntuples as $i => $ntuple ) {
1311 list( , , $archiveRel ) = $ntuple;
1312 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1313 if ( $this->fileExists( $archivePath ) ) {
1314 $status->value
[$i] = 'archived';
1316 $status->value
[$i] = 'new';
1319 // Cleanup for disk source files...
1320 foreach ( $sourceFSFilesToDelete as $file ) {
1321 Wikimedia\
suppressWarnings();
1322 unlink( $file ); // FS cleanup
1323 Wikimedia\restoreWarnings
();
1330 * Creates a directory with the appropriate zone permissions.
1331 * Callers are responsible for doing read-only and "writable repo" checks.
1333 * @param string $dir Virtual URL (or storage path) of directory to clean
1336 protected function initDirectory( $dir ) {
1337 $path = $this->resolveToStoragePath( $dir );
1338 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1340 $params = [ 'dir' => $path ];
1341 if ( $this->isPrivate
1342 ||
$container === $this->zones
['deleted']['container']
1343 ||
$container === $this->zones
['temp']['container']
1345 # Take all available measures to prevent web accessibility of new deleted
1346 # directories, in case the user has not configured offline storage
1347 $params = [ 'noAccess' => true, 'noListing' => true ] +
$params;
1350 $status = $this->newGood();
1351 $status->merge( $this->backend
->prepare( $params ) );
1357 * Deletes a directory if empty.
1359 * @param string $dir Virtual URL (or storage path) of directory to clean
1362 public function cleanDir( $dir ) {
1363 $this->assertWritableRepo(); // fail out if read-only
1365 $status = $this->newGood();
1366 $status->merge( $this->backend
->clean(
1367 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1373 * Checks existence of a a file
1375 * @param string $file Virtual URL (or storage path) of file to check
1378 public function fileExists( $file ) {
1379 $result = $this->fileExistsBatch( [ $file ] );
1385 * Checks existence of an array of files.
1387 * @param array $files Virtual URLs (or storage paths) of files to check
1388 * @return array Map of files and existence flags, or false
1390 public function fileExistsBatch( array $files ) {
1391 $paths = array_map( [ $this, 'resolveToStoragePath' ], $files );
1392 $this->backend
->preloadFileStat( [ 'srcs' => $paths ] );
1395 foreach ( $files as $key => $file ) {
1396 $path = $this->resolveToStoragePath( $file );
1397 $result[$key] = $this->backend
->fileExists( [ 'src' => $path ] );
1404 * Move a file to the deletion archive.
1405 * If no valid deletion archive exists, this may either delete the file
1406 * or throw an exception, depending on the preference of the repository
1408 * @param mixed $srcRel Relative path for the file to be deleted
1409 * @param mixed $archiveRel Relative path for the archive location.
1410 * Relative to a private archive directory.
1413 public function delete( $srcRel, $archiveRel ) {
1414 $this->assertWritableRepo(); // fail out if read-only
1416 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1420 * Move a group of files to the deletion archive.
1422 * If no valid deletion archive is configured, this may either delete the
1423 * file or throw an exception, depending on the preference of the repository.
1425 * The overwrite policy is determined by the repository -- currently LocalRepo
1426 * assumes a naming scheme in the deleted zone based on content hash, as
1427 * opposed to the public zone which is assumed to be unique.
1429 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1430 * is a two-element array containing the source file path relative to the
1431 * public root in the first element, and the archive file path relative
1432 * to the deleted zone root in the second element.
1433 * @throws MWException
1436 public function deleteBatch( array $sourceDestPairs ) {
1437 $this->assertWritableRepo(); // fail out if read-only
1439 // Try creating directories
1440 $status = $this->initZones( [ 'public', 'deleted' ] );
1441 if ( !$status->isOK() ) {
1445 $status = $this->newGood();
1447 $backend = $this->backend
; // convenience
1449 // Validate filenames and create archive directories
1450 foreach ( $sourceDestPairs as $pair ) {
1451 list( $srcRel, $archiveRel ) = $pair;
1452 if ( !$this->validateFilename( $srcRel ) ) {
1453 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1454 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1455 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1458 $publicRoot = $this->getZonePath( 'public' );
1459 $srcPath = "{$publicRoot}/$srcRel";
1461 $deletedRoot = $this->getZonePath( 'deleted' );
1462 $archivePath = "{$deletedRoot}/{$archiveRel}";
1463 $archiveDir = dirname( $archivePath ); // does not touch FS
1465 // Create destination directories
1466 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1467 return $this->newFatal( 'directorycreateerror', $archiveDir );
1473 'dst' => $archivePath,
1474 // We may have 2+ identical files being deleted,
1475 // all of which will map to the same destination file
1476 'overwriteSame' => true // also see T33792
1480 // Move the files by execute the operations for each pair.
1481 // We're now committed to returning an OK result, which will
1482 // lead to the files being moved in the DB also.
1483 $opts = [ 'force' => true ];
1484 $status->merge( $backend->doOperations( $operations, $opts ) );
1490 * Delete files in the deleted directory if they are not referenced in the filearchive table
1493 * @param array $storageKeys
1495 public function cleanupDeletedBatch( array $storageKeys ) {
1496 $this->assertWritableRepo();
1500 * Get a relative path for a deletion archive key,
1501 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1503 * @param string $key
1504 * @throws MWException
1507 public function getDeletedHashPath( $key ) {
1508 if ( strlen( $key ) < 31 ) {
1509 throw new MWException( "Invalid storage key '$key'." );
1512 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1513 $path .= $key[$i] . '/';
1520 * If a path is a virtual URL, resolve it to a storage path.
1521 * Otherwise, just return the path as it is.
1523 * @param string $path
1525 * @throws MWException
1527 protected function resolveToStoragePath( $path ) {
1528 if ( $this->isVirtualUrl( $path ) ) {
1529 return $this->resolveVirtualUrl( $path );
1536 * Get a local FS copy of a file with a given virtual URL/storage path.
1537 * Temporary files may be purged when the file object falls out of scope.
1539 * @param string $virtualUrl
1540 * @return TempFSFile|null Returns null on failure
1542 public function getLocalCopy( $virtualUrl ) {
1543 $path = $this->resolveToStoragePath( $virtualUrl );
1545 return $this->backend
->getLocalCopy( [ 'src' => $path ] );
1549 * Get a local FS file with a given virtual URL/storage path.
1550 * The file is either an original or a copy. It should not be changed.
1551 * Temporary files may be purged when the file object falls out of scope.
1553 * @param string $virtualUrl
1554 * @return FSFile|null Returns null on failure.
1556 public function getLocalReference( $virtualUrl ) {
1557 $path = $this->resolveToStoragePath( $virtualUrl );
1559 return $this->backend
->getLocalReference( [ 'src' => $path ] );
1563 * Get properties of a file with a given virtual URL/storage path.
1564 * Properties should ultimately be obtained via FSFile::getProps().
1566 * @param string $virtualUrl
1569 public function getFileProps( $virtualUrl ) {
1570 $fsFile = $this->getLocalReference( $virtualUrl );
1571 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1573 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1575 $props = $mwProps->newPlaceholderProps();
1582 * Get the timestamp of a file with a given virtual URL/storage path
1584 * @param string $virtualUrl
1585 * @return string|bool False on failure
1587 public function getFileTimestamp( $virtualUrl ) {
1588 $path = $this->resolveToStoragePath( $virtualUrl );
1590 return $this->backend
->getFileTimestamp( [ 'src' => $path ] );
1594 * Get the size of a file with a given virtual URL/storage path
1596 * @param string $virtualUrl
1597 * @return int|bool False on failure
1599 public function getFileSize( $virtualUrl ) {
1600 $path = $this->resolveToStoragePath( $virtualUrl );
1602 return $this->backend
->getFileSize( [ 'src' => $path ] );
1606 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1608 * @param string $virtualUrl
1609 * @return string|bool
1611 public function getFileSha1( $virtualUrl ) {
1612 $path = $this->resolveToStoragePath( $virtualUrl );
1614 return $this->backend
->getFileSha1Base36( [ 'src' => $path ] );
1618 * Attempt to stream a file with the given virtual URL/storage path
1620 * @param string $virtualUrl
1621 * @param array $headers Additional HTTP headers to send on success
1622 * @param array $optHeaders HTTP request headers (if-modified-since, range, ...)
1626 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1627 $path = $this->resolveToStoragePath( $virtualUrl );
1628 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1630 // T172851: HHVM does not flush the output properly, causing OOM
1631 ob_start( null, 1048576 );
1632 ob_implicit_flush( true );
1634 $status = $this->newGood();
1635 $status->merge( $this->backend
->streamFile( $params ) );
1643 * Attempt to stream a file with the given virtual URL/storage path
1645 * @deprecated since 1.26, use streamFileWithStatus
1646 * @param string $virtualUrl
1647 * @param array $headers Additional HTTP headers to send on success
1648 * @return bool Success
1650 public function streamFile( $virtualUrl, $headers = [] ) {
1651 return $this->streamFileWithStatus( $virtualUrl, $headers )->isOK();
1655 * Call a callback function for every public regular file in the repository.
1656 * This only acts on the current version of files, not any old versions.
1657 * May use either the database or the filesystem.
1659 * @param callable $callback
1662 public function enumFiles( $callback ) {
1663 $this->enumFilesInStorage( $callback );
1667 * Call a callback function for every public file in the repository.
1668 * May use either the database or the filesystem.
1670 * @param callable $callback
1673 protected function enumFilesInStorage( $callback ) {
1674 $publicRoot = $this->getZonePath( 'public' );
1675 $numDirs = 1 << ( $this->hashLevels
* 4 );
1676 // Use a priori assumptions about directory structure
1677 // to reduce the tree height of the scanning process.
1678 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1679 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1680 $path = $publicRoot;
1681 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1682 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1684 $iterator = $this->backend
->getFileList( [ 'dir' => $path ] );
1685 foreach ( $iterator as $name ) {
1686 // Each item returned is a public file
1687 call_user_func( $callback, "{$path}/{$name}" );
1693 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1695 * @param string $filename
1698 public function validateFilename( $filename ) {
1699 if ( strval( $filename ) == '' ) {
1703 return FileBackend
::isPathTraversalFree( $filename );
1707 * Get a callback function to use for cleaning error message parameters
1711 function getErrorCleanupFunction() {
1712 switch ( $this->pathDisclosureProtection
) {
1714 case 'simple': // b/c
1715 $callback = [ $this, 'passThrough' ];
1717 default: // 'paranoid'
1718 $callback = [ $this, 'paranoidClean' ];
1724 * Path disclosure protection function
1726 * @param string $param
1729 function paranoidClean( $param ) {
1734 * Path disclosure protection function
1736 * @param string $param
1739 function passThrough( $param ) {
1744 * Create a new fatal error
1746 * @param string $message
1749 public function newFatal( $message /*, parameters...*/ ) {
1750 $status = call_user_func_array( [ Status
::class, 'newFatal' ], func_get_args() );
1751 $status->cleanCallback
= $this->getErrorCleanupFunction();
1757 * Create a new good result
1759 * @param null|string $value
1762 public function newGood( $value = null ) {
1763 $status = Status
::newGood( $value );
1764 $status->cleanCallback
= $this->getErrorCleanupFunction();
1770 * Checks if there is a redirect named as $title. If there is, return the
1771 * title object. If not, return false.
1774 * @param Title $title Title of image
1777 public function checkRedirect( Title
$title ) {
1782 * Invalidates image redirect cache related to that image
1783 * Doesn't do anything for repositories that don't support image redirects.
1786 * @param Title $title Title of image
1788 public function invalidateImageRedirect( Title
$title ) {
1792 * Get the human-readable name of the repo
1796 public function getDisplayName() {
1799 if ( $this->isLocal() ) {
1803 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1804 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1808 * Get the portion of the file that contains the origin file name.
1809 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1811 * @param string $name
1814 public function nameForThumb( $name ) {
1815 if ( strlen( $name ) > $this->abbrvThreshold
) {
1816 $ext = FileBackend
::extensionFromPath( $name );
1817 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1824 * Returns true if this the local file repository.
1828 public function isLocal() {
1829 return $this->getName() == 'local';
1833 * Get a key on the primary cache for this repository.
1834 * Returns false if the repository's cache is not accessible at this site.
1835 * The parameters are the parts of the key, as for wfMemcKey().
1840 public function getSharedCacheKey( /*...*/ ) {
1845 * Get a key for this repo in the local cache domain. These cache keys are
1846 * not shared with remote instances of the repo.
1847 * The parameters are the parts of the key, as for wfMemcKey().
1851 public function getLocalCacheKey( /*...*/ ) {
1852 $args = func_get_args();
1853 array_unshift( $args, 'filerepo', $this->getName() );
1855 return call_user_func_array( 'wfMemcKey', $args );
1859 * Get a temporary private FileRepo associated with this repo.
1861 * Files will be created in the temp zone of this repo.
1862 * It will have the same backend as this repo.
1864 * @return TempFileRepo
1866 public function getTempRepo() {
1867 return new TempFileRepo( [
1868 'name' => "{$this->name}-temp",
1869 'backend' => $this->backend
,
1872 // Same place storeTemp() uses in the base repo, though
1873 // the path hashing is mismatched, which is annoying.
1874 'container' => $this->zones
['temp']['container'],
1875 'directory' => $this->zones
['temp']['directory']
1878 'container' => $this->zones
['temp']['container'],
1879 'directory' => $this->zones
['temp']['directory'] == ''
1881 : $this->zones
['temp']['directory'] . '/thumb'
1884 'container' => $this->zones
['temp']['container'],
1885 'directory' => $this->zones
['temp']['directory'] == ''
1887 : $this->zones
['temp']['directory'] . '/transcoded'
1890 'hashLevels' => $this->hashLevels
, // performance
1891 'isPrivate' => true // all in temp zone
1896 * Get an UploadStash associated with this repo.
1899 * @return UploadStash
1901 public function getUploadStash( User
$user = null ) {
1902 return new UploadStash( $this, $user );
1906 * Throw an exception if this repo is read-only by design.
1907 * This does not and should not check getReadOnlyReason().
1910 * @throws MWException
1912 protected function assertWritableRepo() {
1916 * Return information about the repository.
1921 public function getInfo() {
1923 'name' => $this->getName(),
1924 'displayname' => $this->getDisplayName(),
1925 'rootUrl' => $this->getZoneUrl( 'public' ),
1926 'local' => $this->isLocal(),
1929 $optionalSettings = [
1930 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1931 'fetchDescription', 'descriptionCacheExpiry', 'scriptExtension', 'favicon'
1933 foreach ( $optionalSettings as $k ) {
1934 if ( isset( $this->$k ) ) {
1935 $ret[$k] = $this->$k;
1943 * Returns whether or not storage is SHA-1 based
1946 public function hasSha1Storage() {
1947 return $this->hasSha1Storage
;
1951 * Returns whether or not repo supports having originals SHA-1s in the thumb URLs
1954 public function supportsSha1URLs() {
1955 return $this->supportsSha1URLs
;