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 bool Whether to fetch commons image description pages and display
44 * them on the local wiki */
45 public $fetchDescription;
48 public $descriptionCacheExpiry;
50 /** @var FileBackend */
53 /** @var Array Map of zones to config */
54 protected $zones = array();
56 /** @var string URL of thumb.php */
57 protected $thumbScriptUrl;
59 /** @var bool Whether to skip media file transformation on parse and rely
60 * on a 404 handler instead. */
61 protected $transformVia404;
63 /** @var string URL of image description pages, e.g.
64 * http://en.wikipedia.org/wiki/File:
66 protected $descBaseUrl;
68 /** @var string URL of the MediaWiki installation, equivalent to
69 * $wgScriptPath, e.g. https://en.wikipedia.org/w
71 protected $scriptDirUrl;
73 /** @var string Script extension of the MediaWiki installation, equivalent
74 * to $wgScriptExtension, e.g. .php5 defaults to .php */
75 protected $scriptExtension;
77 /** @var string Equivalent to $wgArticlePath, e.g. http://en.wikipedia.org/wiki/$1 */
78 protected $articleUrl;
80 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
81 * determines whether filenames implicitly start with a capital letter.
82 * The current implementation may give incorrect description page links
83 * when the local $wgCapitalLinks and initialCapital are mismatched.
85 protected $initialCapital;
87 /** @var string May be 'paranoid' to remove all parameters from error
88 * messages, 'none' to leave the paths in unchanged, or 'simple' to
89 * replace paths with placeholders. Default for LocalRepo is
92 protected $pathDisclosureProtection = 'simple';
94 /** @var bool Public zone URL. */
97 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
100 /** @var int The number of directory levels for hash-based division of files */
101 protected $hashLevels;
103 /** @var int The number of directory levels for hash-based division of deleted files */
104 protected $deletedHashLevels;
106 /** @var int File names over this size will use the short form of thumbnail
107 * names. Short thumbnail names only have the width, parameters, and the
110 protected $abbrvThreshold;
113 * Factory functions for creating new files
114 * Override these in the base class
116 protected $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
117 protected $oldFileFactory = false;
118 protected $fileFactoryKey = false;
119 protected $oldFileFactoryKey = false;
122 * @param array|null $info
123 * @throws MWException
125 public function __construct( array $info = null ) {
126 // Verify required settings presence
129 ||
!array_key_exists( 'name', $info )
130 ||
!array_key_exists( 'backend', $info )
132 throw new MWException( __CLASS__
.
133 " requires an array of options having both 'name' and 'backend' keys.\n" );
137 $this->name
= $info['name'];
138 if ( $info['backend'] instanceof FileBackend
) {
139 $this->backend
= $info['backend']; // useful for testing
141 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
144 // Optional settings that can have no value
145 $optionalSettings = array(
146 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
147 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
150 foreach ( $optionalSettings as $var ) {
151 if ( isset( $info[$var] ) ) {
152 $this->$var = $info[$var];
156 // Optional settings that have a default
157 $this->initialCapital
= isset( $info['initialCapital'] )
158 ?
$info['initialCapital']
159 : MWNamespace
::isCapitalized( NS_FILE
);
160 $this->url
= isset( $info['url'] )
162 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
163 if ( isset( $info['thumbUrl'] ) ) {
164 $this->thumbUrl
= $info['thumbUrl'];
166 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
168 $this->hashLevels
= isset( $info['hashLevels'] )
169 ?
$info['hashLevels']
171 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
172 ?
$info['deletedHashLevels']
174 $this->transformVia404
= !empty( $info['transformVia404'] );
175 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
176 ?
$info['abbrvThreshold']
178 $this->isPrivate
= !empty( $info['isPrivate'] );
179 // Give defaults for the basic zones...
180 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
181 foreach ( array( 'public', 'thumb', 'transcoded', 'temp', 'deleted' ) as $zone ) {
182 if ( !isset( $this->zones
[$zone]['container'] ) ) {
183 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
185 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
186 $this->zones
[$zone]['directory'] = '';
188 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
189 $this->zones
[$zone]['urlsByExt'] = array();
195 * Get the file backend instance. Use this function wisely.
197 * @return FileBackend
199 public function getBackend() {
200 return $this->backend
;
204 * Get an explanatory message if this repo is read-only.
205 * This checks if an administrator disabled writes to the backend.
207 * @return string|bool Returns false if the repo is not read-only
209 public function getReadOnlyReason() {
210 return $this->backend
->getReadOnlyReason();
214 * Check if a single zone or list of zones is defined for usage
216 * @param array $doZones Only do a particular zones
217 * @throws MWException
220 protected function initZones( $doZones = array() ) {
221 $status = $this->newGood();
222 foreach ( (array)$doZones as $zone ) {
223 $root = $this->getZonePath( $zone );
224 if ( $root === null ) {
225 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
233 * Determine if a string is an mwrepo:// URL
238 public static function isVirtualUrl( $url ) {
239 return substr( $url, 0, 9 ) == 'mwrepo://';
243 * Get a URL referring to this repository, with the private mwrepo protocol.
244 * The suffix, if supplied, is considered to be unencoded, and will be
245 * URL-encoded before being returned.
247 * @param string|bool $suffix
250 public function getVirtualUrl( $suffix = false ) {
251 $path = 'mwrepo://' . $this->name
;
252 if ( $suffix !== false ) {
253 $path .= '/' . rawurlencode( $suffix );
260 * Get the URL corresponding to one of the four basic zones
262 * @param string $zone One of: public, deleted, temp, thumb
263 * @param string|null $ext Optional file extension
264 * @return string|bool
266 public function getZoneUrl( $zone, $ext = null ) {
267 if ( in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) ) ) {
268 // standard public zones
269 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
270 // custom URL for extension/zone
271 return $this->zones
[$zone]['urlsByExt'][$ext];
272 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
273 // custom URL for zone
274 return $this->zones
[$zone]['url'];
281 return "{$this->url}/temp";
283 return false; // no public URL
285 return $this->thumbUrl
;
287 return "{$this->url}/transcoded";
294 * Get the thumb zone URL configured to be handled by scripts like thumb_handler.php.
295 * This is probably only useful for internal requests, such as from a fast frontend server
296 * to a slower backend server.
298 * Large sites may use a different host name for uploads than for wikis. In any case, the
299 * wiki configuration is needed in order to use thumb.php. To avoid extracting the wiki ID
300 * from the URL path, one can configure thumb_handler.php to recognize a special path on the
301 * same host name as the wiki that is used for viewing thumbnails.
303 * @param string $zone one of: public, deleted, temp, thumb
304 * @return string|bool String or false
306 public function getZoneHandlerUrl( $zone ) {
307 if ( isset( $this->zones
[$zone]['handlerUrl'] )
308 && in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) )
310 return $this->zones
[$zone]['handlerUrl'];
317 * Get the backend storage path corresponding to a virtual URL.
318 * Use this function wisely.
321 * @throws MWException
324 public function resolveVirtualUrl( $url ) {
325 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
326 throw new MWException( __METHOD__
. ': unknown protocol' );
328 $bits = explode( '/', substr( $url, 9 ), 3 );
329 if ( count( $bits ) != 3 ) {
330 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
332 list( $repo, $zone, $rel ) = $bits;
333 if ( $repo !== $this->name
) {
334 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
336 $base = $this->getZonePath( $zone );
338 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
341 return $base . '/' . rawurldecode( $rel );
345 * The the storage container and base path of a zone
347 * @param string $zone
348 * @return array (container, base path) or (null, null)
350 protected function getZoneLocation( $zone ) {
351 if ( !isset( $this->zones
[$zone] ) ) {
352 return array( null, null ); // bogus
355 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
359 * Get the storage path corresponding to one of the zones
361 * @param string $zone
362 * @return string|null Returns null if the zone is not defined
364 public function getZonePath( $zone ) {
365 list( $container, $base ) = $this->getZoneLocation( $zone );
366 if ( $container === null ||
$base === null ) {
369 $backendName = $this->backend
->getName();
370 if ( $base != '' ) { // may not be set
374 return "mwstore://$backendName/{$container}{$base}";
378 * Create a new File object from the local repository
380 * @param Title|string $title Title object or string
381 * @param bool|string $time Time at which the image was uploaded. If this
382 * is specified, the returned object will be an instance of the
383 * repository's old file class instead of a current file. Repositories
384 * not supporting version control should return false if this parameter
386 * @return File|null A File, or null if passed an invalid Title
388 public function newFile( $title, $time = false ) {
389 $title = File
::normalizeTitle( $title );
394 if ( $this->oldFileFactory
) {
395 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
400 return call_user_func( $this->fileFactory
, $title, $this );
405 * Find an instance of the named file created at the specified time
406 * Returns false if the file does not exist. Repositories not supporting
407 * version control should return false if the time is specified.
409 * @param Title|string $title Title object or string
410 * @param array $options Associative array of options:
411 * time: requested time for a specific file version, or false for the
412 * current version. An image object will be returned which was
413 * created at the specified time (which may be archived or current).
414 * ignoreRedirect: If true, do not follow file redirects
415 * private: If true, return restricted (deleted) files if the current
416 * user is allowed to view them. Otherwise, such files will not
418 * @return File|bool False on failure
420 public function findFile( $title, $options = array() ) {
421 $title = File
::normalizeTitle( $title );
425 $time = isset( $options['time'] ) ?
$options['time'] : false;
426 # First try the current version of the file to see if it precedes the timestamp
427 $img = $this->newFile( $title );
431 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
434 # Now try an old version of the file
435 if ( $time !== false ) {
436 $img = $this->newFile( $title, $time );
437 if ( $img && $img->exists() ) {
438 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
439 return $img; // always OK
440 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
447 if ( !empty( $options['ignoreRedirect'] ) ) {
450 $redir = $this->checkRedirect( $title );
451 if ( $redir && $title->getNamespace() == NS_FILE
) {
452 $img = $this->newFile( $redir );
456 if ( $img->exists() ) {
457 $img->redirectedFrom( $title->getDBkey() );
467 * Find many files at once.
469 * @param array $items An array of titles, or an array of findFile() options with
470 * the "title" option giving the title. Example:
472 * $findItem = array( 'title' => $title, 'private' => true );
473 * $findBatch = array( $findItem );
474 * $repo->findFiles( $findBatch );
477 public function findFiles( array $items ) {
479 foreach ( $items as $item ) {
480 if ( is_array( $item ) ) {
481 $title = $item['title'];
483 unset( $options['title'] );
488 $file = $this->findFile( $title, $options );
490 $result[$file->getTitle()->getDBkey()] = $file;
498 * Find an instance of the file with this key, created at the specified time
499 * Returns false if the file does not exist. Repositories not supporting
500 * version control should return false if the time is specified.
502 * @param string $sha1 Base 36 SHA-1 hash
503 * @param array $options Option array, same as findFile().
504 * @return File|bool False on failure
506 public function findFileFromKey( $sha1, $options = array() ) {
507 $time = isset( $options['time'] ) ?
$options['time'] : false;
508 # First try to find a matching current version of a file...
509 if ( $this->fileFactoryKey
) {
510 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
512 return false; // find-by-sha1 not supported
514 if ( $img && $img->exists() ) {
517 # Now try to find a matching old version of a file...
518 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
519 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
520 if ( $img && $img->exists() ) {
521 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
522 return $img; // always OK
523 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
533 * Get an array or iterator of file objects for files that have a given
534 * SHA-1 content hash.
537 * @param string $hash SHA-1 hash
540 public function findBySha1( $hash ) {
545 * Get an array of arrays or iterators of file objects for files that
546 * have the given SHA-1 content hashes.
548 * @param array $hashes An array of hashes
549 * @return array An Array of arrays or iterators of file objects and the hash as key
551 public function findBySha1s( array $hashes ) {
553 foreach ( $hashes as $hash ) {
554 $files = $this->findBySha1( $hash );
555 if ( count( $files ) ) {
556 $result[$hash] = $files;
564 * Return an array of files where the name starts with $prefix.
567 * @param string $prefix The prefix to search for
568 * @param int $limit The maximum amount of files to return
571 public function findFilesByPrefix( $prefix, $limit ) {
576 * Get the public root URL of the repository
578 * @deprecated since 1.20
581 public function getRootUrl() {
582 return $this->getZoneUrl( 'public' );
586 * Get the URL of thumb.php
590 public function getThumbScriptUrl() {
591 return $this->thumbScriptUrl
;
595 * Returns true if the repository can transform files via a 404 handler
599 public function canTransformVia404() {
600 return $this->transformVia404
;
604 * Get the name of a file from its title object
606 * @param Title $title
609 public function getNameFromTitle( Title
$title ) {
611 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
612 $name = $title->getUserCaseDBKey();
613 if ( $this->initialCapital
) {
614 $name = $wgContLang->ucfirst( $name );
617 $name = $title->getDBkey();
624 * Get the public zone root storage directory of the repository
628 public function getRootDirectory() {
629 return $this->getZonePath( 'public' );
633 * Get a relative path including trailing slash, e.g. f/fa/
634 * If the repo is not hashed, returns an empty string
636 * @param string $name Name of file
639 public function getHashPath( $name ) {
640 return self
::getHashPathForLevel( $name, $this->hashLevels
);
644 * Get a relative path including trailing slash, e.g. f/fa/
645 * If the repo is not hashed, returns an empty string
647 * @param string $suffix Basename of file from FileRepo::storeTemp()
650 public function getTempHashPath( $suffix ) {
651 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
652 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
653 return self
::getHashPathForLevel( $name, $this->hashLevels
);
657 * @param string $name
661 protected static function getHashPathForLevel( $name, $levels ) {
662 if ( $levels == 0 ) {
665 $hash = md5( $name );
667 for ( $i = 1; $i <= $levels; $i++
) {
668 $path .= substr( $hash, 0, $i ) . '/';
676 * Get the number of hash directory levels
680 public function getHashLevels() {
681 return $this->hashLevels
;
685 * Get the name of this repository, as specified by $info['name]' to the constructor
689 public function getName() {
694 * Make an url to this repo
696 * @param string $query Query string to append
697 * @param string $entry Entry point; defaults to index
698 * @return string|bool False on failure
700 public function makeUrl( $query = '', $entry = 'index' ) {
701 if ( isset( $this->scriptDirUrl
) ) {
702 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
704 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
711 * Get the URL of an image description page. May return false if it is
712 * unknown or not applicable. In general this should only be called by the
713 * File class, since it may return invalid results for certain kinds of
714 * repositories. Use File::getDescriptionUrl() in user code.
716 * In particular, it uses the article paths as specified to the repository
717 * constructor, whereas local repositories use the local Title functions.
719 * @param string $name
722 public function getDescriptionUrl( $name ) {
723 $encName = wfUrlencode( $name );
724 if ( !is_null( $this->descBaseUrl
) ) {
725 # "http://example.com/wiki/File:"
726 return $this->descBaseUrl
. $encName;
728 if ( !is_null( $this->articleUrl
) ) {
729 # "http://example.com/wiki/$1"
731 # We use "Image:" as the canonical namespace for
732 # compatibility across all MediaWiki versions.
733 return str_replace( '$1',
734 "Image:$encName", $this->articleUrl
);
736 if ( !is_null( $this->scriptDirUrl
) ) {
737 # "http://example.com/w"
739 # We use "Image:" as the canonical namespace for
740 # compatibility across all MediaWiki versions,
741 # and just sort of hope index.php is right. ;)
742 return $this->makeUrl( "title=Image:$encName" );
749 * Get the URL of the content-only fragment of the description page. For
750 * MediaWiki this means action=render. This should only be called by the
751 * repository's file class, since it may return invalid results. User code
752 * should use File::getDescriptionText().
754 * @param string $name Name of image to fetch
755 * @param string $lang Language to fetch it in, if any.
758 public function getDescriptionRenderUrl( $name, $lang = null ) {
759 $query = 'action=render';
760 if ( !is_null( $lang ) ) {
761 $query .= '&uselang=' . $lang;
763 if ( isset( $this->scriptDirUrl
) ) {
764 return $this->makeUrl(
766 wfUrlencode( 'Image:' . $name ) .
769 $descUrl = $this->getDescriptionUrl( $name );
771 return wfAppendQuery( $descUrl, $query );
779 * Get the URL of the stylesheet to apply to description pages
781 * @return string|bool False on failure
783 public function getDescriptionStylesheetUrl() {
784 if ( isset( $this->scriptDirUrl
) ) {
785 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
786 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
793 * Store a file to a given destination.
795 * @param string $srcPath Source file system path, storage path, or virtual URL
796 * @param string $dstZone Destination zone
797 * @param string $dstRel Destination relative path
798 * @param int $flags Bitwise combination of the following flags:
799 * self::DELETE_SOURCE Delete the source file after upload
800 * self::OVERWRITE Overwrite an existing destination file instead of failing
801 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
802 * same contents as the source
803 * self::SKIP_LOCKING Skip any file locking when doing the store
804 * @return FileRepoStatus
806 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
807 $this->assertWritableRepo(); // fail out if read-only
809 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
810 if ( $status->successCount
== 0 ) {
818 * Store a batch of files
820 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
821 * @param int $flags Bitwise combination of the following flags:
822 * self::DELETE_SOURCE Delete the source file after upload
823 * self::OVERWRITE Overwrite an existing destination file instead of failing
824 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
825 * same contents as the source
826 * self::SKIP_LOCKING Skip any file locking when doing the store
827 * @throws MWException
828 * @return FileRepoStatus
830 public function storeBatch( array $triplets, $flags = 0 ) {
831 $this->assertWritableRepo(); // fail out if read-only
833 $status = $this->newGood();
834 $backend = $this->backend
; // convenience
836 $operations = array();
837 $sourceFSFilesToDelete = array(); // cleanup for disk source files
838 // Validate each triplet and get the store operation...
839 foreach ( $triplets as $triplet ) {
840 list( $srcPath, $dstZone, $dstRel ) = $triplet;
842 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
845 // Resolve destination path
846 $root = $this->getZonePath( $dstZone );
848 throw new MWException( "Invalid zone: $dstZone" );
850 if ( !$this->validateFilename( $dstRel ) ) {
851 throw new MWException( 'Validation error in $dstRel' );
853 $dstPath = "$root/$dstRel";
854 $dstDir = dirname( $dstPath );
855 // Create destination directories for this triplet
856 if ( !$this->initDirectory( $dstDir )->isOK() ) {
857 return $this->newFatal( 'directorycreateerror', $dstDir );
860 // Resolve source to a storage path if virtual
861 $srcPath = $this->resolveToStoragePath( $srcPath );
863 // Get the appropriate file operation
864 if ( FileBackend
::isStoragePath( $srcPath ) ) {
865 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
868 if ( $flags & self
::DELETE_SOURCE
) {
869 $sourceFSFilesToDelete[] = $srcPath;
872 $operations[] = array(
876 'overwrite' => $flags & self
::OVERWRITE
,
877 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
881 // Execute the store operation for each triplet
882 $opts = array( 'force' => true );
883 if ( $flags & self
::SKIP_LOCKING
) {
884 $opts['nonLocking'] = true;
886 $status->merge( $backend->doOperations( $operations, $opts ) );
887 // Cleanup for disk source files...
888 foreach ( $sourceFSFilesToDelete as $file ) {
889 wfSuppressWarnings();
890 unlink( $file ); // FS cleanup
898 * Deletes a batch of files.
899 * Each file can be a (zone, rel) pair, virtual url, storage path.
900 * It will try to delete each file, but ignores any errors that may occur.
902 * @param array $files List of files to delete
903 * @param int $flags Bitwise combination of the following flags:
904 * self::SKIP_LOCKING Skip any file locking when doing the deletions
905 * @return FileRepoStatus
907 public function cleanupBatch( array $files, $flags = 0 ) {
908 $this->assertWritableRepo(); // fail out if read-only
910 $status = $this->newGood();
912 $operations = array();
913 foreach ( $files as $path ) {
914 if ( is_array( $path ) ) {
915 // This is a pair, extract it
916 list( $zone, $rel ) = $path;
917 $path = $this->getZonePath( $zone ) . "/$rel";
919 // Resolve source to a storage path if virtual
920 $path = $this->resolveToStoragePath( $path );
922 $operations[] = array( 'op' => 'delete', 'src' => $path );
924 // Actually delete files from storage...
925 $opts = array( 'force' => true );
926 if ( $flags & self
::SKIP_LOCKING
) {
927 $opts['nonLocking'] = true;
929 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
935 * Import a file from the local file system into the repo.
936 * This does no locking nor journaling and overrides existing files.
937 * This function can be used to write to otherwise read-only foreign repos.
938 * This is intended for copying generated thumbnails into the repo.
940 * @param string $src Source file system path, storage path, or virtual URL
941 * @param string $dst Virtual URL or storage path
942 * @param string|null $disposition Content-Disposition if given and supported
943 * @return FileRepoStatus
945 final public function quickImport( $src, $dst, $disposition = null ) {
946 return $this->quickImportBatch( array( array( $src, $dst, $disposition ) ) );
950 * Purge a file from the repo. This does no locking nor journaling.
951 * This function can be used to write to otherwise read-only foreign repos.
952 * This is intended for purging thumbnails.
954 * @param string $path Virtual URL or storage path
955 * @return FileRepoStatus
957 final public function quickPurge( $path ) {
958 return $this->quickPurgeBatch( array( $path ) );
962 * Deletes a directory if empty.
963 * This function can be used to write to otherwise read-only foreign repos.
965 * @param string $dir Virtual URL (or storage path) of directory to clean
968 public function quickCleanDir( $dir ) {
969 $status = $this->newGood();
970 $status->merge( $this->backend
->clean(
971 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
977 * Import a batch of files from the local file system into the repo.
978 * This does no locking nor journaling and overrides existing files.
979 * This function can be used to write to otherwise read-only foreign repos.
980 * This is intended for copying generated thumbnails into the repo.
982 * All path parameters may be a file system path, storage path, or virtual URL.
983 * When "dispositions" are given they are used as Content-Disposition if supported.
985 * @param array $triples List of (source path, destination path, disposition)
986 * @return FileRepoStatus
988 public function quickImportBatch( array $triples ) {
989 $status = $this->newGood();
990 $operations = array();
991 foreach ( $triples as $triple ) {
992 list( $src, $dst ) = $triple;
993 $src = $this->resolveToStoragePath( $src );
994 $dst = $this->resolveToStoragePath( $dst );
995 $operations[] = array(
996 'op' => FileBackend
::isStoragePath( $src ) ?
'copy' : 'store',
999 'disposition' => isset( $triple[2] ) ?
$triple[2] : null
1001 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1003 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1009 * Purge a batch of files from the repo.
1010 * This function can be used to write to otherwise read-only foreign repos.
1011 * This does no locking nor journaling and is intended for purging thumbnails.
1013 * @param array $paths List of virtual URLs or storage paths
1014 * @return FileRepoStatus
1016 public function quickPurgeBatch( array $paths ) {
1017 $status = $this->newGood();
1018 $operations = array();
1019 foreach ( $paths as $path ) {
1020 $operations[] = array(
1022 'src' => $this->resolveToStoragePath( $path ),
1023 'ignoreMissingSource' => true
1026 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1032 * Pick a random name in the temp zone and store a file to it.
1033 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1034 * file can later be disposed using FileRepo::freeTemp().
1036 * @param string $originalName the base name of the file as specified
1037 * by the user. The file extension will be maintained.
1038 * @param string $srcPath The current location of the file.
1039 * @return FileRepoStatus Object with the URL in the value.
1041 public function storeTemp( $originalName, $srcPath ) {
1042 $this->assertWritableRepo(); // fail out if read-only
1044 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1045 $hashPath = $this->getHashPath( $originalName );
1046 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1047 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1049 $result = $this->quickImport( $srcPath, $virtualUrl );
1050 $result->value
= $virtualUrl;
1056 * Remove a temporary file or mark it for garbage collection
1058 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1059 * @return bool True on success, false on failure
1061 public function freeTemp( $virtualUrl ) {
1062 $this->assertWritableRepo(); // fail out if read-only
1064 $temp = $this->getVirtualUrl( 'temp' );
1065 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1066 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1071 return $this->quickPurge( $virtualUrl )->isOK();
1075 * Concatenate a list of temporary files into a target file location.
1077 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1078 * @param string $dstPath Target file system path
1079 * @param int $flags Bitwise combination of the following flags:
1080 * self::DELETE_SOURCE Delete the source files
1081 * @return FileRepoStatus
1083 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1084 $this->assertWritableRepo(); // fail out if read-only
1086 $status = $this->newGood();
1089 foreach ( $srcPaths as $srcPath ) {
1090 // Resolve source to a storage path if virtual
1091 $source = $this->resolveToStoragePath( $srcPath );
1092 $sources[] = $source; // chunk to merge
1095 // Concatenate the chunks into one FS file
1096 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1097 $status->merge( $this->backend
->concatenate( $params ) );
1098 if ( !$status->isOK() ) {
1102 // Delete the sources if required
1103 if ( $flags & self
::DELETE_SOURCE
) {
1104 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1107 // Make sure status is OK, despite any quickPurgeBatch() fatals
1108 $status->setResult( true );
1114 * Copy or move a file either from a storage path, virtual URL,
1115 * or file system path, into this repository at the specified destination location.
1117 * Returns a FileRepoStatus object. On success, the value contains "new" or
1118 * "archived", to indicate whether the file was new with that name.
1120 * Options to $options include:
1121 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1123 * @param string $srcPath The source file system path, storage path, or URL
1124 * @param string $dstRel The destination relative path
1125 * @param string $archiveRel The relative path where the existing file is to
1126 * be archived, if there is one. Relative to the public zone root.
1127 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1128 * that the source file should be deleted if possible
1129 * @param array $options Optional additional parameters
1130 * @return FileRepoStatus
1132 public function publish(
1133 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1135 $this->assertWritableRepo(); // fail out if read-only
1137 $status = $this->publishBatch(
1138 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1139 if ( $status->successCount
== 0 ) {
1140 $status->ok
= false;
1142 if ( isset( $status->value
[0] ) ) {
1143 $status->value
= $status->value
[0];
1145 $status->value
= false;
1152 * Publish a batch of files
1154 * @param array $ntuples (source, dest, archive) triplets or
1155 * (source, dest, archive, options) 4-tuples as per publish().
1156 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1157 * that the source files should be deleted if possible
1158 * @throws MWException
1159 * @return FileRepoStatus
1161 public function publishBatch( array $ntuples, $flags = 0 ) {
1162 $this->assertWritableRepo(); // fail out if read-only
1164 $backend = $this->backend
; // convenience
1165 // Try creating directories
1166 $status = $this->initZones( 'public' );
1167 if ( !$status->isOK() ) {
1171 $status = $this->newGood( array() );
1173 $operations = array();
1174 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1175 // Validate each triplet and get the store operation...
1176 foreach ( $ntuples as $ntuple ) {
1177 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1178 $options = isset( $ntuple[3] ) ?
$ntuple[3] : array();
1179 // Resolve source to a storage path if virtual
1180 $srcPath = $this->resolveToStoragePath( $srcPath );
1181 if ( !$this->validateFilename( $dstRel ) ) {
1182 throw new MWException( 'Validation error in $dstRel' );
1184 if ( !$this->validateFilename( $archiveRel ) ) {
1185 throw new MWException( 'Validation error in $archiveRel' );
1188 $publicRoot = $this->getZonePath( 'public' );
1189 $dstPath = "$publicRoot/$dstRel";
1190 $archivePath = "$publicRoot/$archiveRel";
1192 $dstDir = dirname( $dstPath );
1193 $archiveDir = dirname( $archivePath );
1194 // Abort immediately on directory creation errors since they're likely to be repetitive
1195 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1196 return $this->newFatal( 'directorycreateerror', $dstDir );
1198 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1199 return $this->newFatal( 'directorycreateerror', $archiveDir );
1202 // Set any desired headers to be use in GET/HEAD responses
1203 $headers = isset( $options['headers'] ) ?
$options['headers'] : array();
1205 // Archive destination file if it exists.
1206 // This will check if the archive file also exists and fail if does.
1207 // This is a sanity check to avoid data loss. On Windows and Linux,
1208 // copy() will overwrite, so the existence check is vulnerable to
1209 // race conditions unless an functioning LockManager is used.
1210 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1211 $operations[] = array(
1214 'dst' => $archivePath,
1215 'ignoreMissingSource' => true
1218 // Copy (or move) the source file to the destination
1219 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1220 if ( $flags & self
::DELETE_SOURCE
) {
1221 $operations[] = array(
1225 'overwrite' => true, // replace current
1226 'headers' => $headers
1229 $operations[] = array(
1233 'overwrite' => true, // replace current
1234 'headers' => $headers
1237 } else { // FS source path
1238 $operations[] = array(
1242 'overwrite' => true, // replace current
1243 'headers' => $headers
1245 if ( $flags & self
::DELETE_SOURCE
) {
1246 $sourceFSFilesToDelete[] = $srcPath;
1251 // Execute the operations for each triplet
1252 $status->merge( $backend->doOperations( $operations ) );
1253 // Find out which files were archived...
1254 foreach ( $ntuples as $i => $ntuple ) {
1255 list( , , $archiveRel ) = $ntuple;
1256 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1257 if ( $this->fileExists( $archivePath ) ) {
1258 $status->value
[$i] = 'archived';
1260 $status->value
[$i] = 'new';
1263 // Cleanup for disk source files...
1264 foreach ( $sourceFSFilesToDelete as $file ) {
1265 wfSuppressWarnings();
1266 unlink( $file ); // FS cleanup
1267 wfRestoreWarnings();
1274 * Creates a directory with the appropriate zone permissions.
1275 * Callers are responsible for doing read-only and "writable repo" checks.
1277 * @param string $dir Virtual URL (or storage path) of directory to clean
1280 protected function initDirectory( $dir ) {
1281 $path = $this->resolveToStoragePath( $dir );
1282 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1284 $params = array( 'dir' => $path );
1285 if ( $this->isPrivate ||
$container === $this->zones
['deleted']['container'] ) {
1286 # Take all available measures to prevent web accessibility of new deleted
1287 # directories, in case the user has not configured offline storage
1288 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1291 return $this->backend
->prepare( $params );
1295 * Deletes a directory if empty.
1297 * @param string $dir Virtual URL (or storage path) of directory to clean
1300 public function cleanDir( $dir ) {
1301 $this->assertWritableRepo(); // fail out if read-only
1303 $status = $this->newGood();
1304 $status->merge( $this->backend
->clean(
1305 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1311 * Checks existence of a a file
1313 * @param string $file Virtual URL (or storage path) of file to check
1316 public function fileExists( $file ) {
1317 $result = $this->fileExistsBatch( array( $file ) );
1323 * Checks existence of an array of files.
1325 * @param array $files Virtual URLs (or storage paths) of files to check
1326 * @return array|bool Either array of files and existence flags, or false
1328 public function fileExistsBatch( array $files ) {
1330 foreach ( $files as $key => $file ) {
1331 $file = $this->resolveToStoragePath( $file );
1332 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1339 * Move a file to the deletion archive.
1340 * If no valid deletion archive exists, this may either delete the file
1341 * or throw an exception, depending on the preference of the repository
1343 * @param mixed $srcRel Relative path for the file to be deleted
1344 * @param mixed $archiveRel Relative path for the archive location.
1345 * Relative to a private archive directory.
1346 * @return FileRepoStatus object
1348 public function delete( $srcRel, $archiveRel ) {
1349 $this->assertWritableRepo(); // fail out if read-only
1351 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1355 * Move a group of files to the deletion archive.
1357 * If no valid deletion archive is configured, this may either delete the
1358 * file or throw an exception, depending on the preference of the repository.
1360 * The overwrite policy is determined by the repository -- currently LocalRepo
1361 * assumes a naming scheme in the deleted zone based on content hash, as
1362 * opposed to the public zone which is assumed to be unique.
1364 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1365 * is a two-element array containing the source file path relative to the
1366 * public root in the first element, and the archive file path relative
1367 * to the deleted zone root in the second element.
1368 * @throws MWException
1369 * @return FileRepoStatus
1371 public function deleteBatch( array $sourceDestPairs ) {
1372 $this->assertWritableRepo(); // fail out if read-only
1374 // Try creating directories
1375 $status = $this->initZones( array( 'public', 'deleted' ) );
1376 if ( !$status->isOK() ) {
1380 $status = $this->newGood();
1382 $backend = $this->backend
; // convenience
1383 $operations = array();
1384 // Validate filenames and create archive directories
1385 foreach ( $sourceDestPairs as $pair ) {
1386 list( $srcRel, $archiveRel ) = $pair;
1387 if ( !$this->validateFilename( $srcRel ) ) {
1388 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1389 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1390 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1393 $publicRoot = $this->getZonePath( 'public' );
1394 $srcPath = "{$publicRoot}/$srcRel";
1396 $deletedRoot = $this->getZonePath( 'deleted' );
1397 $archivePath = "{$deletedRoot}/{$archiveRel}";
1398 $archiveDir = dirname( $archivePath ); // does not touch FS
1400 // Create destination directories
1401 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1402 return $this->newFatal( 'directorycreateerror', $archiveDir );
1405 $operations[] = array(
1408 'dst' => $archivePath,
1409 // We may have 2+ identical files being deleted,
1410 // all of which will map to the same destination file
1411 'overwriteSame' => true // also see bug 31792
1415 // Move the files by execute the operations for each pair.
1416 // We're now committed to returning an OK result, which will
1417 // lead to the files being moved in the DB also.
1418 $opts = array( 'force' => true );
1419 $status->merge( $backend->doOperations( $operations, $opts ) );
1425 * Delete files in the deleted directory if they are not referenced in the filearchive table
1429 public function cleanupDeletedBatch( array $storageKeys ) {
1430 $this->assertWritableRepo();
1434 * Get a relative path for a deletion archive key,
1435 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1437 * @param string $key
1438 * @throws MWException
1441 public function getDeletedHashPath( $key ) {
1442 if ( strlen( $key ) < 31 ) {
1443 throw new MWException( "Invalid storage key '$key'." );
1446 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1447 $path .= $key[$i] . '/';
1454 * If a path is a virtual URL, resolve it to a storage path.
1455 * Otherwise, just return the path as it is.
1457 * @param string $path
1459 * @throws MWException
1461 protected function resolveToStoragePath( $path ) {
1462 if ( $this->isVirtualUrl( $path ) ) {
1463 return $this->resolveVirtualUrl( $path );
1470 * Get a local FS copy of a file with a given virtual URL/storage path.
1471 * Temporary files may be purged when the file object falls out of scope.
1473 * @param string $virtualUrl
1474 * @return TempFSFile|null Returns null on failure
1476 public function getLocalCopy( $virtualUrl ) {
1477 $path = $this->resolveToStoragePath( $virtualUrl );
1479 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1483 * Get a local FS file with a given virtual URL/storage path.
1484 * The file is either an original or a copy. It should not be changed.
1485 * Temporary files may be purged when the file object falls out of scope.
1487 * @param string $virtualUrl
1488 * @return FSFile|null Returns null on failure.
1490 public function getLocalReference( $virtualUrl ) {
1491 $path = $this->resolveToStoragePath( $virtualUrl );
1493 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1497 * Get properties of a file with a given virtual URL/storage path.
1498 * Properties should ultimately be obtained via FSFile::getProps().
1500 * @param string $virtualUrl
1503 public function getFileProps( $virtualUrl ) {
1504 $path = $this->resolveToStoragePath( $virtualUrl );
1506 return $this->backend
->getFileProps( array( 'src' => $path ) );
1510 * Get the timestamp of a file with a given virtual URL/storage path
1512 * @param string $virtualUrl
1513 * @return string|bool False on failure
1515 public function getFileTimestamp( $virtualUrl ) {
1516 $path = $this->resolveToStoragePath( $virtualUrl );
1518 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1522 * Get the size of a file with a given virtual URL/storage path
1524 * @param string $virtualUrl
1525 * @return integer|bool False on failure
1527 public function getFileSize( $virtualUrl ) {
1528 $path = $this->resolveToStoragePath( $virtualUrl );
1530 return $this->backend
->getFileSize( array( 'src' => $path ) );
1534 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1536 * @param string $virtualUrl
1537 * @return string|bool
1539 public function getFileSha1( $virtualUrl ) {
1540 $path = $this->resolveToStoragePath( $virtualUrl );
1542 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1546 * Attempt to stream a file with the given virtual URL/storage path
1548 * @param string $virtualUrl
1549 * @param array $headers Additional HTTP headers to send on success
1550 * @return bool Success
1552 public function streamFile( $virtualUrl, $headers = array() ) {
1553 $path = $this->resolveToStoragePath( $virtualUrl );
1554 $params = array( 'src' => $path, 'headers' => $headers );
1556 return $this->backend
->streamFile( $params )->isOK();
1560 * Call a callback function for every public regular file in the repository.
1561 * This only acts on the current version of files, not any old versions.
1562 * May use either the database or the filesystem.
1564 * @param array|string $callback
1567 public function enumFiles( $callback ) {
1568 $this->enumFilesInStorage( $callback );
1572 * Call a callback function for every public file in the repository.
1573 * May use either the database or the filesystem.
1575 * @param array|string $callback
1578 protected function enumFilesInStorage( $callback ) {
1579 $publicRoot = $this->getZonePath( 'public' );
1580 $numDirs = 1 << ( $this->hashLevels
* 4 );
1581 // Use a priori assumptions about directory structure
1582 // to reduce the tree height of the scanning process.
1583 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1584 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1585 $path = $publicRoot;
1586 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1587 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1589 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1590 foreach ( $iterator as $name ) {
1591 // Each item returned is a public file
1592 call_user_func( $callback, "{$path}/{$name}" );
1598 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1600 * @param $filename string
1603 public function validateFilename( $filename ) {
1604 if ( strval( $filename ) == '' ) {
1608 return FileBackend
::isPathTraversalFree( $filename );
1612 * Get a callback function to use for cleaning error message parameters
1616 function getErrorCleanupFunction() {
1617 switch ( $this->pathDisclosureProtection
) {
1619 case 'simple': // b/c
1620 $callback = array( $this, 'passThrough' );
1622 default: // 'paranoid'
1623 $callback = array( $this, 'paranoidClean' );
1629 * Path disclosure protection function
1631 * @param string $param
1634 function paranoidClean( $param ) {
1639 * Path disclosure protection function
1641 * @param string $param
1644 function passThrough( $param ) {
1649 * 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 null|string $value
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 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 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." );