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;
52 /** @var FileBackend */
55 /** @var array Map of zones to config */
56 protected $zones = array();
58 /** @var string URL of thumb.php */
59 protected $thumbScriptUrl;
61 /** @var bool Whether to skip media file transformation on parse and rely
62 * on a 404 handler instead. */
63 protected $transformVia404;
65 /** @var string URL of image description pages, e.g.
66 * http://en.wikipedia.org/wiki/File:
68 protected $descBaseUrl;
70 /** @var string URL of the MediaWiki installation, equivalent to
71 * $wgScriptPath, e.g. https://en.wikipedia.org/w
73 protected $scriptDirUrl;
75 /** @var string Script extension of the MediaWiki installation, equivalent
76 * to $wgScriptExtension, e.g. .php5 defaults to .php */
77 protected $scriptExtension;
79 /** @var string Equivalent to $wgArticlePath, e.g. http://en.wikipedia.org/wiki/$1 */
80 protected $articleUrl;
82 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
83 * determines whether filenames implicitly start with a capital letter.
84 * The current implementation may give incorrect description page links
85 * when the local $wgCapitalLinks and initialCapital are mismatched.
87 protected $initialCapital;
89 /** @var string May be 'paranoid' to remove all parameters from error
90 * messages, 'none' to leave the paths in unchanged, or 'simple' to
91 * replace paths with placeholders. Default for LocalRepo is
94 protected $pathDisclosureProtection = 'simple';
96 /** @var bool Public zone URL. */
99 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
102 /** @var int The number of directory levels for hash-based division of files */
103 protected $hashLevels;
105 /** @var int The number of directory levels for hash-based division of deleted files */
106 protected $deletedHashLevels;
108 /** @var int File names over this size will use the short form of thumbnail
109 * names. Short thumbnail names only have the width, parameters, and the
112 protected $abbrvThreshold;
114 /** @var string The URL of the repo's favicon, if any */
117 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
118 protected $isPrivate;
121 * Factory functions for creating new files
122 * Override these in the base class
124 protected $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
125 protected $oldFileFactory = false;
126 protected $fileFactoryKey = false;
127 protected $oldFileFactoryKey = false;
130 * @param array|null $info
131 * @throws MWException
133 public function __construct( array $info = null ) {
134 // Verify required settings presence
137 ||
!array_key_exists( 'name', $info )
138 ||
!array_key_exists( 'backend', $info )
140 throw new MWException( __CLASS__
.
141 " requires an array of options having both 'name' and 'backend' keys.\n" );
145 $this->name
= $info['name'];
146 if ( $info['backend'] instanceof FileBackend
) {
147 $this->backend
= $info['backend']; // useful for testing
149 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
152 // Optional settings that can have no value
153 $optionalSettings = array(
154 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
155 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
156 'scriptExtension', 'favicon'
158 foreach ( $optionalSettings as $var ) {
159 if ( isset( $info[$var] ) ) {
160 $this->$var = $info[$var];
164 // Optional settings that have a default
165 $this->initialCapital
= isset( $info['initialCapital'] )
166 ?
$info['initialCapital']
167 : MWNamespace
::isCapitalized( NS_FILE
);
168 $this->url
= isset( $info['url'] )
170 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
171 if ( isset( $info['thumbUrl'] ) ) {
172 $this->thumbUrl
= $info['thumbUrl'];
174 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
176 $this->hashLevels
= isset( $info['hashLevels'] )
177 ?
$info['hashLevels']
179 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
180 ?
$info['deletedHashLevels']
182 $this->transformVia404
= !empty( $info['transformVia404'] );
183 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
184 ?
$info['abbrvThreshold']
186 $this->isPrivate
= !empty( $info['isPrivate'] );
187 // Give defaults for the basic zones...
188 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
189 foreach ( array( 'public', 'thumb', 'transcoded', 'temp', 'deleted' ) as $zone ) {
190 if ( !isset( $this->zones
[$zone]['container'] ) ) {
191 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
193 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
194 $this->zones
[$zone]['directory'] = '';
196 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
197 $this->zones
[$zone]['urlsByExt'] = array();
203 * Get the file backend instance. Use this function wisely.
205 * @return FileBackend
207 public function getBackend() {
208 return $this->backend
;
212 * Get an explanatory message if this repo is read-only.
213 * This checks if an administrator disabled writes to the backend.
215 * @return string|bool Returns false if the repo is not read-only
217 public function getReadOnlyReason() {
218 return $this->backend
->getReadOnlyReason();
222 * Check if a single zone or list of zones is defined for usage
224 * @param array $doZones Only do a particular zones
225 * @throws MWException
228 protected function initZones( $doZones = array() ) {
229 $status = $this->newGood();
230 foreach ( (array)$doZones as $zone ) {
231 $root = $this->getZonePath( $zone );
232 if ( $root === null ) {
233 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
241 * Determine if a string is an mwrepo:// URL
246 public static function isVirtualUrl( $url ) {
247 return substr( $url, 0, 9 ) == 'mwrepo://';
251 * Get a URL referring to this repository, with the private mwrepo protocol.
252 * The suffix, if supplied, is considered to be unencoded, and will be
253 * URL-encoded before being returned.
255 * @param string|bool $suffix
258 public function getVirtualUrl( $suffix = false ) {
259 $path = 'mwrepo://' . $this->name
;
260 if ( $suffix !== false ) {
261 $path .= '/' . rawurlencode( $suffix );
268 * Get the URL corresponding to one of the four basic zones
270 * @param string $zone One of: public, deleted, temp, thumb
271 * @param string|null $ext Optional file extension
272 * @return string|bool
274 public function getZoneUrl( $zone, $ext = null ) {
275 if ( in_array( $zone, array( 'public', 'thumb', 'transcoded' ) ) ) {
276 // standard public zones
277 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
278 // custom URL for extension/zone
279 return $this->zones
[$zone]['urlsByExt'][$ext];
280 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
281 // custom URL for zone
282 return $this->zones
[$zone]['url'];
290 return false; // no public URL
292 return $this->thumbUrl
;
294 return "{$this->url}/transcoded";
301 * @return bool Whether non-ASCII path characters are allowed
303 public function backendSupportsUnicodePaths() {
304 return ( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
308 * Get the backend storage path corresponding to a virtual URL.
309 * Use this function wisely.
312 * @throws MWException
315 public function resolveVirtualUrl( $url ) {
316 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
317 throw new MWException( __METHOD__
. ': unknown protocol' );
319 $bits = explode( '/', substr( $url, 9 ), 3 );
320 if ( count( $bits ) != 3 ) {
321 throw new MWException( __METHOD__
. ": invalid mwrepo URL: $url" );
323 list( $repo, $zone, $rel ) = $bits;
324 if ( $repo !== $this->name
) {
325 throw new MWException( __METHOD__
. ": fetching from a foreign repo is not supported" );
327 $base = $this->getZonePath( $zone );
329 throw new MWException( __METHOD__
. ": invalid zone: $zone" );
332 return $base . '/' . rawurldecode( $rel );
336 * The the storage container and base path of a zone
338 * @param string $zone
339 * @return array (container, base path) or (null, null)
341 protected function getZoneLocation( $zone ) {
342 if ( !isset( $this->zones
[$zone] ) ) {
343 return array( null, null ); // bogus
346 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
350 * Get the storage path corresponding to one of the zones
352 * @param string $zone
353 * @return string|null Returns null if the zone is not defined
355 public function getZonePath( $zone ) {
356 list( $container, $base ) = $this->getZoneLocation( $zone );
357 if ( $container === null ||
$base === null ) {
360 $backendName = $this->backend
->getName();
361 if ( $base != '' ) { // may not be set
365 return "mwstore://$backendName/{$container}{$base}";
369 * Create a new File object from the local repository
371 * @param Title|string $title Title object or string
372 * @param bool|string $time Time at which the image was uploaded. If this
373 * is specified, the returned object will be an instance of the
374 * repository's old file class instead of a current file. Repositories
375 * not supporting version control should return false if this parameter
377 * @return File|null A File, or null if passed an invalid Title
379 public function newFile( $title, $time = false ) {
380 $title = File
::normalizeTitle( $title );
385 if ( $this->oldFileFactory
) {
386 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
391 return call_user_func( $this->fileFactory
, $title, $this );
396 * Find an instance of the named file created at the specified time
397 * Returns false if the file does not exist. Repositories not supporting
398 * version control should return false if the time is specified.
400 * @param Title|string $title Title object or string
401 * @param array $options Associative array of options:
402 * time: requested time for a specific file version, or false for the
403 * current version. An image object will be returned which was
404 * created at the specified time (which may be archived or current).
405 * ignoreRedirect: If true, do not follow file redirects
406 * private: If true, return restricted (deleted) files if the current
407 * user is allowed to view them. Otherwise, such files will not
408 * be found. If a User object, use that user instead of the current.
409 * @return File|bool False on failure
411 public function findFile( $title, $options = array() ) {
412 $title = File
::normalizeTitle( $title );
416 $time = isset( $options['time'] ) ?
$options['time'] : false;
417 # First try the current version of the file to see if it precedes the timestamp
418 $img = $this->newFile( $title );
422 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
425 # Now try an old version of the file
426 if ( $time !== false ) {
427 $img = $this->newFile( $title, $time );
428 if ( $img && $img->exists() ) {
429 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
430 return $img; // always OK
431 } elseif ( !empty( $options['private'] ) &&
432 $img->userCan( File
::DELETED_FILE
,
433 $options['private'] instanceof User ?
$options['private'] : null
442 if ( !empty( $options['ignoreRedirect'] ) ) {
445 $redir = $this->checkRedirect( $title );
446 if ( $redir && $title->getNamespace() == NS_FILE
) {
447 $img = $this->newFile( $redir );
451 if ( $img->exists() ) {
452 $img->redirectedFrom( $title->getDBkey() );
462 * Find many files at once.
464 * @param array $items An array of titles, or an array of findFile() options with
465 * the "title" option giving the title. Example:
467 * $findItem = array( 'title' => $title, 'private' => true );
468 * $findBatch = array( $findItem );
469 * $repo->findFiles( $findBatch );
471 * No title should appear in $items twice, as the result use titles as keys
472 * @param int $flags Supports:
473 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
474 * The search title uses the input titles; the other is the final post-redirect title.
475 * All titles are returned as string DB keys and the inner array is associative.
476 * @return array Map of (file name => File objects) for matches
478 public function findFiles( array $items, $flags = 0 ) {
480 foreach ( $items as $item ) {
481 if ( is_array( $item ) ) {
482 $title = $item['title'];
484 unset( $options['title'] );
489 $file = $this->findFile( $title, $options );
491 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
492 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
493 $result[$searchName] = array(
494 'title' => $file->getTitle()->getDBkey(),
495 'timestamp' => $file->getTimestamp()
498 $result[$searchName] = $file;
507 * Find an instance of the file with this key, created at the specified time
508 * Returns false if the file does not exist. Repositories not supporting
509 * version control should return false if the time is specified.
511 * @param string $sha1 Base 36 SHA-1 hash
512 * @param array $options Option array, same as findFile().
513 * @return File|bool False on failure
515 public function findFileFromKey( $sha1, $options = array() ) {
516 $time = isset( $options['time'] ) ?
$options['time'] : false;
517 # First try to find a matching current version of a file...
518 if ( $this->fileFactoryKey
) {
519 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
521 return false; // find-by-sha1 not supported
523 if ( $img && $img->exists() ) {
526 # Now try to find a matching old version of a file...
527 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
528 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
529 if ( $img && $img->exists() ) {
530 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
531 return $img; // always OK
532 } elseif ( !empty( $options['private'] ) &&
533 $img->userCan( File
::DELETED_FILE
,
534 $options['private'] instanceof User ?
$options['private'] : null
546 * Get an array or iterator of file objects for files that have a given
547 * SHA-1 content hash.
550 * @param string $hash SHA-1 hash
553 public function findBySha1( $hash ) {
558 * Get an array of arrays or iterators of file objects for files that
559 * have the given SHA-1 content hashes.
561 * @param array $hashes An array of hashes
562 * @return array An Array of arrays or iterators of file objects and the hash as key
564 public function findBySha1s( array $hashes ) {
566 foreach ( $hashes as $hash ) {
567 $files = $this->findBySha1( $hash );
568 if ( count( $files ) ) {
569 $result[$hash] = $files;
577 * Return an array of files where the name starts with $prefix.
580 * @param string $prefix The prefix to search for
581 * @param int $limit The maximum amount of files to return
584 public function findFilesByPrefix( $prefix, $limit ) {
589 * Get the public root URL of the repository
591 * @deprecated since 1.20
594 public function getRootUrl() {
595 return $this->getZoneUrl( 'public' );
599 * Get the URL of thumb.php
603 public function getThumbScriptUrl() {
604 return $this->thumbScriptUrl
;
608 * Returns true if the repository can transform files via a 404 handler
612 public function canTransformVia404() {
613 return $this->transformVia404
;
617 * Get the name of a file from its title object
619 * @param Title $title
622 public function getNameFromTitle( Title
$title ) {
624 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
625 $name = $title->getUserCaseDBKey();
626 if ( $this->initialCapital
) {
627 $name = $wgContLang->ucfirst( $name );
630 $name = $title->getDBkey();
637 * Get the public zone root storage directory of the repository
641 public function getRootDirectory() {
642 return $this->getZonePath( 'public' );
646 * Get a relative path including trailing slash, e.g. f/fa/
647 * If the repo is not hashed, returns an empty string
649 * @param string $name Name of file
652 public function getHashPath( $name ) {
653 return self
::getHashPathForLevel( $name, $this->hashLevels
);
657 * Get a relative path including trailing slash, e.g. f/fa/
658 * If the repo is not hashed, returns an empty string
660 * @param string $suffix Basename of file from FileRepo::storeTemp()
663 public function getTempHashPath( $suffix ) {
664 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
665 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
666 return self
::getHashPathForLevel( $name, $this->hashLevels
);
670 * @param string $name
674 protected static function getHashPathForLevel( $name, $levels ) {
675 if ( $levels == 0 ) {
678 $hash = md5( $name );
680 for ( $i = 1; $i <= $levels; $i++
) {
681 $path .= substr( $hash, 0, $i ) . '/';
689 * Get the number of hash directory levels
693 public function getHashLevels() {
694 return $this->hashLevels
;
698 * Get the name of this repository, as specified by $info['name]' to the constructor
702 public function getName() {
707 * Make an url to this repo
709 * @param string $query Query string to append
710 * @param string $entry Entry point; defaults to index
711 * @return string|bool False on failure
713 public function makeUrl( $query = '', $entry = 'index' ) {
714 if ( isset( $this->scriptDirUrl
) ) {
715 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
717 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
724 * Get the URL of an image description page. May return false if it is
725 * unknown or not applicable. In general this should only be called by the
726 * File class, since it may return invalid results for certain kinds of
727 * repositories. Use File::getDescriptionUrl() in user code.
729 * In particular, it uses the article paths as specified to the repository
730 * constructor, whereas local repositories use the local Title functions.
732 * @param string $name
735 public function getDescriptionUrl( $name ) {
736 $encName = wfUrlencode( $name );
737 if ( !is_null( $this->descBaseUrl
) ) {
738 # "http://example.com/wiki/File:"
739 return $this->descBaseUrl
. $encName;
741 if ( !is_null( $this->articleUrl
) ) {
742 # "http://example.com/wiki/$1"
744 # We use "Image:" as the canonical namespace for
745 # compatibility across all MediaWiki versions.
746 return str_replace( '$1',
747 "Image:$encName", $this->articleUrl
);
749 if ( !is_null( $this->scriptDirUrl
) ) {
750 # "http://example.com/w"
752 # We use "Image:" as the canonical namespace for
753 # compatibility across all MediaWiki versions,
754 # and just sort of hope index.php is right. ;)
755 return $this->makeUrl( "title=Image:$encName" );
762 * Get the URL of the content-only fragment of the description page. For
763 * MediaWiki this means action=render. This should only be called by the
764 * repository's file class, since it may return invalid results. User code
765 * should use File::getDescriptionText().
767 * @param string $name Name of image to fetch
768 * @param string $lang Language to fetch it in, if any.
771 public function getDescriptionRenderUrl( $name, $lang = null ) {
772 $query = 'action=render';
773 if ( !is_null( $lang ) ) {
774 $query .= '&uselang=' . $lang;
776 if ( isset( $this->scriptDirUrl
) ) {
777 return $this->makeUrl(
779 wfUrlencode( 'Image:' . $name ) .
782 $descUrl = $this->getDescriptionUrl( $name );
784 return wfAppendQuery( $descUrl, $query );
792 * Get the URL of the stylesheet to apply to description pages
794 * @return string|bool False on failure
796 public function getDescriptionStylesheetUrl() {
797 if ( isset( $this->scriptDirUrl
) ) {
798 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
799 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
806 * Store a file to a given destination.
808 * @param string $srcPath Source file system path, storage path, or virtual URL
809 * @param string $dstZone Destination zone
810 * @param string $dstRel Destination relative path
811 * @param int $flags Bitwise combination of the following flags:
812 * self::DELETE_SOURCE Delete the source file after upload
813 * self::OVERWRITE Overwrite an existing destination file instead of failing
814 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
815 * same contents as the source
816 * self::SKIP_LOCKING Skip any file locking when doing the store
817 * @return FileRepoStatus
819 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
820 $this->assertWritableRepo(); // fail out if read-only
822 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
823 if ( $status->successCount
== 0 ) {
831 * Store a batch of files
833 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
834 * @param int $flags Bitwise combination of the following flags:
835 * self::DELETE_SOURCE Delete the source file after upload
836 * self::OVERWRITE Overwrite an existing destination file instead of failing
837 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
838 * same contents as the source
839 * self::SKIP_LOCKING Skip any file locking when doing the store
840 * @throws MWException
841 * @return FileRepoStatus
843 public function storeBatch( array $triplets, $flags = 0 ) {
844 $this->assertWritableRepo(); // fail out if read-only
846 $status = $this->newGood();
847 $backend = $this->backend
; // convenience
849 $operations = array();
850 $sourceFSFilesToDelete = array(); // cleanup for disk source files
851 // Validate each triplet and get the store operation...
852 foreach ( $triplets as $triplet ) {
853 list( $srcPath, $dstZone, $dstRel ) = $triplet;
855 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
858 // Resolve destination path
859 $root = $this->getZonePath( $dstZone );
861 throw new MWException( "Invalid zone: $dstZone" );
863 if ( !$this->validateFilename( $dstRel ) ) {
864 throw new MWException( 'Validation error in $dstRel' );
866 $dstPath = "$root/$dstRel";
867 $dstDir = dirname( $dstPath );
868 // Create destination directories for this triplet
869 if ( !$this->initDirectory( $dstDir )->isOK() ) {
870 return $this->newFatal( 'directorycreateerror', $dstDir );
873 // Resolve source to a storage path if virtual
874 $srcPath = $this->resolveToStoragePath( $srcPath );
876 // Get the appropriate file operation
877 if ( FileBackend
::isStoragePath( $srcPath ) ) {
878 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
881 if ( $flags & self
::DELETE_SOURCE
) {
882 $sourceFSFilesToDelete[] = $srcPath;
885 $operations[] = array(
889 'overwrite' => $flags & self
::OVERWRITE
,
890 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
894 // Execute the store operation for each triplet
895 $opts = array( 'force' => true );
896 if ( $flags & self
::SKIP_LOCKING
) {
897 $opts['nonLocking'] = true;
899 $status->merge( $backend->doOperations( $operations, $opts ) );
900 // Cleanup for disk source files...
901 foreach ( $sourceFSFilesToDelete as $file ) {
902 wfSuppressWarnings();
903 unlink( $file ); // FS cleanup
911 * Deletes a batch of files.
912 * Each file can be a (zone, rel) pair, virtual url, storage path.
913 * It will try to delete each file, but ignores any errors that may occur.
915 * @param array $files List of files to delete
916 * @param int $flags Bitwise combination of the following flags:
917 * self::SKIP_LOCKING Skip any file locking when doing the deletions
918 * @return FileRepoStatus
920 public function cleanupBatch( array $files, $flags = 0 ) {
921 $this->assertWritableRepo(); // fail out if read-only
923 $status = $this->newGood();
925 $operations = array();
926 foreach ( $files as $path ) {
927 if ( is_array( $path ) ) {
928 // This is a pair, extract it
929 list( $zone, $rel ) = $path;
930 $path = $this->getZonePath( $zone ) . "/$rel";
932 // Resolve source to a storage path if virtual
933 $path = $this->resolveToStoragePath( $path );
935 $operations[] = array( 'op' => 'delete', 'src' => $path );
937 // Actually delete files from storage...
938 $opts = array( 'force' => true );
939 if ( $flags & self
::SKIP_LOCKING
) {
940 $opts['nonLocking'] = true;
942 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
948 * Import a file from the local file system into the repo.
949 * This does no locking nor journaling and overrides existing files.
950 * This function can be used to write to otherwise read-only foreign repos.
951 * This is intended for copying generated thumbnails into the repo.
953 * @param string $src Source file system path, storage path, or virtual URL
954 * @param string $dst Virtual URL or storage path
955 * @param array|string|null $options An array consisting of a key named headers
956 * listing extra headers. If a string, taken as content-disposition header.
957 * (Support for array of options new in 1.23)
958 * @return FileRepoStatus
960 final public function quickImport( $src, $dst, $options = null ) {
961 return $this->quickImportBatch( array( array( $src, $dst, $options ) ) );
965 * Purge a file from the repo. This does no locking nor journaling.
966 * This function can be used to write to otherwise read-only foreign repos.
967 * This is intended for purging thumbnails.
969 * @param string $path Virtual URL or storage path
970 * @return FileRepoStatus
972 final public function quickPurge( $path ) {
973 return $this->quickPurgeBatch( array( $path ) );
977 * Deletes a directory if empty.
978 * This function can be used to write to otherwise read-only foreign repos.
980 * @param string $dir Virtual URL (or storage path) of directory to clean
983 public function quickCleanDir( $dir ) {
984 $status = $this->newGood();
985 $status->merge( $this->backend
->clean(
986 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
992 * Import a batch of files from the local file system into the repo.
993 * This does no locking nor journaling and overrides existing files.
994 * This function can be used to write to otherwise read-only foreign repos.
995 * This is intended for copying generated thumbnails into the repo.
997 * All path parameters may be a file system path, storage path, or virtual URL.
998 * When "headers" are given they are used as HTTP headers if supported.
1000 * @param array $triples List of (source path, destination path, disposition)
1001 * @return FileRepoStatus
1003 public function quickImportBatch( array $triples ) {
1004 $status = $this->newGood();
1005 $operations = array();
1006 foreach ( $triples as $triple ) {
1007 list( $src, $dst ) = $triple;
1008 $src = $this->resolveToStoragePath( $src );
1009 $dst = $this->resolveToStoragePath( $dst );
1011 if ( !isset( $triple[2] ) ) {
1013 } elseif ( is_string( $triple[2] ) ) {
1015 $headers = array( 'Content-Disposition' => $triple[2] );
1016 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1017 $headers = $triple[2]['headers'];
1019 // @fixme: $headers might not be defined
1020 $operations[] = array(
1021 'op' => FileBackend
::isStoragePath( $src ) ?
'copy' : 'store',
1024 'headers' => $headers
1026 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1028 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1034 * Purge a batch of files from the repo.
1035 * This function can be used to write to otherwise read-only foreign repos.
1036 * This does no locking nor journaling and is intended for purging thumbnails.
1038 * @param array $paths List of virtual URLs or storage paths
1039 * @return FileRepoStatus
1041 public function quickPurgeBatch( array $paths ) {
1042 $status = $this->newGood();
1043 $operations = array();
1044 foreach ( $paths as $path ) {
1045 $operations[] = array(
1047 'src' => $this->resolveToStoragePath( $path ),
1048 'ignoreMissingSource' => true
1051 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1057 * Pick a random name in the temp zone and store a file to it.
1058 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1059 * file can later be disposed using FileRepo::freeTemp().
1061 * @param string $originalName The base name of the file as specified
1062 * by the user. The file extension will be maintained.
1063 * @param string $srcPath The current location of the file.
1064 * @return FileRepoStatus Object with the URL in the value.
1066 public function storeTemp( $originalName, $srcPath ) {
1067 $this->assertWritableRepo(); // fail out if read-only
1069 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1070 $hashPath = $this->getHashPath( $originalName );
1071 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1072 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1074 $result = $this->quickImport( $srcPath, $virtualUrl );
1075 $result->value
= $virtualUrl;
1081 * Remove a temporary file or mark it for garbage collection
1083 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1084 * @return bool True on success, false on failure
1086 public function freeTemp( $virtualUrl ) {
1087 $this->assertWritableRepo(); // fail out if read-only
1089 $temp = $this->getVirtualUrl( 'temp' );
1090 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1091 wfDebug( __METHOD__
. ": Invalid temp virtual URL\n" );
1096 return $this->quickPurge( $virtualUrl )->isOK();
1100 * Concatenate a list of temporary files into a target file location.
1102 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1103 * @param string $dstPath Target file system path
1104 * @param int $flags Bitwise combination of the following flags:
1105 * self::DELETE_SOURCE Delete the source files
1106 * @return FileRepoStatus
1108 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1109 $this->assertWritableRepo(); // fail out if read-only
1111 $status = $this->newGood();
1114 foreach ( $srcPaths as $srcPath ) {
1115 // Resolve source to a storage path if virtual
1116 $source = $this->resolveToStoragePath( $srcPath );
1117 $sources[] = $source; // chunk to merge
1120 // Concatenate the chunks into one FS file
1121 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1122 $status->merge( $this->backend
->concatenate( $params ) );
1123 if ( !$status->isOK() ) {
1127 // Delete the sources if required
1128 if ( $flags & self
::DELETE_SOURCE
) {
1129 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1132 // Make sure status is OK, despite any quickPurgeBatch() fatals
1133 $status->setResult( true );
1139 * Copy or move a file either from a storage path, virtual URL,
1140 * or file system path, into this repository at the specified destination location.
1142 * Returns a FileRepoStatus object. On success, the value contains "new" or
1143 * "archived", to indicate whether the file was new with that name.
1145 * Options to $options include:
1146 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1148 * @param string $srcPath The source file system path, storage path, or URL
1149 * @param string $dstRel The destination relative path
1150 * @param string $archiveRel The relative path where the existing file is to
1151 * be archived, if there is one. Relative to the public zone root.
1152 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1153 * that the source file should be deleted if possible
1154 * @param array $options Optional additional parameters
1155 * @return FileRepoStatus
1157 public function publish(
1158 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1160 $this->assertWritableRepo(); // fail out if read-only
1162 $status = $this->publishBatch(
1163 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1164 if ( $status->successCount
== 0 ) {
1165 $status->ok
= false;
1167 if ( isset( $status->value
[0] ) ) {
1168 $status->value
= $status->value
[0];
1170 $status->value
= false;
1177 * Publish a batch of files
1179 * @param array $ntuples (source, dest, archive) triplets or
1180 * (source, dest, archive, options) 4-tuples as per publish().
1181 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1182 * that the source files should be deleted if possible
1183 * @throws MWException
1184 * @return FileRepoStatus
1186 public function publishBatch( array $ntuples, $flags = 0 ) {
1187 $this->assertWritableRepo(); // fail out if read-only
1189 $backend = $this->backend
; // convenience
1190 // Try creating directories
1191 $status = $this->initZones( 'public' );
1192 if ( !$status->isOK() ) {
1196 $status = $this->newGood( array() );
1198 $operations = array();
1199 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1200 // Validate each triplet and get the store operation...
1201 foreach ( $ntuples as $ntuple ) {
1202 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1203 $options = isset( $ntuple[3] ) ?
$ntuple[3] : array();
1204 // Resolve source to a storage path if virtual
1205 $srcPath = $this->resolveToStoragePath( $srcPath );
1206 if ( !$this->validateFilename( $dstRel ) ) {
1207 throw new MWException( 'Validation error in $dstRel' );
1209 if ( !$this->validateFilename( $archiveRel ) ) {
1210 throw new MWException( 'Validation error in $archiveRel' );
1213 $publicRoot = $this->getZonePath( 'public' );
1214 $dstPath = "$publicRoot/$dstRel";
1215 $archivePath = "$publicRoot/$archiveRel";
1217 $dstDir = dirname( $dstPath );
1218 $archiveDir = dirname( $archivePath );
1219 // Abort immediately on directory creation errors since they're likely to be repetitive
1220 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1221 return $this->newFatal( 'directorycreateerror', $dstDir );
1223 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1224 return $this->newFatal( 'directorycreateerror', $archiveDir );
1227 // Set any desired headers to be use in GET/HEAD responses
1228 $headers = isset( $options['headers'] ) ?
$options['headers'] : array();
1230 // Archive destination file if it exists.
1231 // This will check if the archive file also exists and fail if does.
1232 // This is a sanity check to avoid data loss. On Windows and Linux,
1233 // copy() will overwrite, so the existence check is vulnerable to
1234 // race conditions unless a functioning LockManager is used.
1235 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1236 $operations[] = array(
1239 'dst' => $archivePath,
1240 'ignoreMissingSource' => true
1243 // Copy (or move) the source file to the destination
1244 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1245 if ( $flags & self
::DELETE_SOURCE
) {
1246 $operations[] = array(
1250 'overwrite' => true, // replace current
1251 'headers' => $headers
1254 $operations[] = array(
1258 'overwrite' => true, // replace current
1259 'headers' => $headers
1262 } else { // FS source path
1263 $operations[] = array(
1267 'overwrite' => true, // replace current
1268 'headers' => $headers
1270 if ( $flags & self
::DELETE_SOURCE
) {
1271 $sourceFSFilesToDelete[] = $srcPath;
1276 // Execute the operations for each triplet
1277 $status->merge( $backend->doOperations( $operations ) );
1278 // Find out which files were archived...
1279 foreach ( $ntuples as $i => $ntuple ) {
1280 list( , , $archiveRel ) = $ntuple;
1281 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1282 if ( $this->fileExists( $archivePath ) ) {
1283 $status->value
[$i] = 'archived';
1285 $status->value
[$i] = 'new';
1288 // Cleanup for disk source files...
1289 foreach ( $sourceFSFilesToDelete as $file ) {
1290 wfSuppressWarnings();
1291 unlink( $file ); // FS cleanup
1292 wfRestoreWarnings();
1299 * Creates a directory with the appropriate zone permissions.
1300 * Callers are responsible for doing read-only and "writable repo" checks.
1302 * @param string $dir Virtual URL (or storage path) of directory to clean
1305 protected function initDirectory( $dir ) {
1306 $path = $this->resolveToStoragePath( $dir );
1307 list( , $container, ) = FileBackend
::splitStoragePath( $path );
1309 $params = array( 'dir' => $path );
1310 if ( $this->isPrivate
1311 ||
$container === $this->zones
['deleted']['container']
1312 ||
$container === $this->zones
['temp']['container']
1314 # Take all available measures to prevent web accessibility of new deleted
1315 # directories, in case the user has not configured offline storage
1316 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1319 return $this->backend
->prepare( $params );
1323 * Deletes a directory if empty.
1325 * @param string $dir Virtual URL (or storage path) of directory to clean
1328 public function cleanDir( $dir ) {
1329 $this->assertWritableRepo(); // fail out if read-only
1331 $status = $this->newGood();
1332 $status->merge( $this->backend
->clean(
1333 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1339 * Checks existence of a a file
1341 * @param string $file Virtual URL (or storage path) of file to check
1344 public function fileExists( $file ) {
1345 $result = $this->fileExistsBatch( array( $file ) );
1351 * Checks existence of an array of files.
1353 * @param array $files Virtual URLs (or storage paths) of files to check
1354 * @return array Map of files and existence flags, or false
1356 public function fileExistsBatch( array $files ) {
1357 $paths = array_map( array( $this, 'resolveToStoragePath' ), $files );
1358 $this->backend
->preloadFileStat( array( 'srcs' => $paths ) );
1361 foreach ( $files as $key => $file ) {
1362 $path = $this->resolveToStoragePath( $file );
1363 $result[$key] = $this->backend
->fileExists( array( 'src' => $path ) );
1370 * Move a file to the deletion archive.
1371 * If no valid deletion archive exists, this may either delete the file
1372 * or throw an exception, depending on the preference of the repository
1374 * @param mixed $srcRel Relative path for the file to be deleted
1375 * @param mixed $archiveRel Relative path for the archive location.
1376 * Relative to a private archive directory.
1377 * @return FileRepoStatus
1379 public function delete( $srcRel, $archiveRel ) {
1380 $this->assertWritableRepo(); // fail out if read-only
1382 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1386 * Move a group of files to the deletion archive.
1388 * If no valid deletion archive is configured, this may either delete the
1389 * file or throw an exception, depending on the preference of the repository.
1391 * The overwrite policy is determined by the repository -- currently LocalRepo
1392 * assumes a naming scheme in the deleted zone based on content hash, as
1393 * opposed to the public zone which is assumed to be unique.
1395 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1396 * is a two-element array containing the source file path relative to the
1397 * public root in the first element, and the archive file path relative
1398 * to the deleted zone root in the second element.
1399 * @throws MWException
1400 * @return FileRepoStatus
1402 public function deleteBatch( array $sourceDestPairs ) {
1403 $this->assertWritableRepo(); // fail out if read-only
1405 // Try creating directories
1406 $status = $this->initZones( array( 'public', 'deleted' ) );
1407 if ( !$status->isOK() ) {
1411 $status = $this->newGood();
1413 $backend = $this->backend
; // convenience
1414 $operations = array();
1415 // Validate filenames and create archive directories
1416 foreach ( $sourceDestPairs as $pair ) {
1417 list( $srcRel, $archiveRel ) = $pair;
1418 if ( !$this->validateFilename( $srcRel ) ) {
1419 throw new MWException( __METHOD__
. ':Validation error in $srcRel' );
1420 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1421 throw new MWException( __METHOD__
. ':Validation error in $archiveRel' );
1424 $publicRoot = $this->getZonePath( 'public' );
1425 $srcPath = "{$publicRoot}/$srcRel";
1427 $deletedRoot = $this->getZonePath( 'deleted' );
1428 $archivePath = "{$deletedRoot}/{$archiveRel}";
1429 $archiveDir = dirname( $archivePath ); // does not touch FS
1431 // Create destination directories
1432 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1433 return $this->newFatal( 'directorycreateerror', $archiveDir );
1436 $operations[] = array(
1439 'dst' => $archivePath,
1440 // We may have 2+ identical files being deleted,
1441 // all of which will map to the same destination file
1442 'overwriteSame' => true // also see bug 31792
1446 // Move the files by execute the operations for each pair.
1447 // We're now committed to returning an OK result, which will
1448 // lead to the files being moved in the DB also.
1449 $opts = array( 'force' => true );
1450 $status->merge( $backend->doOperations( $operations, $opts ) );
1456 * Delete files in the deleted directory if they are not referenced in the filearchive table
1459 * @param array $storageKeys
1461 public function cleanupDeletedBatch( array $storageKeys ) {
1462 $this->assertWritableRepo();
1466 * Get a relative path for a deletion archive key,
1467 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1469 * @param string $key
1470 * @throws MWException
1473 public function getDeletedHashPath( $key ) {
1474 if ( strlen( $key ) < 31 ) {
1475 throw new MWException( "Invalid storage key '$key'." );
1478 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1479 $path .= $key[$i] . '/';
1486 * If a path is a virtual URL, resolve it to a storage path.
1487 * Otherwise, just return the path as it is.
1489 * @param string $path
1491 * @throws MWException
1493 protected function resolveToStoragePath( $path ) {
1494 if ( $this->isVirtualUrl( $path ) ) {
1495 return $this->resolveVirtualUrl( $path );
1502 * Get a local FS copy of a file with a given virtual URL/storage path.
1503 * Temporary files may be purged when the file object falls out of scope.
1505 * @param string $virtualUrl
1506 * @return TempFSFile|null Returns null on failure
1508 public function getLocalCopy( $virtualUrl ) {
1509 $path = $this->resolveToStoragePath( $virtualUrl );
1511 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1515 * Get a local FS file with a given virtual URL/storage path.
1516 * The file is either an original or a copy. It should not be changed.
1517 * Temporary files may be purged when the file object falls out of scope.
1519 * @param string $virtualUrl
1520 * @return FSFile|null Returns null on failure.
1522 public function getLocalReference( $virtualUrl ) {
1523 $path = $this->resolveToStoragePath( $virtualUrl );
1525 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1529 * Get properties of a file with a given virtual URL/storage path.
1530 * Properties should ultimately be obtained via FSFile::getProps().
1532 * @param string $virtualUrl
1535 public function getFileProps( $virtualUrl ) {
1536 $path = $this->resolveToStoragePath( $virtualUrl );
1538 return $this->backend
->getFileProps( array( 'src' => $path ) );
1542 * Get the timestamp of a file with a given virtual URL/storage path
1544 * @param string $virtualUrl
1545 * @return string|bool False on failure
1547 public function getFileTimestamp( $virtualUrl ) {
1548 $path = $this->resolveToStoragePath( $virtualUrl );
1550 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1554 * Get the size of a file with a given virtual URL/storage path
1556 * @param string $virtualUrl
1557 * @return int|bool False on failure
1559 public function getFileSize( $virtualUrl ) {
1560 $path = $this->resolveToStoragePath( $virtualUrl );
1562 return $this->backend
->getFileSize( array( 'src' => $path ) );
1566 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1568 * @param string $virtualUrl
1569 * @return string|bool
1571 public function getFileSha1( $virtualUrl ) {
1572 $path = $this->resolveToStoragePath( $virtualUrl );
1574 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1578 * Attempt to stream a file with the given virtual URL/storage path
1580 * @param string $virtualUrl
1581 * @param array $headers Additional HTTP headers to send on success
1582 * @return bool Success
1584 public function streamFile( $virtualUrl, $headers = array() ) {
1585 $path = $this->resolveToStoragePath( $virtualUrl );
1586 $params = array( 'src' => $path, 'headers' => $headers );
1588 return $this->backend
->streamFile( $params )->isOK();
1592 * Call a callback function for every public regular file in the repository.
1593 * This only acts on the current version of files, not any old versions.
1594 * May use either the database or the filesystem.
1596 * @param callable $callback
1599 public function enumFiles( $callback ) {
1600 $this->enumFilesInStorage( $callback );
1604 * Call a callback function for every public file in the repository.
1605 * May use either the database or the filesystem.
1607 * @param callable $callback
1610 protected function enumFilesInStorage( $callback ) {
1611 $publicRoot = $this->getZonePath( 'public' );
1612 $numDirs = 1 << ( $this->hashLevels
* 4 );
1613 // Use a priori assumptions about directory structure
1614 // to reduce the tree height of the scanning process.
1615 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1616 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1617 $path = $publicRoot;
1618 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1619 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1621 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1622 foreach ( $iterator as $name ) {
1623 // Each item returned is a public file
1624 call_user_func( $callback, "{$path}/{$name}" );
1630 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1632 * @param string $filename
1635 public function validateFilename( $filename ) {
1636 if ( strval( $filename ) == '' ) {
1640 return FileBackend
::isPathTraversalFree( $filename );
1644 * Get a callback function to use for cleaning error message parameters
1648 function getErrorCleanupFunction() {
1649 switch ( $this->pathDisclosureProtection
) {
1651 case 'simple': // b/c
1652 $callback = array( $this, 'passThrough' );
1654 default: // 'paranoid'
1655 $callback = array( $this, 'paranoidClean' );
1661 * Path disclosure protection function
1663 * @param string $param
1666 function paranoidClean( $param ) {
1671 * Path disclosure protection function
1673 * @param string $param
1676 function passThrough( $param ) {
1681 * Create a new fatal error
1683 * @param string $message
1686 public function newFatal( $message /*, parameters...*/ ) {
1687 $status = call_user_func_array( array( 'Status', 'newFatal' ), func_get_args() );
1688 $status->cleanCallback
= $this->getErrorCleanupFunction();
1694 * Create a new good result
1696 * @param null|string $value
1699 public function newGood( $value = null ) {
1700 $status = Status
::newGood( $value );
1701 $status->cleanCallback
= $this->getErrorCleanupFunction();
1707 * Checks if there is a redirect named as $title. If there is, return the
1708 * title object. If not, return false.
1711 * @param Title $title Title of image
1714 public function checkRedirect( Title
$title ) {
1719 * Invalidates image redirect cache related to that image
1720 * Doesn't do anything for repositories that don't support image redirects.
1723 * @param Title $title Title of image
1725 public function invalidateImageRedirect( Title
$title ) {
1729 * Get the human-readable name of the repo
1733 public function getDisplayName() {
1736 if ( $this->isLocal() ) {
1740 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1741 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1745 * Get the portion of the file that contains the origin file name.
1746 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1748 * @param string $name
1751 public function nameForThumb( $name ) {
1752 if ( strlen( $name ) > $this->abbrvThreshold
) {
1753 $ext = FileBackend
::extensionFromPath( $name );
1754 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1761 * Returns true if this the local file repository.
1765 public function isLocal() {
1766 return $this->getName() == 'local';
1770 * Get a key on the primary cache for this repository.
1771 * Returns false if the repository's cache is not accessible at this site.
1772 * The parameters are the parts of the key, as for wfMemcKey().
1777 public function getSharedCacheKey( /*...*/ ) {
1782 * Get a key for this repo in the local cache domain. These cache keys are
1783 * not shared with remote instances of the repo.
1784 * The parameters are the parts of the key, as for wfMemcKey().
1788 public function getLocalCacheKey( /*...*/ ) {
1789 $args = func_get_args();
1790 array_unshift( $args, 'filerepo', $this->getName() );
1792 return call_user_func_array( 'wfMemcKey', $args );
1796 * Get a temporary private FileRepo associated with this repo.
1798 * Files will be created in the temp zone of this repo.
1799 * It will have the same backend as this repo.
1801 * @return TempFileRepo
1803 public function getTempRepo() {
1804 return new TempFileRepo( array(
1805 'name' => "{$this->name}-temp",
1806 'backend' => $this->backend
,
1809 // Same place storeTemp() uses in the base repo, though
1810 // the path hashing is mismatched, which is annoying.
1811 'container' => $this->zones
['temp']['container'],
1812 'directory' => $this->zones
['temp']['directory']
1815 'container' => $this->zones
['temp']['container'],
1816 'directory' => $this->zones
['temp']['directory'] == ''
1818 : $this->zones
['temp']['directory'] . '/thumb'
1820 'transcoded' => array(
1821 'container' => $this->zones
['temp']['container'],
1822 'directory' => $this->zones
['temp']['directory'] == ''
1824 : $this->zones
['temp']['directory'] . '/transcoded'
1827 'hashLevels' => $this->hashLevels
, // performance
1828 'isPrivate' => true // all in temp zone
1833 * Get an UploadStash associated with this repo.
1836 * @return UploadStash
1838 public function getUploadStash( User
$user = null ) {
1839 return new UploadStash( $this, $user );
1843 * Throw an exception if this repo is read-only by design.
1844 * This does not and should not check getReadOnlyReason().
1847 * @throws MWException
1849 protected function assertWritableRepo() {
1853 * Return information about the repository.
1858 public function getInfo() {
1860 'name' => $this->getName(),
1861 'displayname' => $this->getDisplayName(),
1862 'rootUrl' => $this->getZoneUrl( 'public' ),
1863 'local' => $this->isLocal(),
1866 $optionalSettings = array(
1867 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1868 'fetchDescription', 'descriptionCacheExpiry', 'scriptExtension', 'favicon'
1870 foreach ( $optionalSettings as $k ) {
1871 if ( isset( $this->$k ) ) {
1872 $ret[$k] = $this->$k;
1881 * FileRepo for temporary files created via FileRepo::getTempRepo()
1883 class TempFileRepo
extends FileRepo
{
1884 public function getTempRepo() {
1885 throw new MWException( "Cannot get a temp repo from a temp repo." );