8611238d8eef798128b5269da6ebbb528154c152
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 /** @var FileBackend */
46 /** @var Array Map of zones to config */
47 protected $zones = array();
49 /** @var string URL of thumb.php */
50 protected $thumbScriptUrl;
52 /** @var bool Whether to skip media file transformation on parse and rely
53 * on a 404 handler instead. */
54 protected $transformVia404;
56 /** @var string URL of image description pages, e.g.
57 * http://en.wikipedia.org/wiki/File:
59 protected $descBaseUrl;
61 /** @var string URL of the MediaWiki installation, equivalent to
62 * $wgScriptPath, e.g. https://en.wikipedia.org/w
64 protected $scriptDirUrl;
66 /** @var string Script extension of the MediaWiki installation, equivalent
67 * to $wgScriptExtension, e.g. .php5 defaults to .php */
68 protected $scriptExtension;
70 /** @var string Equivalent to $wgArticlePath, e.g. http://en.wikipedia.org/wiki/$1 */
71 protected $articleUrl;
73 /** @var bool Whether to fetch commons image description pages and display them on the local wiki */
74 public $fetchDescription;
76 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
77 * determines whether filenames implicitly start with a capital letter.
78 * The current implementation may give incorrect description page links
79 * when the local $wgCapitalLinks and initialCapital are mismatched.
81 protected $initialCapital;
83 /** @var string May be 'paranoid' to remove all parameters from error
84 * messages, 'none' to leave the paths in unchanged, or 'simple' to
85 * replace paths with placeholders. Default for LocalRepo is
88 protected $pathDisclosureProtection = 'simple';
91 public $descriptionCacheExpiry;
93 /** @var bool Public zone URL. */
96 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
99 /** @var int The number of directory levels for hash-based division of files */
100 protected $hashLevels;
102 /** @var int The number of directory levels for hash-based division of deleted files */
103 protected $deletedHashLevels;
105 /** @var int File names over this size will use the short form of thumbnail
106 * names. Short thumbnail names only have the width, parameters, and the
109 protected $abbrvThreshold;
112 * Factory functions for creating new files
113 * Override these in the base class
115 protected $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
116 protected $oldFileFactory = false;
117 protected $fileFactoryKey = false;
118 protected $oldFileFactoryKey = false;
121 * @param $info array|null
122 * @throws MWException
124 public function __construct( array $info = null ) {
125 // Verify required settings presence
128 ||
!array_key_exists( 'name', $info )
129 ||
!array_key_exists( 'backend', $info )
131 throw new MWException( __CLASS__
.
132 " requires an array of options having both 'name' and 'backend' keys.\n" );
136 $this->name
= $info['name'];
137 if ( $info['backend'] instanceof FileBackend
) {
138 $this->backend
= $info['backend']; // useful for testing
140 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
143 // Optional settings that can have no value
144 $optionalSettings = array(
145 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
146 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
149 foreach ( $optionalSettings as $var ) {
150 if ( isset( $info[$var] ) ) {
151 $this->$var = $info[$var];
155 // Optional settings that have a default
156 $this->initialCapital
= isset( $info['initialCapital'] )
157 ?
$info['initialCapital']
158 : MWNamespace
::isCapitalized( NS_FILE
);
159 $this->url
= isset( $info['url'] )
161 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
162 if ( isset( $info['thumbUrl'] ) ) {
163 $this->thumbUrl
= $info['thumbUrl'];
165 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
167 $this->hashLevels
= isset( $info['hashLevels'] )
168 ?
$info['hashLevels']
170 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
171 ?
$info['deletedHashLevels']
173 $this->transformVia404
= !empty( $info['transformVia404'] );
174 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
175 ?
$info['abbrvThreshold']
177 $this->isPrivate
= !empty( $info['isPrivate'] );
178 // Give defaults for the basic zones...
179 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
180 foreach ( array( 'public', 'thumb', 'transcoded', 'temp', 'deleted' ) as $zone ) {
181 if ( !isset( $this->zones
[$zone]['container'] ) ) {
182 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
184 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
185 $this->zones
[$zone]['directory'] = '';
187 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
188 $this->zones
[$zone]['urlsByExt'] = array();
194 * Get the file backend instance. Use this function wisely.
196 * @return FileBackend
198 public function getBackend() {
199 return $this->backend
;
203 * Get an explanatory message if this repo is read-only.
204 * This checks if an administrator disabled writes to the backend.
206 * @return string|bool Returns false if the repo is not read-only
208 public function getReadOnlyReason() {
209 return $this->backend
->getReadOnlyReason();
213 * Check if a single zone or list of zones is defined for usage
215 * @param array $doZones Only do a particular zones
216 * @throws MWException
219 protected function initZones( $doZones = array() ) {
220 $status = $this->newGood();
221 foreach ( (array)$doZones as $zone ) {
222 $root = $this->getZonePath( $zone );
223 if ( $root === null ) {
224 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
232 * Determine if a string is an mwrepo:// URL
237 public static function isVirtualUrl( $url ) {
238 return substr( $url, 0, 9 ) == 'mwrepo://';
242 * Get a URL referring to this repository, with the private mwrepo protocol.
243 * The suffix, if supplied, is considered to be unencoded, and will be
244 * URL-encoded before being returned.
246 * @param $suffix string|bool
249 public function getVirtualUrl( $suffix = false ) {
250 $path = 'mwrepo://' . $this->name
;
251 if ( $suffix !== false ) {
252 $path .= '/' . rawurlencode( $suffix );
259 * Get the URL corresponding to one of the four basic zones
261 * @param string $zone One of: public, deleted, temp, thumb
262 * @param string|null $ext Optional file extension
263 * @return string|bool
265 public function getZoneUrl( $zone, $ext = null ) {
266 if ( in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) ) ) {
267 // standard public zones
268 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
269 // custom URL for extension/zone
270 return $this->zones
[$zone]['urlsByExt'][$ext];
271 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
272 // custom URL for zone
273 return $this->zones
[$zone]['url'];
280 return "{$this->url}/temp";
282 return false; // no public URL
284 return $this->thumbUrl
;
286 return "{$this->url}/transcoded";
293 * Get the thumb zone URL configured to be handled by scripts like thumb_handler.php.
294 * This is probably only useful for internal requests, such as from a fast frontend server
295 * to a slower backend server.
297 * Large sites may use a different host name for uploads than for wikis. In any case, the
298 * wiki configuration is needed in order to use thumb.php. To avoid extracting the wiki ID
299 * from the URL path, one can configure thumb_handler.php to recognize a special path on the
300 * same host name as the wiki that is used for viewing thumbnails.
302 * @param string $zone one of: public, deleted, temp, thumb
303 * @return String or false
305 public function getZoneHandlerUrl( $zone ) {
306 if ( isset( $this->zones
[$zone]['handlerUrl'] )
307 && in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) )
309 return $this->zones
[$zone]['handlerUrl'];
316 * Get the backend storage path corresponding to a virtual URL.
317 * Use this function wisely.
320 * @throws MWException
323 public function resolveVirtualUrl( $url ) {
324 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
325 throw new MWException( __METHOD__
. ': unknown protocol' );
327 $bits = explode( '/', substr( $url, 9 ), 3 );
328 if ( count( $bits ) != 3 ) {
329 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
331 list( $repo, $zone, $rel ) = $bits;
332 if ( $repo !== $this->name
) {
333 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
335 $base = $this->getZonePath( $zone );
337 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
340 return $base . '/' . rawurldecode( $rel );
344 * The the storage container and base path of a zone
346 * @param $zone string
347 * @return Array (container, base path) or (null, null)
349 protected function getZoneLocation( $zone ) {
350 if ( !isset( $this->zones
[$zone] ) ) {
351 return array( null, null ); // bogus
354 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
358 * Get the storage path corresponding to one of the zones
360 * @param $zone string
361 * @return string|null Returns null if the zone is not defined
363 public function getZonePath( $zone ) {
364 list( $container, $base ) = $this->getZoneLocation( $zone );
365 if ( $container === null ||
$base === null ) {
368 $backendName = $this->backend
->getName();
369 if ( $base != '' ) { // may not be set
373 return "mwstore://$backendName/{$container}{$base}";
377 * Create a new File object from the local repository
379 * @param $title Mixed: Title object or string
380 * @param $time Mixed: Time at which the image was uploaded.
381 * If this is specified, the returned object will be an
382 * instance of the repository's old file class instead of a
383 * current file. Repositories not supporting version control
384 * should return false if this parameter is set.
385 * @return File|null A File, or null if passed an invalid Title
387 public function newFile( $title, $time = false ) {
388 $title = File
::normalizeTitle( $title );
393 if ( $this->oldFileFactory
) {
394 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
399 return call_user_func( $this->fileFactory
, $title, $this );
404 * Find an instance of the named file created at the specified time
405 * Returns false if the file does not exist. Repositories not supporting
406 * version control should return false if the time is specified.
408 * @param $title Mixed: Title object or string
409 * @param array $options Associative array of options:
410 * time: requested time for a specific file version, or false for the
411 * current version. An image object will be returned which was
412 * created at the specified time (which may be archived or current).
414 * ignoreRedirect: If true, do not follow file redirects
416 * private: If true, return restricted (deleted) files if the current
417 * user is allowed to view them. Otherwise, such files will not
419 * @return File|bool False on failure
421 public function findFile( $title, $options = array() ) {
422 $title = File
::normalizeTitle( $title );
426 $time = isset( $options['time'] ) ?
$options['time'] : false;
427 # First try the current version of the file to see if it precedes the timestamp
428 $img = $this->newFile( $title );
432 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
435 # Now try an old version of the file
436 if ( $time !== false ) {
437 $img = $this->newFile( $title, $time );
438 if ( $img && $img->exists() ) {
439 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
440 return $img; // always OK
441 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
448 if ( !empty( $options['ignoreRedirect'] ) ) {
451 $redir = $this->checkRedirect( $title );
452 if ( $redir && $title->getNamespace() == NS_FILE
) {
453 $img = $this->newFile( $redir );
457 if ( $img->exists() ) {
458 $img->redirectedFrom( $title->getDBkey() );
468 * Find many files at once.
470 * @param array $items An array of titles, or an array of findFile() options with
471 * the "title" option giving the title. Example:
473 * $findItem = array( 'title' => $title, 'private' => true );
474 * $findBatch = array( $findItem );
475 * $repo->findFiles( $findBatch );
478 public function findFiles( array $items ) {
480 foreach ( $items as $item ) {
481 if ( is_array( $item ) ) {
482 $title = $item['title'];
484 unset( $options['title'] );
489 $file = $this->findFile( $title, $options );
491 $result[$file->getTitle()->getDBkey()] = $file;
499 * Find an instance of the file with this key, created at the specified time
500 * Returns false if the file does not exist. Repositories not supporting
501 * version control should return false if the time is specified.
503 * @param string $sha1 base 36 SHA-1 hash
504 * @param array $options Option array, same as findFile().
505 * @return File|bool False on failure
507 public function findFileFromKey( $sha1, $options = array() ) {
508 $time = isset( $options['time'] ) ?
$options['time'] : false;
509 # First try to find a matching current version of a file...
510 if ( $this->fileFactoryKey
) {
511 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
513 return false; // find-by-sha1 not supported
515 if ( $img && $img->exists() ) {
518 # Now try to find a matching old version of a file...
519 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
520 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
521 if ( $img && $img->exists() ) {
522 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
523 return $img; // always OK
524 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
534 * Get an array or iterator of file objects for files that have a given
535 * SHA-1 content hash.
541 public function findBySha1( $hash ) {
546 * Get an array of arrays or iterators of file objects for files that
547 * have the given SHA-1 content hashes.
549 * @param array $hashes An array of hashes
550 * @return array An Array of arrays or iterators of file objects and the hash as key
552 public function findBySha1s( array $hashes ) {
554 foreach ( $hashes as $hash ) {
555 $files = $this->findBySha1( $hash );
556 if ( count( $files ) ) {
557 $result[$hash] = $files;
565 * Return an array of files where the name starts with $prefix.
568 * @param string $prefix The prefix to search for
569 * @param int $limit The maximum amount of files to return
572 public function findFilesByPrefix( $prefix, $limit ) {
577 * Get the public root URL of the repository
579 * @deprecated since 1.20
582 public function getRootUrl() {
583 return $this->getZoneUrl( 'public' );
587 * Get the URL of thumb.php
591 public function getThumbScriptUrl() {
592 return $this->thumbScriptUrl
;
596 * Returns true if the repository can transform files via a 404 handler
600 public function canTransformVia404() {
601 return $this->transformVia404
;
605 * Get the name of a file from its title object
607 * @param $title Title
610 public function getNameFromTitle( Title
$title ) {
612 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
613 $name = $title->getUserCaseDBKey();
614 if ( $this->initialCapital
) {
615 $name = $wgContLang->ucfirst( $name );
618 $name = $title->getDBkey();
625 * Get the public zone root storage directory of the repository
629 public function getRootDirectory() {
630 return $this->getZonePath( 'public' );
634 * Get a relative path including trailing slash, e.g. f/fa/
635 * If the repo is not hashed, returns an empty string
637 * @param string $name Name of file
640 public function getHashPath( $name ) {
641 return self
::getHashPathForLevel( $name, $this->hashLevels
);
645 * Get a relative path including trailing slash, e.g. f/fa/
646 * If the repo is not hashed, returns an empty string
648 * @param string $suffix Basename of file from FileRepo::storeTemp()
651 public function getTempHashPath( $suffix ) {
652 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
653 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
654 return self
::getHashPathForLevel( $name, $this->hashLevels
);
662 protected static function getHashPathForLevel( $name, $levels ) {
663 if ( $levels == 0 ) {
666 $hash = md5( $name );
668 for ( $i = 1; $i <= $levels; $i++
) {
669 $path .= substr( $hash, 0, $i ) . '/';
677 * Get the number of hash directory levels
681 public function getHashLevels() {
682 return $this->hashLevels
;
686 * Get the name of this repository, as specified by $info['name]' to the constructor
690 public function getName() {
695 * Make an url to this repo
697 * @param $query mixed Query string to append
698 * @param string $entry Entry point; defaults to index
699 * @return string|bool False on failure
701 public function makeUrl( $query = '', $entry = 'index' ) {
702 if ( isset( $this->scriptDirUrl
) ) {
703 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
705 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
712 * Get the URL of an image description page. May return false if it is
713 * unknown or not applicable. In general this should only be called by the
714 * File class, since it may return invalid results for certain kinds of
715 * repositories. Use File::getDescriptionUrl() in user code.
717 * In particular, it uses the article paths as specified to the repository
718 * constructor, whereas local repositories use the local Title functions.
720 * @param $name string
723 public function getDescriptionUrl( $name ) {
724 $encName = wfUrlencode( $name );
725 if ( !is_null( $this->descBaseUrl
) ) {
726 # "http://example.com/wiki/File:"
727 return $this->descBaseUrl
. $encName;
729 if ( !is_null( $this->articleUrl
) ) {
730 # "http://example.com/wiki/$1"
732 # We use "Image:" as the canonical namespace for
733 # compatibility across all MediaWiki versions.
734 return str_replace( '$1',
735 "Image:$encName", $this->articleUrl
);
737 if ( !is_null( $this->scriptDirUrl
) ) {
738 # "http://example.com/w"
740 # We use "Image:" as the canonical namespace for
741 # compatibility across all MediaWiki versions,
742 # and just sort of hope index.php is right. ;)
743 return $this->makeUrl( "title=Image:$encName" );
750 * Get the URL of the content-only fragment of the description page. For
751 * MediaWiki this means action=render. This should only be called by the
752 * repository's file class, since it may return invalid results. User code
753 * should use File::getDescriptionText().
755 * @param string $name name of image to fetch
756 * @param string $lang language to fetch it in, if any.
759 public function getDescriptionRenderUrl( $name, $lang = null ) {
760 $query = 'action=render';
761 if ( !is_null( $lang ) ) {
762 $query .= '&uselang=' . $lang;
764 if ( isset( $this->scriptDirUrl
) ) {
765 return $this->makeUrl(
767 wfUrlencode( 'Image:' . $name ) .
770 $descUrl = $this->getDescriptionUrl( $name );
772 return wfAppendQuery( $descUrl, $query );
780 * Get the URL of the stylesheet to apply to description pages
782 * @return string|bool False on failure
784 public function getDescriptionStylesheetUrl() {
785 if ( isset( $this->scriptDirUrl
) ) {
786 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
787 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
794 * Store a file to a given destination.
796 * @param string $srcPath source file system path, storage path, or virtual URL
797 * @param string $dstZone destination zone
798 * @param string $dstRel destination relative path
799 * @param $flags Integer: bitwise combination of the following flags:
800 * self::DELETE_SOURCE Delete the source file after upload
801 * self::OVERWRITE Overwrite an existing destination file instead of failing
802 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
803 * same contents as the source
804 * self::SKIP_LOCKING Skip any file locking when doing the store
805 * @return FileRepoStatus
807 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
808 $this->assertWritableRepo(); // fail out if read-only
810 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
811 if ( $status->successCount
== 0 ) {
819 * Store a batch of files
821 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
822 * @param $flags Integer: bitwise combination of the following flags:
823 * self::DELETE_SOURCE Delete the source file after upload
824 * self::OVERWRITE Overwrite an existing destination file instead of failing
825 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
826 * same contents as the source
827 * self::SKIP_LOCKING Skip any file locking when doing the store
828 * @throws MWException
829 * @return FileRepoStatus
831 public function storeBatch( array $triplets, $flags = 0 ) {
832 $this->assertWritableRepo(); // fail out if read-only
834 $status = $this->newGood();
835 $backend = $this->backend
; // convenience
837 $operations = array();
838 $sourceFSFilesToDelete = array(); // cleanup for disk source files
839 // Validate each triplet and get the store operation...
840 foreach ( $triplets as $triplet ) {
841 list( $srcPath, $dstZone, $dstRel ) = $triplet;
843 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
846 // Resolve destination path
847 $root = $this->getZonePath( $dstZone );
849 throw new MWException( "Invalid zone: $dstZone" );
851 if ( !$this->validateFilename( $dstRel ) ) {
852 throw new MWException( 'Validation error in $dstRel' );
854 $dstPath = "$root/$dstRel";
855 $dstDir = dirname( $dstPath );
856 // Create destination directories for this triplet
857 if ( !$this->initDirectory( $dstDir )->isOK() ) {
858 return $this->newFatal( 'directorycreateerror', $dstDir );
861 // Resolve source to a storage path if virtual
862 $srcPath = $this->resolveToStoragePath( $srcPath );
864 // Get the appropriate file operation
865 if ( FileBackend
::isStoragePath( $srcPath ) ) {
866 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
869 if ( $flags & self
::DELETE_SOURCE
) {
870 $sourceFSFilesToDelete[] = $srcPath;
873 $operations[] = array(
877 'overwrite' => $flags & self
::OVERWRITE
,
878 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
882 // Execute the store operation for each triplet
883 $opts = array( 'force' => true );
884 if ( $flags & self
::SKIP_LOCKING
) {
885 $opts['nonLocking'] = true;
887 $status->merge( $backend->doOperations( $operations, $opts ) );
888 // Cleanup for disk source files...
889 foreach ( $sourceFSFilesToDelete as $file ) {
890 wfSuppressWarnings();
891 unlink( $file ); // FS cleanup
899 * Deletes a batch of files.
900 * Each file can be a (zone, rel) pair, virtual url, storage path.
901 * It will try to delete each file, but ignores any errors that may occur.
903 * @param array $files List of files to delete
904 * @param $flags Integer: bitwise combination of the following flags:
905 * self::SKIP_LOCKING Skip any file locking when doing the deletions
906 * @return FileRepoStatus
908 public function cleanupBatch( array $files, $flags = 0 ) {
909 $this->assertWritableRepo(); // fail out if read-only
911 $status = $this->newGood();
913 $operations = array();
914 foreach ( $files as $path ) {
915 if ( is_array( $path ) ) {
916 // This is a pair, extract it
917 list( $zone, $rel ) = $path;
918 $path = $this->getZonePath( $zone ) . "/$rel";
920 // Resolve source to a storage path if virtual
921 $path = $this->resolveToStoragePath( $path );
923 $operations[] = array( 'op' => 'delete', 'src' => $path );
925 // Actually delete files from storage...
926 $opts = array( 'force' => true );
927 if ( $flags & self
::SKIP_LOCKING
) {
928 $opts['nonLocking'] = true;
930 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
936 * Import a file from the local file system into the repo.
937 * This does no locking nor journaling and overrides existing files.
938 * This function can be used to write to otherwise read-only foreign repos.
939 * This is intended for copying generated thumbnails into the repo.
941 * @param string $src Source file system path, storage path, or virtual URL
942 * @param string $dst Virtual URL or storage path
943 * @param string|null $disposition Content-Disposition if given and supported
944 * @return FileRepoStatus
946 final public function quickImport( $src, $dst, $disposition = null ) {
947 return $this->quickImportBatch( array( array( $src, $dst, $disposition ) ) );
951 * Purge a file from the repo. This does no locking nor journaling.
952 * This function can be used to write to otherwise read-only foreign repos.
953 * This is intended for purging thumbnails.
955 * @param string $path Virtual URL or storage path
956 * @return FileRepoStatus
958 final public function quickPurge( $path ) {
959 return $this->quickPurgeBatch( array( $path ) );
963 * Deletes a directory if empty.
964 * This function can be used to write to otherwise read-only foreign repos.
966 * @param string $dir Virtual URL (or storage path) of directory to clean
969 public function quickCleanDir( $dir ) {
970 $status = $this->newGood();
971 $status->merge( $this->backend
->clean(
972 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
978 * Import a batch of files from the local file system into the repo.
979 * This does no locking nor journaling and overrides existing files.
980 * This function can be used to write to otherwise read-only foreign repos.
981 * This is intended for copying generated thumbnails into the repo.
983 * All path parameters may be a file system path, storage path, or virtual URL.
984 * When "dispositions" are given they are used as Content-Disposition if supported.
986 * @param array $triples List of (source path, destination path, disposition)
987 * @return FileRepoStatus
989 public function quickImportBatch( array $triples ) {
990 $status = $this->newGood();
991 $operations = array();
992 foreach ( $triples as $triple ) {
993 list( $src, $dst ) = $triple;
994 $src = $this->resolveToStoragePath( $src );
995 $dst = $this->resolveToStoragePath( $dst );
996 $operations[] = array(
997 'op' => FileBackend
::isStoragePath( $src ) ?
'copy' : 'store',
1000 'disposition' => isset( $triple[2] ) ?
$triple[2] : null
1002 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1004 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1010 * Purge a batch of files from the repo.
1011 * This function can be used to write to otherwise read-only foreign repos.
1012 * This does no locking nor journaling and is intended for purging thumbnails.
1014 * @param array $paths List of virtual URLs or storage paths
1015 * @return FileRepoStatus
1017 public function quickPurgeBatch( array $paths ) {
1018 $status = $this->newGood();
1019 $operations = array();
1020 foreach ( $paths as $path ) {
1021 $operations[] = array(
1023 'src' => $this->resolveToStoragePath( $path ),
1024 'ignoreMissingSource' => true
1027 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1033 * Pick a random name in the temp zone and store a file to it.
1034 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1035 * file can later be disposed using FileRepo::freeTemp().
1037 * @param string $originalName the base name of the file as specified
1038 * by the user. The file extension will be maintained.
1039 * @param string $srcPath the current location of the file.
1040 * @return FileRepoStatus object with the URL in the value.
1042 public function storeTemp( $originalName, $srcPath ) {
1043 $this->assertWritableRepo(); // fail out if read-only
1045 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1046 $hashPath = $this->getHashPath( $originalName );
1047 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1048 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1050 $result = $this->quickImport( $srcPath, $virtualUrl );
1051 $result->value
= $virtualUrl;
1057 * Remove a temporary file or mark it for garbage collection
1059 * @param string $virtualUrl the virtual URL returned by FileRepo::storeTemp()
1060 * @return Boolean: true on success, false on failure
1062 public function freeTemp( $virtualUrl ) {
1063 $this->assertWritableRepo(); // fail out if read-only
1065 $temp = $this->getVirtualUrl( 'temp' );
1066 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1067 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1072 return $this->quickPurge( $virtualUrl )->isOK();
1076 * Concatenate a list of temporary files into a target file location.
1078 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1079 * @param string $dstPath Target file system path
1080 * @param $flags Integer: bitwise combination of the following flags:
1081 * self::DELETE_SOURCE Delete the source files
1082 * @return FileRepoStatus
1084 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1085 $this->assertWritableRepo(); // fail out if read-only
1087 $status = $this->newGood();
1090 foreach ( $srcPaths as $srcPath ) {
1091 // Resolve source to a storage path if virtual
1092 $source = $this->resolveToStoragePath( $srcPath );
1093 $sources[] = $source; // chunk to merge
1096 // Concatenate the chunks into one FS file
1097 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1098 $status->merge( $this->backend
->concatenate( $params ) );
1099 if ( !$status->isOK() ) {
1103 // Delete the sources if required
1104 if ( $flags & self
::DELETE_SOURCE
) {
1105 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1108 // Make sure status is OK, despite any quickPurgeBatch() fatals
1109 $status->setResult( true );
1115 * Copy or move a file either from a storage path, virtual URL,
1116 * or file system path, into this repository at the specified destination location.
1118 * Returns a FileRepoStatus object. On success, the value contains "new" or
1119 * "archived", to indicate whether the file was new with that name.
1121 * Options to $options include:
1122 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1124 * @param string $srcPath the source file system path, storage path, or URL
1125 * @param string $dstRel the destination relative path
1126 * @param string $archiveRel the relative path where the existing file is to
1127 * be archived, if there is one. Relative to the public zone root.
1128 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1129 * that the source file should be deleted if possible
1130 * @param array $options Optional additional parameters
1131 * @return FileRepoStatus
1133 public function publish(
1134 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1136 $this->assertWritableRepo(); // fail out if read-only
1138 $status = $this->publishBatch(
1139 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1140 if ( $status->successCount
== 0 ) {
1141 $status->ok
= false;
1143 if ( isset( $status->value
[0] ) ) {
1144 $status->value
= $status->value
[0];
1146 $status->value
= false;
1153 * Publish a batch of files
1155 * @param array $ntuples (source, dest, archive) triplets or
1156 * (source, dest, archive, options) 4-tuples as per publish().
1157 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1158 * that the source files should be deleted if possible
1159 * @throws MWException
1160 * @return FileRepoStatus
1162 public function publishBatch( array $ntuples, $flags = 0 ) {
1163 $this->assertWritableRepo(); // fail out if read-only
1165 $backend = $this->backend
; // convenience
1166 // Try creating directories
1167 $status = $this->initZones( 'public' );
1168 if ( !$status->isOK() ) {
1172 $status = $this->newGood( array() );
1174 $operations = array();
1175 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1176 // Validate each triplet and get the store operation...
1177 foreach ( $ntuples as $ntuple ) {
1178 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1179 $options = isset( $ntuple[3] ) ?
$ntuple[3] : array();
1180 // Resolve source to a storage path if virtual
1181 $srcPath = $this->resolveToStoragePath( $srcPath );
1182 if ( !$this->validateFilename( $dstRel ) ) {
1183 throw new MWException( 'Validation error in $dstRel' );
1185 if ( !$this->validateFilename( $archiveRel ) ) {
1186 throw new MWException( 'Validation error in $archiveRel' );
1189 $publicRoot = $this->getZonePath( 'public' );
1190 $dstPath = "$publicRoot/$dstRel";
1191 $archivePath = "$publicRoot/$archiveRel";
1193 $dstDir = dirname( $dstPath );
1194 $archiveDir = dirname( $archivePath );
1195 // Abort immediately on directory creation errors since they're likely to be repetitive
1196 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1197 return $this->newFatal( 'directorycreateerror', $dstDir );
1199 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1200 return $this->newFatal( 'directorycreateerror', $archiveDir );
1203 // Set any desired headers to be use in GET/HEAD responses
1204 $headers = isset( $options['headers'] ) ?
$options['headers'] : array();
1206 // Archive destination file if it exists.
1207 // This will check if the archive file also exists and fail if does.
1208 // This is a sanity check to avoid data loss. On Windows and Linux,
1209 // copy() will overwrite, so the existence check is vulnerable to
1210 // race conditions unless an functioning LockManager is used.
1211 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1212 $operations[] = array(
1215 'dst' => $archivePath,
1216 'ignoreMissingSource' => true
1219 // Copy (or move) the source file to the destination
1220 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1221 if ( $flags & self
::DELETE_SOURCE
) {
1222 $operations[] = array(
1226 'overwrite' => true, // replace current
1227 'headers' => $headers
1230 $operations[] = array(
1234 'overwrite' => true, // replace current
1235 'headers' => $headers
1238 } else { // FS source path
1239 $operations[] = array(
1243 'overwrite' => true, // replace current
1244 'headers' => $headers
1246 if ( $flags & self
::DELETE_SOURCE
) {
1247 $sourceFSFilesToDelete[] = $srcPath;
1252 // Execute the operations for each triplet
1253 $status->merge( $backend->doOperations( $operations ) );
1254 // Find out which files were archived...
1255 foreach ( $ntuples as $i => $ntuple ) {
1256 list( , , $archiveRel ) = $ntuple;
1257 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1258 if ( $this->fileExists( $archivePath ) ) {
1259 $status->value
[$i] = 'archived';
1261 $status->value
[$i] = 'new';
1264 // Cleanup for disk source files...
1265 foreach ( $sourceFSFilesToDelete as $file ) {
1266 wfSuppressWarnings();
1267 unlink( $file ); // FS cleanup
1268 wfRestoreWarnings();
1275 * Creates a directory with the appropriate zone permissions.
1276 * Callers are responsible for doing read-only and "writable repo" checks.
1278 * @param string $dir Virtual URL (or storage path) of directory to clean
1281 protected function initDirectory( $dir ) {
1282 $path = $this->resolveToStoragePath( $dir );
1283 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1285 $params = array( 'dir' => $path );
1286 if ( $this->isPrivate ||
$container === $this->zones
['deleted']['container'] ) {
1287 # Take all available measures to prevent web accessibility of new deleted
1288 # directories, in case the user has not configured offline storage
1289 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1292 return $this->backend
->prepare( $params );
1296 * Deletes a directory if empty.
1298 * @param string $dir Virtual URL (or storage path) of directory to clean
1301 public function cleanDir( $dir ) {
1302 $this->assertWritableRepo(); // fail out if read-only
1304 $status = $this->newGood();
1305 $status->merge( $this->backend
->clean(
1306 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1312 * Checks existence of a a file
1314 * @param string $file Virtual URL (or storage path) of file to check
1317 public function fileExists( $file ) {
1318 $result = $this->fileExistsBatch( array( $file ) );
1324 * Checks existence of an array of files.
1326 * @param array $files Virtual URLs (or storage paths) of files to check
1327 * @return array|bool Either array of files and existence flags, or false
1329 public function fileExistsBatch( array $files ) {
1331 foreach ( $files as $key => $file ) {
1332 $file = $this->resolveToStoragePath( $file );
1333 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1340 * Move a file to the deletion archive.
1341 * If no valid deletion archive exists, this may either delete the file
1342 * or throw an exception, depending on the preference of the repository
1344 * @param $srcRel Mixed: relative path for the file to be deleted
1345 * @param $archiveRel Mixed: relative path for the archive location.
1346 * Relative to a private archive directory.
1347 * @return FileRepoStatus object
1349 public function delete( $srcRel, $archiveRel ) {
1350 $this->assertWritableRepo(); // fail out if read-only
1352 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1356 * Move a group of files to the deletion archive.
1358 * If no valid deletion archive is configured, this may either delete the
1359 * file or throw an exception, depending on the preference of the repository.
1361 * The overwrite policy is determined by the repository -- currently LocalRepo
1362 * assumes a naming scheme in the deleted zone based on content hash, as
1363 * opposed to the public zone which is assumed to be unique.
1365 * @param array $sourceDestPairs of source/destination pairs. Each element
1366 * is a two-element array containing the source file path relative to the
1367 * public root in the first element, and the archive file path relative
1368 * to the deleted zone root in the second element.
1369 * @throws MWException
1370 * @return FileRepoStatus
1372 public function deleteBatch( array $sourceDestPairs ) {
1373 $this->assertWritableRepo(); // fail out if read-only
1375 // Try creating directories
1376 $status = $this->initZones( array( 'public', 'deleted' ) );
1377 if ( !$status->isOK() ) {
1381 $status = $this->newGood();
1383 $backend = $this->backend
; // convenience
1384 $operations = array();
1385 // Validate filenames and create archive directories
1386 foreach ( $sourceDestPairs as $pair ) {
1387 list( $srcRel, $archiveRel ) = $pair;
1388 if ( !$this->validateFilename( $srcRel ) ) {
1389 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1390 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1391 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1394 $publicRoot = $this->getZonePath( 'public' );
1395 $srcPath = "{$publicRoot}/$srcRel";
1397 $deletedRoot = $this->getZonePath( 'deleted' );
1398 $archivePath = "{$deletedRoot}/{$archiveRel}";
1399 $archiveDir = dirname( $archivePath ); // does not touch FS
1401 // Create destination directories
1402 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1403 return $this->newFatal( 'directorycreateerror', $archiveDir );
1406 $operations[] = array(
1409 'dst' => $archivePath,
1410 // We may have 2+ identical files being deleted,
1411 // all of which will map to the same destination file
1412 'overwriteSame' => true // also see bug 31792
1416 // Move the files by execute the operations for each pair.
1417 // We're now committed to returning an OK result, which will
1418 // lead to the files being moved in the DB also.
1419 $opts = array( 'force' => true );
1420 $status->merge( $backend->doOperations( $operations, $opts ) );
1426 * Delete files in the deleted directory if they are not referenced in the filearchive table
1430 public function cleanupDeletedBatch( array $storageKeys ) {
1431 $this->assertWritableRepo();
1435 * Get a relative path for a deletion archive key,
1436 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1438 * @param $key string
1439 * @throws MWException
1442 public function getDeletedHashPath( $key ) {
1443 if ( strlen( $key ) < 31 ) {
1444 throw new MWException( "Invalid storage key '$key'." );
1447 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1448 $path .= $key[$i] . '/';
1455 * If a path is a virtual URL, resolve it to a storage path.
1456 * Otherwise, just return the path as it is.
1458 * @param $path string
1460 * @throws MWException
1462 protected function resolveToStoragePath( $path ) {
1463 if ( $this->isVirtualUrl( $path ) ) {
1464 return $this->resolveVirtualUrl( $path );
1471 * Get a local FS copy of a file with a given virtual URL/storage path.
1472 * Temporary files may be purged when the file object falls out of scope.
1474 * @param $virtualUrl string
1475 * @return TempFSFile|null Returns null on failure
1477 public function getLocalCopy( $virtualUrl ) {
1478 $path = $this->resolveToStoragePath( $virtualUrl );
1480 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1484 * Get a local FS file with a given virtual URL/storage path.
1485 * The file is either an original or a copy. It should not be changed.
1486 * Temporary files may be purged when the file object falls out of scope.
1488 * @param $virtualUrl string
1489 * @return FSFile|null Returns null on failure.
1491 public function getLocalReference( $virtualUrl ) {
1492 $path = $this->resolveToStoragePath( $virtualUrl );
1494 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1498 * Get properties of a file with a given virtual URL/storage path.
1499 * Properties should ultimately be obtained via FSFile::getProps().
1501 * @param $virtualUrl string
1504 public function getFileProps( $virtualUrl ) {
1505 $path = $this->resolveToStoragePath( $virtualUrl );
1507 return $this->backend
->getFileProps( array( 'src' => $path ) );
1511 * Get the timestamp of a file with a given virtual URL/storage path
1513 * @param $virtualUrl string
1514 * @return string|bool False on failure
1516 public function getFileTimestamp( $virtualUrl ) {
1517 $path = $this->resolveToStoragePath( $virtualUrl );
1519 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1523 * Get the size of a file with a given virtual URL/storage path
1525 * @param $virtualUrl string
1526 * @return integer|bool False on failure
1528 public function getFileSize( $virtualUrl ) {
1529 $path = $this->resolveToStoragePath( $virtualUrl );
1531 return $this->backend
->getFileSize( array( 'src' => $path ) );
1535 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1537 * @param $virtualUrl string
1538 * @return string|bool
1540 public function getFileSha1( $virtualUrl ) {
1541 $path = $this->resolveToStoragePath( $virtualUrl );
1543 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1547 * Attempt to stream a file with the given virtual URL/storage path
1549 * @param $virtualUrl string
1550 * @param array $headers Additional HTTP headers to send on success
1551 * @return bool Success
1553 public function streamFile( $virtualUrl, $headers = array() ) {
1554 $path = $this->resolveToStoragePath( $virtualUrl );
1555 $params = array( 'src' => $path, 'headers' => $headers );
1557 return $this->backend
->streamFile( $params )->isOK();
1561 * Call a callback function for every public regular file in the repository.
1562 * This only acts on the current version of files, not any old versions.
1563 * May use either the database or the filesystem.
1565 * @param $callback Array|string
1568 public function enumFiles( $callback ) {
1569 $this->enumFilesInStorage( $callback );
1573 * Call a callback function for every public file in the repository.
1574 * May use either the database or the filesystem.
1576 * @param $callback Array|string
1579 protected function enumFilesInStorage( $callback ) {
1580 $publicRoot = $this->getZonePath( 'public' );
1581 $numDirs = 1 << ( $this->hashLevels
* 4 );
1582 // Use a priori assumptions about directory structure
1583 // to reduce the tree height of the scanning process.
1584 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1585 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1586 $path = $publicRoot;
1587 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1588 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1590 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1591 foreach ( $iterator as $name ) {
1592 // Each item returned is a public file
1593 call_user_func( $callback, "{$path}/{$name}" );
1599 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1601 * @param $filename string
1604 public function validateFilename( $filename ) {
1605 if ( strval( $filename ) == '' ) {
1609 return FileBackend
::isPathTraversalFree( $filename );
1613 * Get a callback function to use for cleaning error message parameters
1617 function getErrorCleanupFunction() {
1618 switch ( $this->pathDisclosureProtection
) {
1620 case 'simple': // b/c
1621 $callback = array( $this, 'passThrough' );
1623 default: // 'paranoid'
1624 $callback = array( $this, 'paranoidClean' );
1630 * Path disclosure protection function
1632 * @param $param string
1635 function paranoidClean( $param ) {
1640 * Path disclosure protection function
1642 * @param $param string
1645 function passThrough( $param ) {
1650 * Create a new fatal error
1652 * @return FileRepoStatus
1654 public function newFatal( $message /*, parameters...*/ ) {
1655 $params = func_get_args();
1656 array_unshift( $params, $this );
1658 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
1662 * Create a new good result
1664 * @param $value null|string
1665 * @return FileRepoStatus
1667 public function newGood( $value = null ) {
1668 return FileRepoStatus
::newGood( $this, $value );
1672 * Checks if there is a redirect named as $title. If there is, return the
1673 * title object. If not, return false.
1676 * @param $title Title of image
1679 public function checkRedirect( Title
$title ) {
1684 * Invalidates image redirect cache related to that image
1685 * Doesn't do anything for repositories that don't support image redirects.
1688 * @param $title Title of image
1690 public function invalidateImageRedirect( Title
$title ) {
1694 * Get the human-readable name of the repo
1698 public function getDisplayName() {
1699 // We don't name our own repo, return nothing
1700 if ( $this->isLocal() ) {
1704 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1705 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1709 * Get the portion of the file that contains the origin file name.
1710 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1712 * @param $name string
1715 public function nameForThumb( $name ) {
1716 if ( strlen( $name ) > $this->abbrvThreshold
) {
1717 $ext = FileBackend
::extensionFromPath( $name );
1718 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1725 * Returns true if this the local file repository.
1729 public function isLocal() {
1730 return $this->getName() == 'local';
1734 * Get a key on the primary cache for this repository.
1735 * Returns false if the repository's cache is not accessible at this site.
1736 * The parameters are the parts of the key, as for wfMemcKey().
1741 public function getSharedCacheKey( /*...*/ ) {
1746 * Get a key for this repo in the local cache domain. These cache keys are
1747 * not shared with remote instances of the repo.
1748 * The parameters are the parts of the key, as for wfMemcKey().
1752 public function getLocalCacheKey( /*...*/ ) {
1753 $args = func_get_args();
1754 array_unshift( $args, 'filerepo', $this->getName() );
1756 return call_user_func_array( 'wfMemcKey', $args );
1760 * Get an temporary FileRepo associated with this repo.
1761 * Files will be created in the temp zone of this repo and
1762 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1763 * It will have the same backend as this repo.
1765 * @return TempFileRepo
1767 public function getTempRepo() {
1768 return new TempFileRepo( array(
1769 'name' => "{$this->name}-temp",
1770 'backend' => $this->backend
,
1773 'container' => $this->zones
['temp']['container'],
1774 'directory' => $this->zones
['temp']['directory']
1777 'container' => $this->zones
['thumb']['container'],
1778 'directory' => $this->zones
['thumb']['directory'] == ''
1780 : $this->zones
['thumb']['directory'] . '/temp'
1782 'transcoded' => array(
1783 'container' => $this->zones
['transcoded']['container'],
1784 'directory' => $this->zones
['transcoded']['directory'] == ''
1786 : $this->zones
['transcoded']['directory'] . '/temp'
1789 'url' => $this->getZoneUrl( 'temp' ),
1790 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1791 'transcodedUrl' => $this->getZoneUrl( 'transcoded' ) . '/temp',
1792 'hashLevels' => $this->hashLevels
// performance
1797 * Get an UploadStash associated with this repo.
1800 * @return UploadStash
1802 public function getUploadStash( User
$user = null ) {
1803 return new UploadStash( $this, $user );
1807 * Throw an exception if this repo is read-only by design.
1808 * This does not and should not check getReadOnlyReason().
1811 * @throws MWException
1813 protected function assertWritableRepo() {
1817 * Return information about the repository.
1822 public function getInfo() {
1824 'name' => $this->getName(),
1825 'displayname' => $this->getDisplayName(),
1826 'rootUrl' => $this->getZoneUrl( 'public' ),
1827 'local' => $this->isLocal(),
1830 $optionalSettings = array(
1831 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1832 'fetchDescription', 'descriptionCacheExpiry', 'scriptExtension'
1834 foreach ( $optionalSettings as $k ) {
1835 if ( isset( $this->$k ) ) {
1836 $ret[$k] = $this->$k;
1845 * FileRepo for temporary files created via FileRepo::getTempRepo()
1847 class TempFileRepo
extends FileRepo
{
1848 public function getTempRepo() {
1849 throw new MWException( "Cannot get a temp repo from a temp repo." );