3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
33 * Base class for file repositories
38 const DELETE_SOURCE
= 1;
40 const OVERWRITE_SAME
= 4;
41 const SKIP_LOCKING
= 8;
43 const NAME_AND_TIME_ONLY
= 1;
45 /** @var bool Whether to fetch commons image description pages and display
46 * them on the local wiki */
47 public $fetchDescription;
50 public $descriptionCacheExpiry;
53 protected $hasSha1Storage = false;
55 /** @var FileBackend */
58 /** @var array Map of zones to config */
59 protected $zones = array();
61 /** @var string URL of thumb.php */
62 protected $thumbScriptUrl;
64 /** @var bool Whether to skip media file transformation on parse and rely
65 * on a 404 handler instead. */
66 protected $transformVia404;
68 /** @var string URL of image description pages, e.g.
69 * https://en.wikipedia.org/wiki/File:
71 protected $descBaseUrl;
73 /** @var string URL of the MediaWiki installation, equivalent to
74 * $wgScriptPath, e.g. https://en.wikipedia.org/w
76 protected $scriptDirUrl;
78 /** @var string Script extension of the MediaWiki installation, equivalent
79 * to $wgScriptExtension, e.g. .php5 defaults to .php */
80 protected $scriptExtension;
82 /** @var string Equivalent to $wgArticlePath, e.g. https://en.wikipedia.org/wiki/$1 */
83 protected $articleUrl;
85 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
86 * determines whether filenames implicitly start with a capital letter.
87 * The current implementation may give incorrect description page links
88 * when the local $wgCapitalLinks and initialCapital are mismatched.
90 protected $initialCapital;
92 /** @var string May be 'paranoid' to remove all parameters from error
93 * messages, 'none' to leave the paths in unchanged, or 'simple' to
94 * replace paths with placeholders. Default for LocalRepo is
97 protected $pathDisclosureProtection = 'simple';
99 /** @var bool Public zone URL. */
102 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
105 /** @var int The number of directory levels for hash-based division of files */
106 protected $hashLevels;
108 /** @var int The number of directory levels for hash-based division of deleted files */
109 protected $deletedHashLevels;
111 /** @var int File names over this size will use the short form of thumbnail
112 * names. Short thumbnail names only have the width, parameters, and the
115 protected $abbrvThreshold;
117 /** @var string The URL of the repo's favicon, if any */
120 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
121 protected $isPrivate;
124 * Factory functions for creating new files
125 * Override these in the base class
127 protected $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
128 protected $oldFileFactory = false;
129 protected $fileFactoryKey = false;
130 protected $oldFileFactoryKey = false;
133 * @param array|null $info
134 * @throws MWException
136 public function __construct( array $info = null ) {
137 // Verify required settings presence
140 ||
!array_key_exists( 'name', $info )
141 ||
!array_key_exists( 'backend', $info )
143 throw new MWException( __CLASS__
.
144 " requires an array of options having both 'name' and 'backend' keys.\n" );
148 $this->name
= $info['name'];
149 if ( $info['backend'] instanceof FileBackend
) {
150 $this->backend
= $info['backend']; // useful for testing
152 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
155 // Optional settings that can have no value
156 $optionalSettings = array(
157 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
158 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
159 'scriptExtension', 'favicon'
161 foreach ( $optionalSettings as $var ) {
162 if ( isset( $info[$var] ) ) {
163 $this->$var = $info[$var];
167 // Optional settings that have a default
168 $this->initialCapital
= isset( $info['initialCapital'] )
169 ?
$info['initialCapital']
170 : MWNamespace
::isCapitalized( NS_FILE
);
171 $this->url
= isset( $info['url'] )
173 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
174 if ( isset( $info['thumbUrl'] ) ) {
175 $this->thumbUrl
= $info['thumbUrl'];
177 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
179 $this->hashLevels
= isset( $info['hashLevels'] )
180 ?
$info['hashLevels']
182 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
183 ?
$info['deletedHashLevels']
185 $this->transformVia404
= !empty( $info['transformVia404'] );
186 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
187 ?
$info['abbrvThreshold']
189 $this->isPrivate
= !empty( $info['isPrivate'] );
190 // Give defaults for the basic zones...
191 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
192 foreach ( array( 'public', 'thumb', 'transcoded', 'temp', 'deleted' ) as $zone ) {
193 if ( !isset( $this->zones
[$zone]['container'] ) ) {
194 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
196 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
197 $this->zones
[$zone]['directory'] = '';
199 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
200 $this->zones
[$zone]['urlsByExt'] = array();
206 * Get the file backend instance. Use this function wisely.
208 * @return FileBackend
210 public function getBackend() {
211 return $this->backend
;
215 * Get an explanatory message if this repo is read-only.
216 * This checks if an administrator disabled writes to the backend.
218 * @return string|bool Returns false if the repo is not read-only
220 public function getReadOnlyReason() {
221 return $this->backend
->getReadOnlyReason();
225 * Check if a single zone or list of zones is defined for usage
227 * @param array $doZones Only do a particular zones
228 * @throws MWException
231 protected function initZones( $doZones = array() ) {
232 $status = $this->newGood();
233 foreach ( (array)$doZones as $zone ) {
234 $root = $this->getZonePath( $zone );
235 if ( $root === null ) {
236 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
244 * Determine if a string is an mwrepo:// URL
249 public static function isVirtualUrl( $url ) {
250 return substr( $url, 0, 9 ) == 'mwrepo://';
254 * Get a URL referring to this repository, with the private mwrepo protocol.
255 * The suffix, if supplied, is considered to be unencoded, and will be
256 * URL-encoded before being returned.
258 * @param string|bool $suffix
261 public function getVirtualUrl( $suffix = false ) {
262 $path = 'mwrepo://' . $this->name
;
263 if ( $suffix !== false ) {
264 $path .= '/' . rawurlencode( $suffix );
271 * Get the URL corresponding to one of the four basic zones
273 * @param string $zone One of: public, deleted, temp, thumb
274 * @param string|null $ext Optional file extension
275 * @return string|bool
277 public function getZoneUrl( $zone, $ext = null ) {
278 if ( in_array( $zone, array( 'public', 'thumb', 'transcoded' ) ) ) {
279 // standard public zones
280 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
281 // custom URL for extension/zone
282 return $this->zones
[$zone]['urlsByExt'][$ext];
283 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
284 // custom URL for zone
285 return $this->zones
[$zone]['url'];
293 return false; // no public URL
295 return $this->thumbUrl
;
297 return "{$this->url}/transcoded";
304 * @return bool Whether non-ASCII path characters are allowed
306 public function backendSupportsUnicodePaths() {
307 return ( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
311 * Get the backend storage path corresponding to a virtual URL.
312 * Use this function wisely.
315 * @throws MWException
318 public function resolveVirtualUrl( $url ) {
319 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
320 throw new MWException( __METHOD__
. ': unknown protocol' );
322 $bits = explode( '/', substr( $url, 9 ), 3 );
323 if ( count( $bits ) != 3 ) {
324 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
326 list( $repo, $zone, $rel ) = $bits;
327 if ( $repo !== $this->name
) {
328 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
330 $base = $this->getZonePath( $zone );
332 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
335 return $base . '/' . rawurldecode( $rel );
339 * The the storage container and base path of a zone
341 * @param string $zone
342 * @return array (container, base path) or (null, null)
344 protected function getZoneLocation( $zone ) {
345 if ( !isset( $this->zones
[$zone] ) ) {
346 return array( null, null ); // bogus
349 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
353 * Get the storage path corresponding to one of the zones
355 * @param string $zone
356 * @return string|null Returns null if the zone is not defined
358 public function getZonePath( $zone ) {
359 list( $container, $base ) = $this->getZoneLocation( $zone );
360 if ( $container === null ||
$base === null ) {
363 $backendName = $this->backend
->getName();
364 if ( $base != '' ) { // may not be set
368 return "mwstore://$backendName/{$container}{$base}";
372 * Create a new File object from the local repository
374 * @param Title|string $title Title object or string
375 * @param bool|string $time Time at which the image was uploaded. If this
376 * is specified, the returned object will be an instance of the
377 * repository's old file class instead of a current file. Repositories
378 * not supporting version control should return false if this parameter
380 * @return File|null A File, or null if passed an invalid Title
382 public function newFile( $title, $time = false ) {
383 $title = File
::normalizeTitle( $title );
388 if ( $this->oldFileFactory
) {
389 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
394 return call_user_func( $this->fileFactory
, $title, $this );
399 * Find an instance of the named file created at the specified time
400 * Returns false if the file does not exist. Repositories not supporting
401 * version control should return false if the time is specified.
403 * @param Title|string $title Title object or string
404 * @param array $options Associative array of options:
405 * time: requested time for a specific file version, or false for the
406 * current version. An image object will be returned which was
407 * created at the specified time (which may be archived or current).
408 * ignoreRedirect: If true, do not follow file redirects
409 * private: If true, return restricted (deleted) files if the current
410 * user is allowed to view them. Otherwise, such files will not
411 * be found. If a User object, use that user instead of the current.
412 * latest: If true, load from the latest available data into File objects
413 * @return File|bool False on failure
415 public function findFile( $title, $options = array() ) {
416 $title = File
::normalizeTitle( $title );
420 if ( isset( $options['bypassCache'] ) ) {
421 $options['latest'] = $options['bypassCache']; // b/c
423 $time = isset( $options['time'] ) ?
$options['time'] : false;
424 $flags = !empty( $options['latest'] ) ? File
::READ_LATEST
: 0;
425 # First try the current version of the file to see if it precedes the timestamp
426 $img = $this->newFile( $title );
430 $img->load( $flags );
431 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
434 # Now try an old version of the file
435 if ( $time !== false ) {
436 $img = $this->newFile( $title, $time );
438 $img->load( $flags );
439 if ( $img->exists() ) {
440 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
441 return $img; // always OK
442 } elseif ( !empty( $options['private'] ) &&
443 $img->userCan( File
::DELETED_FILE
,
444 $options['private'] instanceof User ?
$options['private'] : null
454 if ( !empty( $options['ignoreRedirect'] ) ) {
457 $redir = $this->checkRedirect( $title );
458 if ( $redir && $title->getNamespace() == NS_FILE
) {
459 $img = $this->newFile( $redir );
463 $img->load( $flags );
464 if ( $img->exists() ) {
465 $img->redirectedFrom( $title->getDBkey() );
475 * Find many files at once.
477 * @param array $items An array of titles, or an array of findFile() options with
478 * the "title" option giving the title. Example:
480 * $findItem = array( 'title' => $title, 'private' => true );
481 * $findBatch = array( $findItem );
482 * $repo->findFiles( $findBatch );
484 * No title should appear in $items twice, as the result use titles as keys
485 * @param int $flags Supports:
486 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
487 * The search title uses the input titles; the other is the final post-redirect title.
488 * All titles are returned as string DB keys and the inner array is associative.
489 * @return array Map of (file name => File objects) for matches
491 public function findFiles( array $items, $flags = 0 ) {
493 foreach ( $items as $item ) {
494 if ( is_array( $item ) ) {
495 $title = $item['title'];
497 unset( $options['title'] );
502 $file = $this->findFile( $title, $options );
504 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
505 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
506 $result[$searchName] = array(
507 'title' => $file->getTitle()->getDBkey(),
508 'timestamp' => $file->getTimestamp()
511 $result[$searchName] = $file;
520 * Find an instance of the file with this key, created at the specified time
521 * Returns false if the file does not exist. Repositories not supporting
522 * version control should return false if the time is specified.
524 * @param string $sha1 Base 36 SHA-1 hash
525 * @param array $options Option array, same as findFile().
526 * @return File|bool False on failure
528 public function findFileFromKey( $sha1, $options = array() ) {
529 $time = isset( $options['time'] ) ?
$options['time'] : false;
530 # First try to find a matching current version of a file...
531 if ( $this->fileFactoryKey
) {
532 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
534 return false; // find-by-sha1 not supported
536 if ( $img && $img->exists() ) {
539 # Now try to find a matching old version of a file...
540 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
541 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
542 if ( $img && $img->exists() ) {
543 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
544 return $img; // always OK
545 } elseif ( !empty( $options['private'] ) &&
546 $img->userCan( File
::DELETED_FILE
,
547 $options['private'] instanceof User ?
$options['private'] : null
559 * Get an array or iterator of file objects for files that have a given
560 * SHA-1 content hash.
563 * @param string $hash SHA-1 hash
566 public function findBySha1( $hash ) {
571 * Get an array of arrays or iterators of file objects for files that
572 * have the given SHA-1 content hashes.
574 * @param array $hashes An array of hashes
575 * @return array An Array of arrays or iterators of file objects and the hash as key
577 public function findBySha1s( array $hashes ) {
579 foreach ( $hashes as $hash ) {
580 $files = $this->findBySha1( $hash );
581 if ( count( $files ) ) {
582 $result[$hash] = $files;
590 * Return an array of files where the name starts with $prefix.
593 * @param string $prefix The prefix to search for
594 * @param int $limit The maximum amount of files to return
597 public function findFilesByPrefix( $prefix, $limit ) {
602 * Get the public root URL of the repository
604 * @deprecated since 1.20
607 public function getRootUrl() {
608 return $this->getZoneUrl( 'public' );
612 * Get the URL of thumb.php
616 public function getThumbScriptUrl() {
617 return $this->thumbScriptUrl
;
621 * Returns true if the repository can transform files via a 404 handler
625 public function canTransformVia404() {
626 return $this->transformVia404
;
630 * Get the name of a file from its title object
632 * @param Title $title
635 public function getNameFromTitle( Title
$title ) {
637 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
638 $name = $title->getUserCaseDBKey();
639 if ( $this->initialCapital
) {
640 $name = $wgContLang->ucfirst( $name );
643 $name = $title->getDBkey();
650 * Get the public zone root storage directory of the repository
654 public function getRootDirectory() {
655 return $this->getZonePath( 'public' );
659 * Get a relative path including trailing slash, e.g. f/fa/
660 * If the repo is not hashed, returns an empty string
662 * @param string $name Name of file
665 public function getHashPath( $name ) {
666 return self
::getHashPathForLevel( $name, $this->hashLevels
);
670 * Get a relative path including trailing slash, e.g. f/fa/
671 * If the repo is not hashed, returns an empty string
673 * @param string $suffix Basename of file from FileRepo::storeTemp()
676 public function getTempHashPath( $suffix ) {
677 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
678 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
679 return self
::getHashPathForLevel( $name, $this->hashLevels
);
683 * @param string $name
687 protected static function getHashPathForLevel( $name, $levels ) {
688 if ( $levels == 0 ) {
691 $hash = md5( $name );
693 for ( $i = 1; $i <= $levels; $i++
) {
694 $path .= substr( $hash, 0, $i ) . '/';
702 * Get the number of hash directory levels
706 public function getHashLevels() {
707 return $this->hashLevels
;
711 * Get the name of this repository, as specified by $info['name]' to the constructor
715 public function getName() {
720 * Make an url to this repo
722 * @param string $query Query string to append
723 * @param string $entry Entry point; defaults to index
724 * @return string|bool False on failure
726 public function makeUrl( $query = '', $entry = 'index' ) {
727 if ( isset( $this->scriptDirUrl
) ) {
728 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
730 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
737 * Get the URL of an image description page. May return false if it is
738 * unknown or not applicable. In general this should only be called by the
739 * File class, since it may return invalid results for certain kinds of
740 * repositories. Use File::getDescriptionUrl() in user code.
742 * In particular, it uses the article paths as specified to the repository
743 * constructor, whereas local repositories use the local Title functions.
745 * @param string $name
748 public function getDescriptionUrl( $name ) {
749 $encName = wfUrlencode( $name );
750 if ( !is_null( $this->descBaseUrl
) ) {
751 # "http://example.com/wiki/File:"
752 return $this->descBaseUrl
. $encName;
754 if ( !is_null( $this->articleUrl
) ) {
755 # "http://example.com/wiki/$1"
756 # We use "Image:" as the canonical namespace for
757 # compatibility across all MediaWiki versions.
758 return str_replace( '$1',
759 "Image:$encName", $this->articleUrl
);
761 if ( !is_null( $this->scriptDirUrl
) ) {
762 # "http://example.com/w"
763 # We use "Image:" as the canonical namespace for
764 # compatibility across all MediaWiki versions,
765 # and just sort of hope index.php is right. ;)
766 return $this->makeUrl( "title=Image:$encName" );
773 * Get the URL of the content-only fragment of the description page. For
774 * MediaWiki this means action=render. This should only be called by the
775 * repository's file class, since it may return invalid results. User code
776 * should use File::getDescriptionText().
778 * @param string $name Name of image to fetch
779 * @param string $lang Language to fetch it in, if any.
782 public function getDescriptionRenderUrl( $name, $lang = null ) {
783 $query = 'action=render';
784 if ( !is_null( $lang ) ) {
785 $query .= '&uselang=' . $lang;
787 if ( isset( $this->scriptDirUrl
) ) {
788 return $this->makeUrl(
790 wfUrlencode( 'Image:' . $name ) .
793 $descUrl = $this->getDescriptionUrl( $name );
795 return wfAppendQuery( $descUrl, $query );
803 * Get the URL of the stylesheet to apply to description pages
805 * @return string|bool False on failure
807 public function getDescriptionStylesheetUrl() {
808 if ( isset( $this->scriptDirUrl
) ) {
809 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
810 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
817 * Store a file to a given destination.
819 * @param string $srcPath Source file system path, storage path, or virtual URL
820 * @param string $dstZone Destination zone
821 * @param string $dstRel Destination relative path
822 * @param int $flags 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 * @return FileRepoStatus
830 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
831 $this->assertWritableRepo(); // fail out if read-only
833 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
834 if ( $status->successCount
== 0 ) {
842 * Store a batch of files
844 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
845 * @param int $flags Bitwise combination of the following flags:
846 * self::DELETE_SOURCE Delete the source file after upload
847 * self::OVERWRITE Overwrite an existing destination file instead of failing
848 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
849 * same contents as the source
850 * self::SKIP_LOCKING Skip any file locking when doing the store
851 * @throws MWException
852 * @return FileRepoStatus
854 public function storeBatch( array $triplets, $flags = 0 ) {
855 $this->assertWritableRepo(); // fail out if read-only
857 $status = $this->newGood();
858 $backend = $this->backend
; // convenience
860 $operations = array();
861 $sourceFSFilesToDelete = array(); // cleanup for disk source files
862 // Validate each triplet and get the store operation...
863 foreach ( $triplets as $triplet ) {
864 list( $srcPath, $dstZone, $dstRel ) = $triplet;
866 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
869 // Resolve destination path
870 $root = $this->getZonePath( $dstZone );
872 throw new MWException( "Invalid zone: $dstZone" );
874 if ( !$this->validateFilename( $dstRel ) ) {
875 throw new MWException( 'Validation error in $dstRel' );
877 $dstPath = "$root/$dstRel";
878 $dstDir = dirname( $dstPath );
879 // Create destination directories for this triplet
880 if ( !$this->initDirectory( $dstDir )->isOK() ) {
881 return $this->newFatal( 'directorycreateerror', $dstDir );
884 // Resolve source to a storage path if virtual
885 $srcPath = $this->resolveToStoragePath( $srcPath );
887 // Get the appropriate file operation
888 if ( FileBackend
::isStoragePath( $srcPath ) ) {
889 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
892 if ( $flags & self
::DELETE_SOURCE
) {
893 $sourceFSFilesToDelete[] = $srcPath;
896 $operations[] = array(
900 'overwrite' => $flags & self
::OVERWRITE
,
901 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
905 // Execute the store operation for each triplet
906 $opts = array( 'force' => true );
907 if ( $flags & self
::SKIP_LOCKING
) {
908 $opts['nonLocking'] = true;
910 $status->merge( $backend->doOperations( $operations, $opts ) );
911 // Cleanup for disk source files...
912 foreach ( $sourceFSFilesToDelete as $file ) {
913 MediaWiki\
suppressWarnings();
914 unlink( $file ); // FS cleanup
915 MediaWiki\restoreWarnings
();
922 * Deletes a batch of files.
923 * Each file can be a (zone, rel) pair, virtual url, storage path.
924 * It will try to delete each file, but ignores any errors that may occur.
926 * @param array $files List of files to delete
927 * @param int $flags Bitwise combination of the following flags:
928 * self::SKIP_LOCKING Skip any file locking when doing the deletions
929 * @return FileRepoStatus
931 public function cleanupBatch( array $files, $flags = 0 ) {
932 $this->assertWritableRepo(); // fail out if read-only
934 $status = $this->newGood();
936 $operations = array();
937 foreach ( $files as $path ) {
938 if ( is_array( $path ) ) {
939 // This is a pair, extract it
940 list( $zone, $rel ) = $path;
941 $path = $this->getZonePath( $zone ) . "/$rel";
943 // Resolve source to a storage path if virtual
944 $path = $this->resolveToStoragePath( $path );
946 $operations[] = array( 'op' => 'delete', 'src' => $path );
948 // Actually delete files from storage...
949 $opts = array( 'force' => true );
950 if ( $flags & self
::SKIP_LOCKING
) {
951 $opts['nonLocking'] = true;
953 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
959 * Import a file from the local file system into the repo.
960 * This does no locking nor journaling and overrides existing files.
961 * This function can be used to write to otherwise read-only foreign repos.
962 * This is intended for copying generated thumbnails into the repo.
964 * @param string $src Source file system path, storage path, or virtual URL
965 * @param string $dst Virtual URL or storage path
966 * @param array|string|null $options An array consisting of a key named headers
967 * listing extra headers. If a string, taken as content-disposition header.
968 * (Support for array of options new in 1.23)
969 * @return FileRepoStatus
971 final public function quickImport( $src, $dst, $options = null ) {
972 return $this->quickImportBatch( array( array( $src, $dst, $options ) ) );
976 * Purge a file from the repo. This does no locking nor journaling.
977 * This function can be used to write to otherwise read-only foreign repos.
978 * This is intended for purging thumbnails.
980 * @param string $path Virtual URL or storage path
981 * @return FileRepoStatus
983 final public function quickPurge( $path ) {
984 return $this->quickPurgeBatch( array( $path ) );
988 * Deletes a directory if empty.
989 * This function can be used to write to otherwise read-only foreign repos.
991 * @param string $dir Virtual URL (or storage path) of directory to clean
994 public function quickCleanDir( $dir ) {
995 $status = $this->newGood();
996 $status->merge( $this->backend
->clean(
997 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1003 * Import a batch of files from the local file system into the repo.
1004 * This does no locking nor journaling and overrides existing files.
1005 * This function can be used to write to otherwise read-only foreign repos.
1006 * This is intended for copying generated thumbnails into the repo.
1008 * All path parameters may be a file system path, storage path, or virtual URL.
1009 * When "headers" are given they are used as HTTP headers if supported.
1011 * @param array $triples List of (source path, destination path, disposition)
1012 * @return FileRepoStatus
1014 public function quickImportBatch( array $triples ) {
1015 $status = $this->newGood();
1016 $operations = array();
1017 foreach ( $triples as $triple ) {
1018 list( $src, $dst ) = $triple;
1019 $src = $this->resolveToStoragePath( $src );
1020 $dst = $this->resolveToStoragePath( $dst );
1022 if ( !isset( $triple[2] ) ) {
1024 } elseif ( is_string( $triple[2] ) ) {
1026 $headers = array( 'Content-Disposition' => $triple[2] );
1027 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1028 $headers = $triple[2]['headers'];
1030 // @fixme: $headers might not be defined
1031 $operations[] = array(
1032 'op' => FileBackend
::isStoragePath( $src ) ?
'copy' : 'store',
1035 'headers' => $headers
1037 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1039 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1045 * Purge a batch of files from the repo.
1046 * This function can be used to write to otherwise read-only foreign repos.
1047 * This does no locking nor journaling and is intended for purging thumbnails.
1049 * @param array $paths List of virtual URLs or storage paths
1050 * @return FileRepoStatus
1052 public function quickPurgeBatch( array $paths ) {
1053 $status = $this->newGood();
1054 $operations = array();
1055 foreach ( $paths as $path ) {
1056 $operations[] = array(
1058 'src' => $this->resolveToStoragePath( $path ),
1059 'ignoreMissingSource' => true
1062 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1068 * Pick a random name in the temp zone and store a file to it.
1069 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1070 * file can later be disposed using FileRepo::freeTemp().
1072 * @param string $originalName The base name of the file as specified
1073 * by the user. The file extension will be maintained.
1074 * @param string $srcPath The current location of the file.
1075 * @return FileRepoStatus Object with the URL in the value.
1077 public function storeTemp( $originalName, $srcPath ) {
1078 $this->assertWritableRepo(); // fail out if read-only
1080 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1081 $hashPath = $this->getHashPath( $originalName );
1082 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1083 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1085 $result = $this->quickImport( $srcPath, $virtualUrl );
1086 $result->value
= $virtualUrl;
1092 * Remove a temporary file or mark it for garbage collection
1094 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1095 * @return bool True on success, false on failure
1097 public function freeTemp( $virtualUrl ) {
1098 $this->assertWritableRepo(); // fail out if read-only
1100 $temp = $this->getVirtualUrl( 'temp' );
1101 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1102 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1107 return $this->quickPurge( $virtualUrl )->isOK();
1111 * Concatenate a list of temporary files into a target file location.
1113 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1114 * @param string $dstPath Target file system path
1115 * @param int $flags Bitwise combination of the following flags:
1116 * self::DELETE_SOURCE Delete the source files
1117 * @return FileRepoStatus
1119 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1120 $this->assertWritableRepo(); // fail out if read-only
1122 $status = $this->newGood();
1125 foreach ( $srcPaths as $srcPath ) {
1126 // Resolve source to a storage path if virtual
1127 $source = $this->resolveToStoragePath( $srcPath );
1128 $sources[] = $source; // chunk to merge
1131 // Concatenate the chunks into one FS file
1132 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1133 $status->merge( $this->backend
->concatenate( $params ) );
1134 if ( !$status->isOK() ) {
1138 // Delete the sources if required
1139 if ( $flags & self
::DELETE_SOURCE
) {
1140 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1143 // Make sure status is OK, despite any quickPurgeBatch() fatals
1144 $status->setResult( true );
1150 * Copy or move a file either from a storage path, virtual URL,
1151 * or file system path, into this repository at the specified destination location.
1153 * Returns a FileRepoStatus object. On success, the value contains "new" or
1154 * "archived", to indicate whether the file was new with that name.
1156 * Options to $options include:
1157 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1159 * @param string $srcPath The source file system path, storage path, or URL
1160 * @param string $dstRel The destination relative path
1161 * @param string $archiveRel The relative path where the existing file is to
1162 * be archived, if there is one. Relative to the public zone root.
1163 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1164 * that the source file should be deleted if possible
1165 * @param array $options Optional additional parameters
1166 * @return FileRepoStatus
1168 public function publish(
1169 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1171 $this->assertWritableRepo(); // fail out if read-only
1173 $status = $this->publishBatch(
1174 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1175 if ( $status->successCount
== 0 ) {
1176 $status->ok
= false;
1178 if ( isset( $status->value
[0] ) ) {
1179 $status->value
= $status->value
[0];
1181 $status->value
= false;
1188 * Publish a batch of files
1190 * @param array $ntuples (source, dest, archive) triplets or
1191 * (source, dest, archive, options) 4-tuples as per publish().
1192 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1193 * that the source files should be deleted if possible
1194 * @throws MWException
1195 * @return FileRepoStatus
1197 public function publishBatch( array $ntuples, $flags = 0 ) {
1198 $this->assertWritableRepo(); // fail out if read-only
1200 $backend = $this->backend
; // convenience
1201 // Try creating directories
1202 $status = $this->initZones( 'public' );
1203 if ( !$status->isOK() ) {
1207 $status = $this->newGood( array() );
1209 $operations = array();
1210 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1211 // Validate each triplet and get the store operation...
1212 foreach ( $ntuples as $ntuple ) {
1213 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1214 $options = isset( $ntuple[3] ) ?
$ntuple[3] : array();
1215 // Resolve source to a storage path if virtual
1216 $srcPath = $this->resolveToStoragePath( $srcPath );
1217 if ( !$this->validateFilename( $dstRel ) ) {
1218 throw new MWException( 'Validation error in $dstRel' );
1220 if ( !$this->validateFilename( $archiveRel ) ) {
1221 throw new MWException( 'Validation error in $archiveRel' );
1224 $publicRoot = $this->getZonePath( 'public' );
1225 $dstPath = "$publicRoot/$dstRel";
1226 $archivePath = "$publicRoot/$archiveRel";
1228 $dstDir = dirname( $dstPath );
1229 $archiveDir = dirname( $archivePath );
1230 // Abort immediately on directory creation errors since they're likely to be repetitive
1231 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1232 return $this->newFatal( 'directorycreateerror', $dstDir );
1234 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1235 return $this->newFatal( 'directorycreateerror', $archiveDir );
1238 // Set any desired headers to be use in GET/HEAD responses
1239 $headers = isset( $options['headers'] ) ?
$options['headers'] : array();
1241 // Archive destination file if it exists.
1242 // This will check if the archive file also exists and fail if does.
1243 // This is a sanity check to avoid data loss. On Windows and Linux,
1244 // copy() will overwrite, so the existence check is vulnerable to
1245 // race conditions unless a functioning LockManager is used.
1246 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1247 $operations[] = array(
1250 'dst' => $archivePath,
1251 'ignoreMissingSource' => true
1254 // Copy (or move) the source file to the destination
1255 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1256 if ( $flags & self
::DELETE_SOURCE
) {
1257 $operations[] = array(
1261 'overwrite' => true, // replace current
1262 'headers' => $headers
1265 $operations[] = array(
1269 'overwrite' => true, // replace current
1270 'headers' => $headers
1273 } else { // FS source path
1274 $operations[] = array(
1278 'overwrite' => true, // replace current
1279 'headers' => $headers
1281 if ( $flags & self
::DELETE_SOURCE
) {
1282 $sourceFSFilesToDelete[] = $srcPath;
1287 // Execute the operations for each triplet
1288 $status->merge( $backend->doOperations( $operations ) );
1289 // Find out which files were archived...
1290 foreach ( $ntuples as $i => $ntuple ) {
1291 list( , , $archiveRel ) = $ntuple;
1292 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1293 if ( $this->fileExists( $archivePath ) ) {
1294 $status->value
[$i] = 'archived';
1296 $status->value
[$i] = 'new';
1299 // Cleanup for disk source files...
1300 foreach ( $sourceFSFilesToDelete as $file ) {
1301 MediaWiki\
suppressWarnings();
1302 unlink( $file ); // FS cleanup
1303 MediaWiki\restoreWarnings
();
1310 * Creates a directory with the appropriate zone permissions.
1311 * Callers are responsible for doing read-only and "writable repo" checks.
1313 * @param string $dir Virtual URL (or storage path) of directory to clean
1316 protected function initDirectory( $dir ) {
1317 $path = $this->resolveToStoragePath( $dir );
1318 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1320 $params = array( 'dir' => $path );
1321 if ( $this->isPrivate
1322 ||
$container === $this->zones
['deleted']['container']
1323 ||
$container === $this->zones
['temp']['container']
1325 # Take all available measures to prevent web accessibility of new deleted
1326 # directories, in case the user has not configured offline storage
1327 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1330 return $this->backend
->prepare( $params );
1334 * Deletes a directory if empty.
1336 * @param string $dir Virtual URL (or storage path) of directory to clean
1339 public function cleanDir( $dir ) {
1340 $this->assertWritableRepo(); // fail out if read-only
1342 $status = $this->newGood();
1343 $status->merge( $this->backend
->clean(
1344 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1350 * Checks existence of a a file
1352 * @param string $file Virtual URL (or storage path) of file to check
1355 public function fileExists( $file ) {
1356 $result = $this->fileExistsBatch( array( $file ) );
1362 * Checks existence of an array of files.
1364 * @param array $files Virtual URLs (or storage paths) of files to check
1365 * @return array Map of files and existence flags, or false
1367 public function fileExistsBatch( array $files ) {
1368 $paths = array_map( array( $this, 'resolveToStoragePath' ), $files );
1369 $this->backend
->preloadFileStat( array( 'srcs' => $paths ) );
1372 foreach ( $files as $key => $file ) {
1373 $path = $this->resolveToStoragePath( $file );
1374 $result[$key] = $this->backend
->fileExists( array( 'src' => $path ) );
1381 * Move a file to the deletion archive.
1382 * If no valid deletion archive exists, this may either delete the file
1383 * or throw an exception, depending on the preference of the repository
1385 * @param mixed $srcRel Relative path for the file to be deleted
1386 * @param mixed $archiveRel Relative path for the archive location.
1387 * Relative to a private archive directory.
1388 * @return FileRepoStatus
1390 public function delete( $srcRel, $archiveRel ) {
1391 $this->assertWritableRepo(); // fail out if read-only
1393 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1397 * Move a group of files to the deletion archive.
1399 * If no valid deletion archive is configured, this may either delete the
1400 * file or throw an exception, depending on the preference of the repository.
1402 * The overwrite policy is determined by the repository -- currently LocalRepo
1403 * assumes a naming scheme in the deleted zone based on content hash, as
1404 * opposed to the public zone which is assumed to be unique.
1406 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1407 * is a two-element array containing the source file path relative to the
1408 * public root in the first element, and the archive file path relative
1409 * to the deleted zone root in the second element.
1410 * @throws MWException
1411 * @return FileRepoStatus
1413 public function deleteBatch( array $sourceDestPairs ) {
1414 $this->assertWritableRepo(); // fail out if read-only
1416 // Try creating directories
1417 $status = $this->initZones( array( 'public', 'deleted' ) );
1418 if ( !$status->isOK() ) {
1422 $status = $this->newGood();
1424 $backend = $this->backend
; // convenience
1425 $operations = array();
1426 // Validate filenames and create archive directories
1427 foreach ( $sourceDestPairs as $pair ) {
1428 list( $srcRel, $archiveRel ) = $pair;
1429 if ( !$this->validateFilename( $srcRel ) ) {
1430 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1431 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1432 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1435 $publicRoot = $this->getZonePath( 'public' );
1436 $srcPath = "{$publicRoot}/$srcRel";
1438 $deletedRoot = $this->getZonePath( 'deleted' );
1439 $archivePath = "{$deletedRoot}/{$archiveRel}";
1440 $archiveDir = dirname( $archivePath ); // does not touch FS
1442 // Create destination directories
1443 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1444 return $this->newFatal( 'directorycreateerror', $archiveDir );
1447 $operations[] = array(
1450 'dst' => $archivePath,
1451 // We may have 2+ identical files being deleted,
1452 // all of which will map to the same destination file
1453 'overwriteSame' => true // also see bug 31792
1457 // Move the files by execute the operations for each pair.
1458 // We're now committed to returning an OK result, which will
1459 // lead to the files being moved in the DB also.
1460 $opts = array( 'force' => true );
1461 $status->merge( $backend->doOperations( $operations, $opts ) );
1467 * Delete files in the deleted directory if they are not referenced in the filearchive table
1470 * @param array $storageKeys
1472 public function cleanupDeletedBatch( array $storageKeys ) {
1473 $this->assertWritableRepo();
1477 * Get a relative path for a deletion archive key,
1478 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1480 * @param string $key
1481 * @throws MWException
1484 public function getDeletedHashPath( $key ) {
1485 if ( strlen( $key ) < 31 ) {
1486 throw new MWException( "Invalid storage key '$key'." );
1489 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1490 $path .= $key[$i] . '/';
1497 * If a path is a virtual URL, resolve it to a storage path.
1498 * Otherwise, just return the path as it is.
1500 * @param string $path
1502 * @throws MWException
1504 protected function resolveToStoragePath( $path ) {
1505 if ( $this->isVirtualUrl( $path ) ) {
1506 return $this->resolveVirtualUrl( $path );
1513 * Get a local FS copy of a file with a given virtual URL/storage path.
1514 * Temporary files may be purged when the file object falls out of scope.
1516 * @param string $virtualUrl
1517 * @return TempFSFile|null Returns null on failure
1519 public function getLocalCopy( $virtualUrl ) {
1520 $path = $this->resolveToStoragePath( $virtualUrl );
1522 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1526 * Get a local FS file with a given virtual URL/storage path.
1527 * The file is either an original or a copy. It should not be changed.
1528 * Temporary files may be purged when the file object falls out of scope.
1530 * @param string $virtualUrl
1531 * @return FSFile|null Returns null on failure.
1533 public function getLocalReference( $virtualUrl ) {
1534 $path = $this->resolveToStoragePath( $virtualUrl );
1536 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1540 * Get properties of a file with a given virtual URL/storage path.
1541 * Properties should ultimately be obtained via FSFile::getProps().
1543 * @param string $virtualUrl
1546 public function getFileProps( $virtualUrl ) {
1547 $path = $this->resolveToStoragePath( $virtualUrl );
1549 return $this->backend
->getFileProps( array( 'src' => $path ) );
1553 * Get the timestamp of a file with a given virtual URL/storage path
1555 * @param string $virtualUrl
1556 * @return string|bool False on failure
1558 public function getFileTimestamp( $virtualUrl ) {
1559 $path = $this->resolveToStoragePath( $virtualUrl );
1561 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1565 * Get the size of a file with a given virtual URL/storage path
1567 * @param string $virtualUrl
1568 * @return int|bool False on failure
1570 public function getFileSize( $virtualUrl ) {
1571 $path = $this->resolveToStoragePath( $virtualUrl );
1573 return $this->backend
->getFileSize( array( 'src' => $path ) );
1577 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1579 * @param string $virtualUrl
1580 * @return string|bool
1582 public function getFileSha1( $virtualUrl ) {
1583 $path = $this->resolveToStoragePath( $virtualUrl );
1585 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1589 * Attempt to stream a file with the given virtual URL/storage path
1591 * @param string $virtualUrl
1592 * @param array $headers Additional HTTP headers to send on success
1593 * @return bool Success
1595 public function streamFile( $virtualUrl, $headers = array() ) {
1596 $path = $this->resolveToStoragePath( $virtualUrl );
1597 $params = array( 'src' => $path, 'headers' => $headers );
1599 return $this->backend
->streamFile( $params )->isOK();
1603 * Call a callback function for every public regular file in the repository.
1604 * This only acts on the current version of files, not any old versions.
1605 * May use either the database or the filesystem.
1607 * @param callable $callback
1610 public function enumFiles( $callback ) {
1611 $this->enumFilesInStorage( $callback );
1615 * Call a callback function for every public file in the repository.
1616 * May use either the database or the filesystem.
1618 * @param callable $callback
1621 protected function enumFilesInStorage( $callback ) {
1622 $publicRoot = $this->getZonePath( 'public' );
1623 $numDirs = 1 << ( $this->hashLevels
* 4 );
1624 // Use a priori assumptions about directory structure
1625 // to reduce the tree height of the scanning process.
1626 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1627 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1628 $path = $publicRoot;
1629 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1630 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1632 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1633 foreach ( $iterator as $name ) {
1634 // Each item returned is a public file
1635 call_user_func( $callback, "{$path}/{$name}" );
1641 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1643 * @param string $filename
1646 public function validateFilename( $filename ) {
1647 if ( strval( $filename ) == '' ) {
1651 return FileBackend
::isPathTraversalFree( $filename );
1655 * Get a callback function to use for cleaning error message parameters
1659 function getErrorCleanupFunction() {
1660 switch ( $this->pathDisclosureProtection
) {
1662 case 'simple': // b/c
1663 $callback = array( $this, 'passThrough' );
1665 default: // 'paranoid'
1666 $callback = array( $this, 'paranoidClean' );
1672 * Path disclosure protection function
1674 * @param string $param
1677 function paranoidClean( $param ) {
1682 * Path disclosure protection function
1684 * @param string $param
1687 function passThrough( $param ) {
1692 * Create a new fatal error
1694 * @param string $message
1697 public function newFatal( $message /*, parameters...*/ ) {
1698 $status = call_user_func_array( array( 'Status', 'newFatal' ), func_get_args() );
1699 $status->cleanCallback
= $this->getErrorCleanupFunction();
1705 * Create a new good result
1707 * @param null|string $value
1710 public function newGood( $value = null ) {
1711 $status = Status
::newGood( $value );
1712 $status->cleanCallback
= $this->getErrorCleanupFunction();
1718 * Checks if there is a redirect named as $title. If there is, return the
1719 * title object. If not, return false.
1722 * @param Title $title Title of image
1725 public function checkRedirect( Title
$title ) {
1730 * Invalidates image redirect cache related to that image
1731 * Doesn't do anything for repositories that don't support image redirects.
1734 * @param Title $title Title of image
1736 public function invalidateImageRedirect( Title
$title ) {
1740 * Get the human-readable name of the repo
1744 public function getDisplayName() {
1747 if ( $this->isLocal() ) {
1751 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1752 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1756 * Get the portion of the file that contains the origin file name.
1757 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1759 * @param string $name
1762 public function nameForThumb( $name ) {
1763 if ( strlen( $name ) > $this->abbrvThreshold
) {
1764 $ext = FileBackend
::extensionFromPath( $name );
1765 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1772 * Returns true if this the local file repository.
1776 public function isLocal() {
1777 return $this->getName() == 'local';
1781 * Get a key on the primary cache for this repository.
1782 * Returns false if the repository's cache is not accessible at this site.
1783 * The parameters are the parts of the key, as for wfMemcKey().
1788 public function getSharedCacheKey( /*...*/ ) {
1793 * Get a key for this repo in the local cache domain. These cache keys are
1794 * not shared with remote instances of the repo.
1795 * The parameters are the parts of the key, as for wfMemcKey().
1799 public function getLocalCacheKey( /*...*/ ) {
1800 $args = func_get_args();
1801 array_unshift( $args, 'filerepo', $this->getName() );
1803 return call_user_func_array( 'wfMemcKey', $args );
1807 * Get a temporary private FileRepo associated with this repo.
1809 * Files will be created in the temp zone of this repo.
1810 * It will have the same backend as this repo.
1812 * @return TempFileRepo
1814 public function getTempRepo() {
1815 return new TempFileRepo( array(
1816 'name' => "{$this->name}-temp",
1817 'backend' => $this->backend
,
1820 // Same place storeTemp() uses in the base repo, though
1821 // the path hashing is mismatched, which is annoying.
1822 'container' => $this->zones
['temp']['container'],
1823 'directory' => $this->zones
['temp']['directory']
1826 'container' => $this->zones
['temp']['container'],
1827 'directory' => $this->zones
['temp']['directory'] == ''
1829 : $this->zones
['temp']['directory'] . '/thumb'
1831 'transcoded' => array(
1832 'container' => $this->zones
['temp']['container'],
1833 'directory' => $this->zones
['temp']['directory'] == ''
1835 : $this->zones
['temp']['directory'] . '/transcoded'
1838 'hashLevels' => $this->hashLevels
, // performance
1839 'isPrivate' => true // all in temp zone
1844 * Get an UploadStash associated with this repo.
1847 * @return UploadStash
1849 public function getUploadStash( User
$user = null ) {
1850 return new UploadStash( $this, $user );
1854 * Throw an exception if this repo is read-only by design.
1855 * This does not and should not check getReadOnlyReason().
1858 * @throws MWException
1860 protected function assertWritableRepo() {
1864 * Return information about the repository.
1869 public function getInfo() {
1871 'name' => $this->getName(),
1872 'displayname' => $this->getDisplayName(),
1873 'rootUrl' => $this->getZoneUrl( 'public' ),
1874 'local' => $this->isLocal(),
1877 $optionalSettings = array(
1878 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1879 'fetchDescription', 'descriptionCacheExpiry', 'scriptExtension', 'favicon'
1881 foreach ( $optionalSettings as $k ) {
1882 if ( isset( $this->$k ) ) {
1883 $ret[$k] = $this->$k;
1891 * Returns whether or not storage is SHA-1 based
1894 public function hasSha1Storage() {
1895 return $this->hasSha1Storage
;
1900 * FileRepo for temporary files created via FileRepo::getTempRepo()
1902 class TempFileRepo
extends FileRepo
{
1903 public function getTempRepo() {
1904 throw new MWException( "Cannot get a temp repo from a temp repo." );