3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
33 * Base class for file repositories
38 const DELETE_SOURCE
= 1;
40 const OVERWRITE_SAME
= 4;
41 const SKIP_LOCKING
= 8;
43 /** @var FileBackend */
45 /** @var Array Map of zones to config */
46 protected $zones = array();
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
54 protected $abbrvThreshold;
57 * Factory functions for creating new files
58 * Override these in the base class
60 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
61 var $oldFileFactory = false;
62 var $fileFactoryKey = false, $oldFileFactoryKey = false;
65 * @param $info array|null
68 public function __construct( array $info = null ) {
69 // Verify required settings presence
72 ||
!array_key_exists( 'name', $info )
73 ||
!array_key_exists( 'backend', $info )
75 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
79 $this->name
= $info['name'];
80 if ( $info['backend'] instanceof FileBackend
) {
81 $this->backend
= $info['backend']; // useful for testing
83 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
86 // Optional settings that can have no value
87 $optionalSettings = array(
88 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
89 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
92 foreach ( $optionalSettings as $var ) {
93 if ( isset( $info[$var] ) ) {
94 $this->$var = $info[$var];
98 // Optional settings that have a default
99 $this->initialCapital
= isset( $info['initialCapital'] )
100 ?
$info['initialCapital']
101 : MWNamespace
::isCapitalized( NS_FILE
);
102 $this->url
= isset( $info['url'] )
104 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
105 if ( isset( $info['thumbUrl'] ) ) {
106 $this->thumbUrl
= $info['thumbUrl'];
108 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
110 $this->hashLevels
= isset( $info['hashLevels'] )
111 ?
$info['hashLevels']
113 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
114 ?
$info['deletedHashLevels']
116 $this->transformVia404
= !empty( $info['transformVia404'] );
117 $this->abbrvThreshold
= isset( $info['abbrvThreshold'] )
118 ?
$info['abbrvThreshold']
120 $this->isPrivate
= !empty( $info['isPrivate'] );
121 // Give defaults for the basic zones...
122 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
123 foreach ( array( 'public', 'thumb', 'transcoded', 'temp', 'deleted' ) as $zone ) {
124 if ( !isset( $this->zones
[$zone]['container'] ) ) {
125 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
127 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
128 $this->zones
[$zone]['directory'] = '';
130 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
131 $this->zones
[$zone]['urlsByExt'] = array();
137 * Get the file backend instance. Use this function wisely.
139 * @return FileBackend
141 public function getBackend() {
142 return $this->backend
;
146 * Get an explanatory message if this repo is read-only.
147 * This checks if an administrator disabled writes to the backend.
149 * @return string|bool Returns false if the repo is not read-only
151 public function getReadOnlyReason() {
152 return $this->backend
->getReadOnlyReason();
156 * Check if a single zone or list of zones is defined for usage
158 * @param $doZones Array Only do a particular zones
159 * @throws MWException
162 protected function initZones( $doZones = array() ) {
163 $status = $this->newGood();
164 foreach ( (array)$doZones as $zone ) {
165 $root = $this->getZonePath( $zone );
166 if ( $root === null ) {
167 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
174 * Determine if a string is an mwrepo:// URL
179 public static function isVirtualUrl( $url ) {
180 return substr( $url, 0, 9 ) == 'mwrepo://';
184 * Get a URL referring to this repository, with the private mwrepo protocol.
185 * The suffix, if supplied, is considered to be unencoded, and will be
186 * URL-encoded before being returned.
188 * @param $suffix string|bool
191 public function getVirtualUrl( $suffix = false ) {
192 $path = 'mwrepo://' . $this->name
;
193 if ( $suffix !== false ) {
194 $path .= '/' . rawurlencode( $suffix );
200 * Get the URL corresponding to one of the four basic zones
202 * @param $zone String One of: public, deleted, temp, thumb
203 * @param $ext String|null Optional file extension
204 * @return String or false
206 public function getZoneUrl( $zone, $ext = null ) {
207 if ( in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) ) ) { // standard public zones
208 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
209 return $this->zones
[$zone]['urlsByExt'][$ext]; // custom URL for extension/zone
210 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
211 return $this->zones
[$zone]['url']; // custom URL for zone
218 return "{$this->url}/temp";
220 return false; // no public URL
222 return $this->thumbUrl
;
224 return "{$this->url}/transcoded";
231 * Get the thumb zone URL configured to be handled by scripts like thumb_handler.php.
232 * This is probably only useful for internal requests, such as from a fast frontend server
233 * to a slower backend server.
235 * Large sites may use a different host name for uploads than for wikis. In any case, the
236 * wiki configuration is needed in order to use thumb.php. To avoid extracting the wiki ID
237 * from the URL path, one can configure thumb_handler.php to recognize a special path on the
238 * same host name as the wiki that is used for viewing thumbnails.
240 * @param $zone String: one of: public, deleted, temp, thumb
241 * @return String or false
243 public function getZoneHandlerUrl( $zone ) {
244 if ( isset( $this->zones
[$zone]['handlerUrl'] )
245 && in_array( $zone, array( 'public', 'temp', 'thumb', 'transcoded' ) ) )
247 return $this->zones
[$zone]['handlerUrl'];
253 * Get the backend storage path corresponding to a virtual URL.
254 * Use this function wisely.
257 * @throws MWException
260 public function resolveVirtualUrl( $url ) {
261 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
262 throw new MWException( __METHOD__
.': unknown protocol' );
264 $bits = explode( '/', substr( $url, 9 ), 3 );
265 if ( count( $bits ) != 3 ) {
266 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
268 list( $repo, $zone, $rel ) = $bits;
269 if ( $repo !== $this->name
) {
270 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
272 $base = $this->getZonePath( $zone );
274 throw new MWException( __METHOD__
.": invalid zone: $zone" );
276 return $base . '/' . rawurldecode( $rel );
280 * The the storage container and base path of a zone
282 * @param $zone string
283 * @return Array (container, base path) or (null, null)
285 protected function getZoneLocation( $zone ) {
286 if ( !isset( $this->zones
[$zone] ) ) {
287 return array( null, null ); // bogus
289 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
293 * Get the storage path corresponding to one of the zones
295 * @param $zone string
296 * @return string|null Returns null if the zone is not defined
298 public function getZonePath( $zone ) {
299 list( $container, $base ) = $this->getZoneLocation( $zone );
300 if ( $container === null ||
$base === null ) {
303 $backendName = $this->backend
->getName();
304 if ( $base != '' ) { // may not be set
307 return "mwstore://$backendName/{$container}{$base}";
311 * Create a new File object from the local repository
313 * @param $title Mixed: Title object or string
314 * @param $time Mixed: Time at which the image was uploaded.
315 * If this is specified, the returned object will be an
316 * instance of the repository's old file class instead of a
317 * current file. Repositories not supporting version control
318 * should return false if this parameter is set.
319 * @return File|null A File, or null if passed an invalid Title
321 public function newFile( $title, $time = false ) {
322 $title = File
::normalizeTitle( $title );
327 if ( $this->oldFileFactory
) {
328 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
333 return call_user_func( $this->fileFactory
, $title, $this );
338 * Find an instance of the named file created at the specified time
339 * Returns false if the file does not exist. Repositories not supporting
340 * version control should return false if the time is specified.
342 * @param $title Mixed: Title object or string
343 * @param $options array Associative array of options:
344 * time: requested time for a specific file version, or false for the
345 * current version. An image object will be returned which was
346 * created at the specified time (which may be archived or current).
348 * ignoreRedirect: If true, do not follow file redirects
350 * private: If true, return restricted (deleted) files if the current
351 * user is allowed to view them. Otherwise, such files will not
353 * @return File|bool False on failure
355 public function findFile( $title, $options = array() ) {
356 $title = File
::normalizeTitle( $title );
360 $time = isset( $options['time'] ) ?
$options['time'] : false;
361 # First try the current version of the file to see if it precedes the timestamp
362 $img = $this->newFile( $title );
366 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
369 # Now try an old version of the file
370 if ( $time !== false ) {
371 $img = $this->newFile( $title, $time );
372 if ( $img && $img->exists() ) {
373 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
374 return $img; // always OK
375 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
382 if ( !empty( $options['ignoreRedirect'] ) ) {
385 $redir = $this->checkRedirect( $title );
386 if ( $redir && $title->getNamespace() == NS_FILE
) {
387 $img = $this->newFile( $redir );
391 if ( $img->exists() ) {
392 $img->redirectedFrom( $title->getDBkey() );
400 * Find many files at once.
402 * @param $items array An array of titles, or an array of findFile() options with
403 * the "title" option giving the title. Example:
405 * $findItem = array( 'title' => $title, 'private' => true );
406 * $findBatch = array( $findItem );
407 * $repo->findFiles( $findBatch );
410 public function findFiles( array $items ) {
412 foreach ( $items as $item ) {
413 if ( is_array( $item ) ) {
414 $title = $item['title'];
416 unset( $options['title'] );
421 $file = $this->findFile( $title, $options );
423 $result[$file->getTitle()->getDBkey()] = $file;
430 * Find an instance of the file with this key, created at the specified time
431 * Returns false if the file does not exist. Repositories not supporting
432 * version control should return false if the time is specified.
434 * @param $sha1 String base 36 SHA-1 hash
435 * @param $options array Option array, same as findFile().
436 * @return File|bool False on failure
438 public function findFileFromKey( $sha1, $options = array() ) {
439 $time = isset( $options['time'] ) ?
$options['time'] : false;
440 # First try to find a matching current version of a file...
441 if ( $this->fileFactoryKey
) {
442 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
444 return false; // find-by-sha1 not supported
446 if ( $img && $img->exists() ) {
449 # Now try to find a matching old version of a file...
450 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
451 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
452 if ( $img && $img->exists() ) {
453 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
454 return $img; // always OK
455 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
464 * Get an array or iterator of file objects for files that have a given
465 * SHA-1 content hash.
471 public function findBySha1( $hash ) {
476 * Get an array of arrays or iterators of file objects for files that
477 * have the given SHA-1 content hashes.
479 * @param $hashes array An array of hashes
480 * @return array An Array of arrays or iterators of file objects and the hash as key
482 public function findBySha1s( array $hashes ) {
484 foreach ( $hashes as $hash ) {
485 $files = $this->findBySha1( $hash );
486 if ( count( $files ) ) {
487 $result[$hash] = $files;
494 * Get the public root URL of the repository
496 * @deprecated since 1.20
499 public function getRootUrl() {
500 return $this->getZoneUrl( 'public' );
504 * Get the URL of thumb.php
508 public function getThumbScriptUrl() {
509 return $this->thumbScriptUrl
;
513 * Returns true if the repository can transform files via a 404 handler
517 public function canTransformVia404() {
518 return $this->transformVia404
;
522 * Get the name of an image from its title object
524 * @param $title Title
527 public function getNameFromTitle( Title
$title ) {
529 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
530 $name = $title->getUserCaseDBKey();
531 if ( $this->initialCapital
) {
532 $name = $wgContLang->ucfirst( $name );
535 $name = $title->getDBkey();
541 * Get the public zone root storage directory of the repository
545 public function getRootDirectory() {
546 return $this->getZonePath( 'public' );
550 * Get a relative path including trailing slash, e.g. f/fa/
551 * If the repo is not hashed, returns an empty string
553 * @param $name string Name of file
556 public function getHashPath( $name ) {
557 return self
::getHashPathForLevel( $name, $this->hashLevels
);
561 * Get a relative path including trailing slash, e.g. f/fa/
562 * If the repo is not hashed, returns an empty string
564 * @param $suffix string Basename of file from FileRepo::storeTemp()
567 public function getTempHashPath( $suffix ) {
568 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
569 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
570 return self
::getHashPathForLevel( $name, $this->hashLevels
);
578 protected static function getHashPathForLevel( $name, $levels ) {
579 if ( $levels == 0 ) {
582 $hash = md5( $name );
584 for ( $i = 1; $i <= $levels; $i++
) {
585 $path .= substr( $hash, 0, $i ) . '/';
592 * Get the number of hash directory levels
596 public function getHashLevels() {
597 return $this->hashLevels
;
601 * Get the name of this repository, as specified by $info['name]' to the constructor
605 public function getName() {
610 * Make an url to this repo
612 * @param $query mixed Query string to append
613 * @param $entry string Entry point; defaults to index
614 * @return string|bool False on failure
616 public function makeUrl( $query = '', $entry = 'index' ) {
617 if ( isset( $this->scriptDirUrl
) ) {
618 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
619 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
625 * Get the URL of an image description page. May return false if it is
626 * unknown or not applicable. In general this should only be called by the
627 * File class, since it may return invalid results for certain kinds of
628 * repositories. Use File::getDescriptionUrl() in user code.
630 * In particular, it uses the article paths as specified to the repository
631 * constructor, whereas local repositories use the local Title functions.
633 * @param $name string
636 public function getDescriptionUrl( $name ) {
637 $encName = wfUrlencode( $name );
638 if ( !is_null( $this->descBaseUrl
) ) {
639 # "http://example.com/wiki/Image:"
640 return $this->descBaseUrl
. $encName;
642 if ( !is_null( $this->articleUrl
) ) {
643 # "http://example.com/wiki/$1"
645 # We use "Image:" as the canonical namespace for
646 # compatibility across all MediaWiki versions.
647 return str_replace( '$1',
648 "Image:$encName", $this->articleUrl
);
650 if ( !is_null( $this->scriptDirUrl
) ) {
651 # "http://example.com/w"
653 # We use "Image:" as the canonical namespace for
654 # compatibility across all MediaWiki versions,
655 # and just sort of hope index.php is right. ;)
656 return $this->makeUrl( "title=Image:$encName" );
662 * Get the URL of the content-only fragment of the description page. For
663 * MediaWiki this means action=render. This should only be called by the
664 * repository's file class, since it may return invalid results. User code
665 * should use File::getDescriptionText().
667 * @param $name String: name of image to fetch
668 * @param $lang String: language to fetch it in, if any.
671 public function getDescriptionRenderUrl( $name, $lang = null ) {
672 $query = 'action=render';
673 if ( !is_null( $lang ) ) {
674 $query .= '&uselang=' . $lang;
676 if ( isset( $this->scriptDirUrl
) ) {
677 return $this->makeUrl(
679 wfUrlencode( 'Image:' . $name ) .
682 $descUrl = $this->getDescriptionUrl( $name );
684 return wfAppendQuery( $descUrl, $query );
692 * Get the URL of the stylesheet to apply to description pages
694 * @return string|bool False on failure
696 public function getDescriptionStylesheetUrl() {
697 if ( isset( $this->scriptDirUrl
) ) {
698 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
699 wfArrayToCgi( Skin
::getDynamicStylesheetQuery() ) );
705 * Store a file to a given destination.
707 * @param $srcPath String: source file system path, storage path, or virtual URL
708 * @param $dstZone String: destination zone
709 * @param $dstRel String: destination relative path
710 * @param $flags Integer: bitwise combination of the following flags:
711 * self::DELETE_SOURCE Delete the source file after upload
712 * self::OVERWRITE Overwrite an existing destination file instead of failing
713 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
714 * same contents as the source
715 * self::SKIP_LOCKING Skip any file locking when doing the store
716 * @return FileRepoStatus
718 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
719 $this->assertWritableRepo(); // fail out if read-only
721 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
722 if ( $status->successCount
== 0 ) {
730 * Store a batch of files
732 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
733 * @param $flags Integer: bitwise combination of the following flags:
734 * self::DELETE_SOURCE Delete the source file after upload
735 * self::OVERWRITE Overwrite an existing destination file instead of failing
736 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
737 * same contents as the source
738 * self::SKIP_LOCKING Skip any file locking when doing the store
739 * @throws MWException
740 * @return FileRepoStatus
742 public function storeBatch( array $triplets, $flags = 0 ) {
743 $this->assertWritableRepo(); // fail out if read-only
745 $status = $this->newGood();
746 $backend = $this->backend
; // convenience
748 $operations = array();
749 $sourceFSFilesToDelete = array(); // cleanup for disk source files
750 // Validate each triplet and get the store operation...
751 foreach ( $triplets as $triplet ) {
752 list( $srcPath, $dstZone, $dstRel ) = $triplet;
754 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
757 // Resolve destination path
758 $root = $this->getZonePath( $dstZone );
760 throw new MWException( "Invalid zone: $dstZone" );
762 if ( !$this->validateFilename( $dstRel ) ) {
763 throw new MWException( 'Validation error in $dstRel' );
765 $dstPath = "$root/$dstRel";
766 $dstDir = dirname( $dstPath );
767 // Create destination directories for this triplet
768 if ( !$this->initDirectory( $dstDir )->isOK() ) {
769 return $this->newFatal( 'directorycreateerror', $dstDir );
772 // Resolve source to a storage path if virtual
773 $srcPath = $this->resolveToStoragePath( $srcPath );
775 // Get the appropriate file operation
776 if ( FileBackend
::isStoragePath( $srcPath ) ) {
777 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
780 if ( $flags & self
::DELETE_SOURCE
) {
781 $sourceFSFilesToDelete[] = $srcPath;
784 $operations[] = array(
788 'overwrite' => $flags & self
::OVERWRITE
,
789 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
793 // Execute the store operation for each triplet
794 $opts = array( 'force' => true );
795 if ( $flags & self
::SKIP_LOCKING
) {
796 $opts['nonLocking'] = true;
798 $status->merge( $backend->doOperations( $operations, $opts ) );
799 // Cleanup for disk source files...
800 foreach ( $sourceFSFilesToDelete as $file ) {
801 wfSuppressWarnings();
802 unlink( $file ); // FS cleanup
810 * Deletes a batch of files.
811 * Each file can be a (zone, rel) pair, virtual url, storage path.
812 * It will try to delete each file, but ignores any errors that may occur.
814 * @param $files array List of files to delete
815 * @param $flags Integer: bitwise combination of the following flags:
816 * self::SKIP_LOCKING Skip any file locking when doing the deletions
817 * @return FileRepoStatus
819 public function cleanupBatch( array $files, $flags = 0 ) {
820 $this->assertWritableRepo(); // fail out if read-only
822 $status = $this->newGood();
824 $operations = array();
825 foreach ( $files as $path ) {
826 if ( is_array( $path ) ) {
827 // This is a pair, extract it
828 list( $zone, $rel ) = $path;
829 $path = $this->getZonePath( $zone ) . "/$rel";
831 // Resolve source to a storage path if virtual
832 $path = $this->resolveToStoragePath( $path );
834 $operations[] = array( 'op' => 'delete', 'src' => $path );
836 // Actually delete files from storage...
837 $opts = array( 'force' => true );
838 if ( $flags & self
::SKIP_LOCKING
) {
839 $opts['nonLocking'] = true;
841 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
847 * Import a file from the local file system into the repo.
848 * This does no locking nor journaling and overrides existing files.
849 * This function can be used to write to otherwise read-only foreign repos.
850 * This is intended for copying generated thumbnails into the repo.
852 * @param $src string Source file system path, storage path, or virtual URL
853 * @param $dst string Virtual URL or storage path
854 * @param $disposition string|null Content-Disposition if given and supported
855 * @return FileRepoStatus
857 final public function quickImport( $src, $dst, $disposition = null ) {
858 return $this->quickImportBatch( array( array( $src, $dst, $disposition ) ) );
862 * Purge a file from the repo. This does no locking nor journaling.
863 * This function can be used to write to otherwise read-only foreign repos.
864 * This is intended for purging thumbnails.
866 * @param $path string Virtual URL or storage path
867 * @return FileRepoStatus
869 final public function quickPurge( $path ) {
870 return $this->quickPurgeBatch( array( $path ) );
874 * Deletes a directory if empty.
875 * This function can be used to write to otherwise read-only foreign repos.
877 * @param $dir string Virtual URL (or storage path) of directory to clean
880 public function quickCleanDir( $dir ) {
881 $status = $this->newGood();
882 $status->merge( $this->backend
->clean(
883 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
889 * Import a batch of files from the local file system into the repo.
890 * This does no locking nor journaling and overrides existing files.
891 * This function can be used to write to otherwise read-only foreign repos.
892 * This is intended for copying generated thumbnails into the repo.
894 * All path parameters may be a file system path, storage path, or virtual URL.
895 * When "dispositions" are given they are used as Content-Disposition if supported.
897 * @param $triples Array List of (source path, destination path, disposition)
898 * @return FileRepoStatus
900 public function quickImportBatch( array $triples ) {
901 $status = $this->newGood();
902 $operations = array();
903 foreach ( $triples as $triple ) {
904 list( $src, $dst ) = $triple;
905 $src = $this->resolveToStoragePath( $src );
906 $dst = $this->resolveToStoragePath( $dst );
907 $operations[] = array(
908 'op' => FileBackend
::isStoragePath( $src ) ?
'copy' : 'store',
911 'disposition' => isset( $triple[2] ) ?
$triple[2] : null
913 $status->merge( $this->initDirectory( dirname( $dst ) ) );
915 $status->merge( $this->backend
->doQuickOperations( $operations ) );
921 * Purge a batch of files from the repo.
922 * This function can be used to write to otherwise read-only foreign repos.
923 * This does no locking nor journaling and is intended for purging thumbnails.
925 * @param $paths Array List of virtual URLs or storage paths
926 * @return FileRepoStatus
928 public function quickPurgeBatch( array $paths ) {
929 $status = $this->newGood();
930 $operations = array();
931 foreach ( $paths as $path ) {
932 $operations[] = array(
934 'src' => $this->resolveToStoragePath( $path ),
935 'ignoreMissingSource' => true
938 $status->merge( $this->backend
->doQuickOperations( $operations ) );
944 * Pick a random name in the temp zone and store a file to it.
945 * Returns a FileRepoStatus object with the file Virtual URL in the value,
946 * file can later be disposed using FileRepo::freeTemp().
948 * @param $originalName String: the base name of the file as specified
949 * by the user. The file extension will be maintained.
950 * @param $srcPath String: the current location of the file.
951 * @return FileRepoStatus object with the URL in the value.
953 public function storeTemp( $originalName, $srcPath ) {
954 $this->assertWritableRepo(); // fail out if read-only
956 $date = gmdate( "YmdHis" );
957 $hashPath = $this->getHashPath( $originalName );
958 $dstRel = "{$hashPath}{$date}!{$originalName}";
959 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
960 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
962 $result = $this->quickImport( $srcPath, $virtualUrl );
963 $result->value
= $virtualUrl;
969 * Remove a temporary file or mark it for garbage collection
971 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
972 * @return Boolean: true on success, false on failure
974 public function freeTemp( $virtualUrl ) {
975 $this->assertWritableRepo(); // fail out if read-only
977 $temp = $this->getVirtualUrl( 'temp' );
978 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
979 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
983 return $this->quickPurge( $virtualUrl )->isOK();
987 * Concatenate a list of temporary files into a target file location.
989 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
990 * @param $dstPath String Target file system path
991 * @param $flags Integer: bitwise combination of the following flags:
992 * self::DELETE_SOURCE Delete the source files
993 * @return FileRepoStatus
995 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
996 $this->assertWritableRepo(); // fail out if read-only
998 $status = $this->newGood();
1001 foreach ( $srcPaths as $srcPath ) {
1002 // Resolve source to a storage path if virtual
1003 $source = $this->resolveToStoragePath( $srcPath );
1004 $sources[] = $source; // chunk to merge
1007 // Concatenate the chunks into one FS file
1008 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1009 $status->merge( $this->backend
->concatenate( $params ) );
1010 if ( !$status->isOK() ) {
1014 // Delete the sources if required
1015 if ( $flags & self
::DELETE_SOURCE
) {
1016 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1019 // Make sure status is OK, despite any quickPurgeBatch() fatals
1020 $status->setResult( true );
1026 * Copy or move a file either from a storage path, virtual URL,
1027 * or file system path, into this repository at the specified destination location.
1029 * Returns a FileRepoStatus object. On success, the value contains "new" or
1030 * "archived", to indicate whether the file was new with that name.
1032 * Options to $options include:
1033 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1035 * @param $srcPath String: the source file system path, storage path, or URL
1036 * @param $dstRel String: the destination relative path
1037 * @param $archiveRel String: the relative path where the existing file is to
1038 * be archived, if there is one. Relative to the public zone root.
1039 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1040 * that the source file should be deleted if possible
1041 * @param $options Array Optional additional parameters
1042 * @return FileRepoStatus
1044 public function publish(
1045 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1047 $this->assertWritableRepo(); // fail out if read-only
1049 $status = $this->publishBatch(
1050 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1051 if ( $status->successCount
== 0 ) {
1052 $status->ok
= false;
1054 if ( isset( $status->value
[0] ) ) {
1055 $status->value
= $status->value
[0];
1057 $status->value
= false;
1064 * Publish a batch of files
1066 * @param $ntuples Array: (source, dest, archive) triplets or
1067 * (source, dest, archive, options) 4-tuples as per publish().
1068 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1069 * that the source files should be deleted if possible
1070 * @throws MWException
1071 * @return FileRepoStatus
1073 public function publishBatch( array $ntuples, $flags = 0 ) {
1074 $this->assertWritableRepo(); // fail out if read-only
1076 $backend = $this->backend
; // convenience
1077 // Try creating directories
1078 $status = $this->initZones( 'public' );
1079 if ( !$status->isOK() ) {
1083 $status = $this->newGood( array() );
1085 $operations = array();
1086 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1087 // Validate each triplet and get the store operation...
1088 foreach ( $ntuples as $i => $ntuple ) {
1089 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1090 $options = isset( $ntuple[3] ) ?
$ntuple[3] : array();
1091 // Resolve source to a storage path if virtual
1092 $srcPath = $this->resolveToStoragePath( $srcPath );
1093 if ( !$this->validateFilename( $dstRel ) ) {
1094 throw new MWException( 'Validation error in $dstRel' );
1096 if ( !$this->validateFilename( $archiveRel ) ) {
1097 throw new MWException( 'Validation error in $archiveRel' );
1100 $publicRoot = $this->getZonePath( 'public' );
1101 $dstPath = "$publicRoot/$dstRel";
1102 $archivePath = "$publicRoot/$archiveRel";
1104 $dstDir = dirname( $dstPath );
1105 $archiveDir = dirname( $archivePath );
1106 // Abort immediately on directory creation errors since they're likely to be repetitive
1107 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1108 return $this->newFatal( 'directorycreateerror', $dstDir );
1110 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1111 return $this->newFatal( 'directorycreateerror', $archiveDir );
1114 // Set any desired headers to be use in GET/HEAD responses
1115 $headers = isset( $options['headers'] ) ?
$options['headers'] : array();
1117 // Archive destination file if it exists.
1118 // This will check if the archive file also exists and fail if does.
1119 // This is a sanity check to avoid data loss. On Windows and Linux,
1120 // copy() will overwrite, so the existence check is vulnerable to
1121 // race conditions unless an functioning LockManager is used.
1122 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1123 $operations[] = array(
1126 'dst' => $archivePath,
1127 'ignoreMissingSource' => true
1130 // Copy (or move) the source file to the destination
1131 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1132 if ( $flags & self
::DELETE_SOURCE
) {
1133 $operations[] = array(
1137 'overwrite' => true, // replace current
1138 'headers' => $headers
1141 $operations[] = array(
1145 'overwrite' => true, // replace current
1146 'headers' => $headers
1149 } else { // FS source path
1150 $operations[] = array(
1154 'overwrite' => true, // replace current
1155 'headers' => $headers
1157 if ( $flags & self
::DELETE_SOURCE
) {
1158 $sourceFSFilesToDelete[] = $srcPath;
1163 // Execute the operations for each triplet
1164 $status->merge( $backend->doOperations( $operations ) );
1165 // Find out which files were archived...
1166 foreach ( $ntuples as $i => $ntuple ) {
1167 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1168 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1169 if ( $this->fileExists( $archivePath ) ) {
1170 $status->value
[$i] = 'archived';
1172 $status->value
[$i] = 'new';
1175 // Cleanup for disk source files...
1176 foreach ( $sourceFSFilesToDelete as $file ) {
1177 wfSuppressWarnings();
1178 unlink( $file ); // FS cleanup
1179 wfRestoreWarnings();
1186 * Creates a directory with the appropriate zone permissions.
1187 * Callers are responsible for doing read-only and "writable repo" checks.
1189 * @param $dir string Virtual URL (or storage path) of directory to clean
1192 protected function initDirectory( $dir ) {
1193 $path = $this->resolveToStoragePath( $dir );
1194 list( $b, $container, $r ) = FileBackend
::splitStoragePath( $path );
1196 $params = array( 'dir' => $path );
1197 if ( $this->isPrivate ||
$container === $this->zones
['deleted']['container'] ) {
1198 # Take all available measures to prevent web accessibility of new deleted
1199 # directories, in case the user has not configured offline storage
1200 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1203 return $this->backend
->prepare( $params );
1207 * Deletes a directory if empty.
1209 * @param $dir string Virtual URL (or storage path) of directory to clean
1212 public function cleanDir( $dir ) {
1213 $this->assertWritableRepo(); // fail out if read-only
1215 $status = $this->newGood();
1216 $status->merge( $this->backend
->clean(
1217 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1223 * Checks existence of a a file
1225 * @param $file string Virtual URL (or storage path) of file to check
1228 public function fileExists( $file ) {
1229 $result = $this->fileExistsBatch( array( $file ) );
1234 * Checks existence of an array of files.
1236 * @param $files Array: Virtual URLs (or storage paths) of files to check
1237 * @return array|bool Either array of files and existence flags, or false
1239 public function fileExistsBatch( array $files ) {
1241 foreach ( $files as $key => $file ) {
1242 $file = $this->resolveToStoragePath( $file );
1243 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1249 * Move a file to the deletion archive.
1250 * If no valid deletion archive exists, this may either delete the file
1251 * or throw an exception, depending on the preference of the repository
1253 * @param $srcRel Mixed: relative path for the file to be deleted
1254 * @param $archiveRel Mixed: relative path for the archive location.
1255 * Relative to a private archive directory.
1256 * @return FileRepoStatus object
1258 public function delete( $srcRel, $archiveRel ) {
1259 $this->assertWritableRepo(); // fail out if read-only
1261 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1265 * Move a group of files to the deletion archive.
1267 * If no valid deletion archive is configured, this may either delete the
1268 * file or throw an exception, depending on the preference of the repository.
1270 * The overwrite policy is determined by the repository -- currently LocalRepo
1271 * assumes a naming scheme in the deleted zone based on content hash, as
1272 * opposed to the public zone which is assumed to be unique.
1274 * @param $sourceDestPairs Array of source/destination pairs. Each element
1275 * is a two-element array containing the source file path relative to the
1276 * public root in the first element, and the archive file path relative
1277 * to the deleted zone root in the second element.
1278 * @throws MWException
1279 * @return FileRepoStatus
1281 public function deleteBatch( array $sourceDestPairs ) {
1282 $this->assertWritableRepo(); // fail out if read-only
1284 // Try creating directories
1285 $status = $this->initZones( array( 'public', 'deleted' ) );
1286 if ( !$status->isOK() ) {
1290 $status = $this->newGood();
1292 $backend = $this->backend
; // convenience
1293 $operations = array();
1294 // Validate filenames and create archive directories
1295 foreach ( $sourceDestPairs as $pair ) {
1296 list( $srcRel, $archiveRel ) = $pair;
1297 if ( !$this->validateFilename( $srcRel ) ) {
1298 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1299 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1300 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1303 $publicRoot = $this->getZonePath( 'public' );
1304 $srcPath = "{$publicRoot}/$srcRel";
1306 $deletedRoot = $this->getZonePath( 'deleted' );
1307 $archivePath = "{$deletedRoot}/{$archiveRel}";
1308 $archiveDir = dirname( $archivePath ); // does not touch FS
1310 // Create destination directories
1311 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1312 return $this->newFatal( 'directorycreateerror', $archiveDir );
1315 $operations[] = array(
1318 'dst' => $archivePath,
1319 // We may have 2+ identical files being deleted,
1320 // all of which will map to the same destination file
1321 'overwriteSame' => true // also see bug 31792
1325 // Move the files by execute the operations for each pair.
1326 // We're now committed to returning an OK result, which will
1327 // lead to the files being moved in the DB also.
1328 $opts = array( 'force' => true );
1329 $status->merge( $backend->doOperations( $operations, $opts ) );
1335 * Delete files in the deleted directory if they are not referenced in the filearchive table
1339 public function cleanupDeletedBatch( array $storageKeys ) {
1340 $this->assertWritableRepo();
1344 * Get a relative path for a deletion archive key,
1345 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1347 * @param $key string
1348 * @throws MWException
1351 public function getDeletedHashPath( $key ) {
1352 if ( strlen( $key ) < 31 ) {
1353 throw new MWException( "Invalid storage key '$key'." );
1356 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1357 $path .= $key[$i] . '/';
1363 * If a path is a virtual URL, resolve it to a storage path.
1364 * Otherwise, just return the path as it is.
1366 * @param $path string
1368 * @throws MWException
1370 protected function resolveToStoragePath( $path ) {
1371 if ( $this->isVirtualUrl( $path ) ) {
1372 return $this->resolveVirtualUrl( $path );
1378 * Get a local FS copy of a file with a given virtual URL/storage path.
1379 * Temporary files may be purged when the file object falls out of scope.
1381 * @param $virtualUrl string
1382 * @return TempFSFile|null Returns null on failure
1384 public function getLocalCopy( $virtualUrl ) {
1385 $path = $this->resolveToStoragePath( $virtualUrl );
1386 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1390 * Get a local FS file with a given virtual URL/storage path.
1391 * The file is either an original or a copy. It should not be changed.
1392 * Temporary files may be purged when the file object falls out of scope.
1394 * @param $virtualUrl string
1395 * @return FSFile|null Returns null on failure.
1397 public function getLocalReference( $virtualUrl ) {
1398 $path = $this->resolveToStoragePath( $virtualUrl );
1399 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1403 * Get properties of a file with a given virtual URL/storage path.
1404 * Properties should ultimately be obtained via FSFile::getProps().
1406 * @param $virtualUrl string
1409 public function getFileProps( $virtualUrl ) {
1410 $path = $this->resolveToStoragePath( $virtualUrl );
1411 return $this->backend
->getFileProps( array( 'src' => $path ) );
1415 * Get the timestamp of a file with a given virtual URL/storage path
1417 * @param $virtualUrl string
1418 * @return string|bool False on failure
1420 public function getFileTimestamp( $virtualUrl ) {
1421 $path = $this->resolveToStoragePath( $virtualUrl );
1422 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1426 * Get the size of a file with a given virtual URL/storage path
1428 * @param $virtualUrl string
1429 * @return integer|bool False on failure
1431 public function getFileSize( $virtualUrl ) {
1432 $path = $this->resolveToStoragePath( $virtualUrl );
1433 return $this->backend
->getFileSize( array( 'src' => $path ) );
1437 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1439 * @param $virtualUrl string
1440 * @return string|bool
1442 public function getFileSha1( $virtualUrl ) {
1443 $path = $this->resolveToStoragePath( $virtualUrl );
1444 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1448 * Attempt to stream a file with the given virtual URL/storage path
1450 * @param $virtualUrl string
1451 * @param $headers Array Additional HTTP headers to send on success
1452 * @return bool Success
1454 public function streamFile( $virtualUrl, $headers = array() ) {
1455 $path = $this->resolveToStoragePath( $virtualUrl );
1456 $params = array( 'src' => $path, 'headers' => $headers );
1457 return $this->backend
->streamFile( $params )->isOK();
1461 * Call a callback function for every public regular file in the repository.
1462 * This only acts on the current version of files, not any old versions.
1463 * May use either the database or the filesystem.
1465 * @param $callback Array|string
1468 public function enumFiles( $callback ) {
1469 $this->enumFilesInStorage( $callback );
1473 * Call a callback function for every public file in the repository.
1474 * May use either the database or the filesystem.
1476 * @param $callback Array|string
1479 protected function enumFilesInStorage( $callback ) {
1480 $publicRoot = $this->getZonePath( 'public' );
1481 $numDirs = 1 << ( $this->hashLevels
* 4 );
1482 // Use a priori assumptions about directory structure
1483 // to reduce the tree height of the scanning process.
1484 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1485 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1486 $path = $publicRoot;
1487 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1488 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1490 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1491 foreach ( $iterator as $name ) {
1492 // Each item returned is a public file
1493 call_user_func( $callback, "{$path}/{$name}" );
1499 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1501 * @param $filename string
1504 public function validateFilename( $filename ) {
1505 if ( strval( $filename ) == '' ) {
1508 return FileBackend
::isPathTraversalFree( $filename );
1512 * Get a callback function to use for cleaning error message parameters
1516 function getErrorCleanupFunction() {
1517 switch ( $this->pathDisclosureProtection
) {
1519 case 'simple': // b/c
1520 $callback = array( $this, 'passThrough' );
1522 default: // 'paranoid'
1523 $callback = array( $this, 'paranoidClean' );
1529 * Path disclosure protection function
1531 * @param $param string
1534 function paranoidClean( $param ) {
1539 * Path disclosure protection function
1541 * @param $param string
1544 function passThrough( $param ) {
1549 * Create a new fatal error
1551 * @return FileRepoStatus
1553 public function newFatal( $message /*, parameters...*/ ) {
1554 $params = func_get_args();
1555 array_unshift( $params, $this );
1556 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1560 * Create a new good result
1562 * @param $value null|string
1563 * @return FileRepoStatus
1565 public function newGood( $value = null ) {
1566 return FileRepoStatus
::newGood( $this, $value );
1570 * Checks if there is a redirect named as $title. If there is, return the
1571 * title object. If not, return false.
1574 * @param $title Title of image
1577 public function checkRedirect( Title
$title ) {
1582 * Invalidates image redirect cache related to that image
1583 * Doesn't do anything for repositories that don't support image redirects.
1586 * @param $title Title of image
1588 public function invalidateImageRedirect( Title
$title ) {}
1591 * Get the human-readable name of the repo
1595 public function getDisplayName() {
1596 // We don't name our own repo, return nothing
1597 if ( $this->isLocal() ) {
1600 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1601 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1605 * Get the portion of the file that contains the origin file name.
1606 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1608 * @param $name string
1611 public function nameForThumb( $name ) {
1612 if ( strlen( $name ) > $this->abbrvThreshold
) {
1613 $ext = FileBackend
::extensionFromPath( $name );
1614 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1620 * Returns true if this the local file repository.
1624 public function isLocal() {
1625 return $this->getName() == 'local';
1629 * Get a key on the primary cache for this repository.
1630 * Returns false if the repository's cache is not accessible at this site.
1631 * The parameters are the parts of the key, as for wfMemcKey().
1636 public function getSharedCacheKey( /*...*/ ) {
1641 * Get a key for this repo in the local cache domain. These cache keys are
1642 * not shared with remote instances of the repo.
1643 * The parameters are the parts of the key, as for wfMemcKey().
1647 public function getLocalCacheKey( /*...*/ ) {
1648 $args = func_get_args();
1649 array_unshift( $args, 'filerepo', $this->getName() );
1650 return call_user_func_array( 'wfMemcKey', $args );
1654 * Get an temporary FileRepo associated with this repo.
1655 * Files will be created in the temp zone of this repo and
1656 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1657 * It will have the same backend as this repo.
1659 * @return TempFileRepo
1661 public function getTempRepo() {
1662 return new TempFileRepo( array(
1663 'name' => "{$this->name}-temp",
1664 'backend' => $this->backend
,
1667 'container' => $this->zones
['temp']['container'],
1668 'directory' => $this->zones
['temp']['directory']
1671 'container' => $this->zones
['thumb']['container'],
1672 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1674 : $this->zones
['thumb']['directory'] . '/temp'
1676 'transcoded' => array(
1677 'container' => $this->zones
['transcoded']['container'],
1678 'directory' => ( $this->zones
['transcoded']['directory'] == '' )
1680 : $this->zones
['transcoded']['directory'] . '/temp'
1683 'url' => $this->getZoneUrl( 'temp' ),
1684 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1685 'transcodedUrl' => $this->getZoneUrl( 'transcoded' ) . '/temp',
1686 'hashLevels' => $this->hashLevels
// performance
1691 * Get an UploadStash associated with this repo.
1694 * @return UploadStash
1696 public function getUploadStash( User
$user = null ) {
1697 return new UploadStash( $this, $user );
1701 * Throw an exception if this repo is read-only by design.
1702 * This does not and should not check getReadOnlyReason().
1705 * @throws MWException
1707 protected function assertWritableRepo() {}
1711 * FileRepo for temporary files created via FileRepo::getTempRepo()
1713 class TempFileRepo
extends FileRepo
{
1714 public function getTempRepo() {
1715 throw new MWException( "Cannot get a temp repo from a temp repo." );