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;
56 * Factory functions for creating new files
57 * Override these in the base class
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
64 * @param $info array|null
67 public function __construct( array $info = null ) {
68 // Verify required settings presence
71 ||
!array_key_exists( 'name', $info )
72 ||
!array_key_exists( 'backend', $info )
74 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
78 $this->name
= $info['name'];
79 if ( $info['backend'] instanceof FileBackend
) {
80 $this->backend
= $info['backend']; // useful for testing
82 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
85 // Optional settings that can have no value
86 $optionalSettings = array(
87 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
88 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
91 foreach ( $optionalSettings as $var ) {
92 if ( isset( $info[$var] ) ) {
93 $this->$var = $info[$var];
97 // Optional settings that have a default
98 $this->initialCapital
= isset( $info['initialCapital'] )
99 ?
$info['initialCapital']
100 : MWNamespace
::isCapitalized( NS_FILE
);
101 $this->url
= isset( $info['url'] )
103 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
104 if ( isset( $info['thumbUrl'] ) ) {
105 $this->thumbUrl
= $info['thumbUrl'];
107 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
109 $this->hashLevels
= isset( $info['hashLevels'] )
110 ?
$info['hashLevels']
112 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
113 ?
$info['deletedHashLevels']
115 $this->transformVia404
= !empty( $info['transformVia404'] );
116 $this->isPrivate
= !empty( $info['isPrivate'] );
117 // Give defaults for the basic zones...
118 $this->zones
= isset( $info['zones'] ) ?
$info['zones'] : array();
119 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
120 if ( !isset( $this->zones
[$zone]['container'] ) ) {
121 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
123 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
124 $this->zones
[$zone]['directory'] = '';
130 * Get the file backend instance. Use this function wisely.
132 * @return FileBackend
134 public function getBackend() {
135 return $this->backend
;
139 * Get an explanatory message if this repo is read-only.
140 * This checks if an administrator disabled writes to the backend.
142 * @return string|bool Returns false if the repo is not read-only
144 public function getReadOnlyReason() {
145 return $this->backend
->getReadOnlyReason();
149 * Check if a single zone or list of zones is defined for usage
151 * @param $doZones Array Only do a particular zones
152 * @throws MWException
155 protected function initZones( $doZones = array() ) {
156 $status = $this->newGood();
157 foreach ( (array)$doZones as $zone ) {
158 $root = $this->getZonePath( $zone );
159 if ( $root === null ) {
160 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
167 * Determine if a string is an mwrepo:// URL
172 public static function isVirtualUrl( $url ) {
173 return substr( $url, 0, 9 ) == 'mwrepo://';
177 * Get a URL referring to this repository, with the private mwrepo protocol.
178 * The suffix, if supplied, is considered to be unencoded, and will be
179 * URL-encoded before being returned.
181 * @param $suffix string|bool
184 public function getVirtualUrl( $suffix = false ) {
185 $path = 'mwrepo://' . $this->name
;
186 if ( $suffix !== false ) {
187 $path .= '/' . rawurlencode( $suffix );
193 * Get the URL corresponding to one of the four basic zones
195 * @param $zone String: one of: public, deleted, temp, thumb
196 * @return String or false
198 public function getZoneUrl( $zone ) {
199 if ( isset( $this->zones
[$zone]['url'] )
200 && in_array( $zone, array( 'public', 'temp', 'thumb' ) ) )
202 return $this->zones
[$zone]['url']; // custom URL
208 return "{$this->url}/temp";
210 return false; // no public URL
212 return $this->thumbUrl
;
219 * Get the thumb zone URL configured to be handled by scripts like thumb_handler.php.
220 * This is probably only useful for internal requests, such as from a fast frontend server
221 * to a slower backend server.
223 * Large sites may use a different host name for uploads than for wikis. In any case, the
224 * wiki configuration is needed in order to use thumb.php. To avoid extracting the wiki ID
225 * from the URL path, one can configure thumb_handler.php to recognize a special path on the
226 * same host name as the wiki that is used for viewing thumbnails.
228 * @param $zone String: one of: public, deleted, temp, thumb
229 * @return String or false
231 public function getZoneHandlerUrl( $zone ) {
232 if ( isset( $this->zones
[$zone]['handlerUrl'] )
233 && in_array( $zone, array( 'public', 'temp', 'thumb' ) ) )
235 return $this->zones
[$zone]['handlerUrl'];
241 * Get the backend storage path corresponding to a virtual URL.
242 * Use this function wisely.
245 * @throws MWException
248 public function resolveVirtualUrl( $url ) {
249 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
250 throw new MWException( __METHOD__
.': unknown protocol' );
252 $bits = explode( '/', substr( $url, 9 ), 3 );
253 if ( count( $bits ) != 3 ) {
254 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
256 list( $repo, $zone, $rel ) = $bits;
257 if ( $repo !== $this->name
) {
258 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
260 $base = $this->getZonePath( $zone );
262 throw new MWException( __METHOD__
.": invalid zone: $zone" );
264 return $base . '/' . rawurldecode( $rel );
268 * The the storage container and base path of a zone
270 * @param $zone string
271 * @return Array (container, base path) or (null, null)
273 protected function getZoneLocation( $zone ) {
274 if ( !isset( $this->zones
[$zone] ) ) {
275 return array( null, null ); // bogus
277 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
281 * Get the storage path corresponding to one of the zones
283 * @param $zone string
284 * @return string|null Returns null if the zone is not defined
286 public function getZonePath( $zone ) {
287 list( $container, $base ) = $this->getZoneLocation( $zone );
288 if ( $container === null ||
$base === null ) {
291 $backendName = $this->backend
->getName();
292 if ( $base != '' ) { // may not be set
295 return "mwstore://$backendName/{$container}{$base}";
299 * Create a new File object from the local repository
301 * @param $title Mixed: Title object or string
302 * @param $time Mixed: Time at which the image was uploaded.
303 * If this is specified, the returned object will be an
304 * instance of the repository's old file class instead of a
305 * current file. Repositories not supporting version control
306 * should return false if this parameter is set.
307 * @return File|null A File, or null if passed an invalid Title
309 public function newFile( $title, $time = false ) {
310 $title = File
::normalizeTitle( $title );
315 if ( $this->oldFileFactory
) {
316 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
321 return call_user_func( $this->fileFactory
, $title, $this );
326 * Find an instance of the named file created at the specified time
327 * Returns false if the file does not exist. Repositories not supporting
328 * version control should return false if the time is specified.
330 * @param $title Mixed: Title object or string
331 * @param $options array Associative array of options:
332 * time: requested time for a specific file version, or false for the
333 * current version. An image object will be returned which was
334 * created at the specified time (which may be archived or current).
336 * ignoreRedirect: If true, do not follow file redirects
338 * private: If true, return restricted (deleted) files if the current
339 * user is allowed to view them. Otherwise, such files will not
341 * @return File|bool False on failure
343 public function findFile( $title, $options = array() ) {
344 $title = File
::normalizeTitle( $title );
348 $time = isset( $options['time'] ) ?
$options['time'] : false;
349 # First try the current version of the file to see if it precedes the timestamp
350 $img = $this->newFile( $title );
354 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
357 # Now try an old version of the file
358 if ( $time !== false ) {
359 $img = $this->newFile( $title, $time );
360 if ( $img && $img->exists() ) {
361 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
362 return $img; // always OK
363 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
370 if ( !empty( $options['ignoreRedirect'] ) ) {
373 $redir = $this->checkRedirect( $title );
374 if ( $redir && $title->getNamespace() == NS_FILE
) {
375 $img = $this->newFile( $redir );
379 if ( $img->exists() ) {
380 $img->redirectedFrom( $title->getDBkey() );
388 * Find many files at once.
390 * @param $items array An array of titles, or an array of findFile() options with
391 * the "title" option giving the title. Example:
393 * $findItem = array( 'title' => $title, 'private' => true );
394 * $findBatch = array( $findItem );
395 * $repo->findFiles( $findBatch );
398 public function findFiles( array $items ) {
400 foreach ( $items as $item ) {
401 if ( is_array( $item ) ) {
402 $title = $item['title'];
404 unset( $options['title'] );
409 $file = $this->findFile( $title, $options );
411 $result[$file->getTitle()->getDBkey()] = $file;
418 * Find an instance of the file with this key, created at the specified time
419 * Returns false if the file does not exist. Repositories not supporting
420 * version control should return false if the time is specified.
422 * @param $sha1 String base 36 SHA-1 hash
423 * @param $options array Option array, same as findFile().
424 * @return File|bool False on failure
426 public function findFileFromKey( $sha1, $options = array() ) {
427 $time = isset( $options['time'] ) ?
$options['time'] : false;
428 # First try to find a matching current version of a file...
429 if ( $this->fileFactoryKey
) {
430 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
432 return false; // find-by-sha1 not supported
434 if ( $img && $img->exists() ) {
437 # Now try to find a matching old version of a file...
438 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
439 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
440 if ( $img && $img->exists() ) {
441 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
442 return $img; // always OK
443 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
452 * Get an array or iterator of file objects for files that have a given
453 * SHA-1 content hash.
459 public function findBySha1( $hash ) {
464 * Get an array of arrays or iterators of file objects for files that
465 * have the given SHA-1 content hashes.
467 * @param $hashes array An array of hashes
468 * @return array An Array of arrays or iterators of file objects and the hash as key
470 public function findBySha1s( array $hashes ) {
472 foreach ( $hashes as $hash ) {
473 $files = $this->findBySha1( $hash );
474 if ( count( $files ) ) {
475 $result[$hash] = $files;
482 * Get the public root URL of the repository
484 * @deprecated since 1.20
487 public function getRootUrl() {
488 return $this->getZoneUrl( 'public' );
492 * Get the URL of thumb.php
496 public function getThumbScriptUrl() {
497 return $this->thumbScriptUrl
;
501 * Returns true if the repository can transform files via a 404 handler
505 public function canTransformVia404() {
506 return $this->transformVia404
;
510 * Get the name of an image from its title object
512 * @param $title Title
515 public function getNameFromTitle( Title
$title ) {
517 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
518 $name = $title->getUserCaseDBKey();
519 if ( $this->initialCapital
) {
520 $name = $wgContLang->ucfirst( $name );
523 $name = $title->getDBkey();
529 * Get the public zone root storage directory of the repository
533 public function getRootDirectory() {
534 return $this->getZonePath( 'public' );
538 * Get a relative path including trailing slash, e.g. f/fa/
539 * If the repo is not hashed, returns an empty string
541 * @param $name string Name of file
544 public function getHashPath( $name ) {
545 return self
::getHashPathForLevel( $name, $this->hashLevels
);
549 * Get a relative path including trailing slash, e.g. f/fa/
550 * If the repo is not hashed, returns an empty string
552 * @param $suffix string Basename of file from FileRepo::storeTemp()
555 public function getTempHashPath( $suffix ) {
556 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
557 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
558 return self
::getHashPathForLevel( $name, $this->hashLevels
);
566 protected static function getHashPathForLevel( $name, $levels ) {
567 if ( $levels == 0 ) {
570 $hash = md5( $name );
572 for ( $i = 1; $i <= $levels; $i++
) {
573 $path .= substr( $hash, 0, $i ) . '/';
580 * Get the number of hash directory levels
584 public function getHashLevels() {
585 return $this->hashLevels
;
589 * Get the name of this repository, as specified by $info['name]' to the constructor
593 public function getName() {
598 * Make an url to this repo
600 * @param $query mixed Query string to append
601 * @param $entry string Entry point; defaults to index
602 * @return string|bool False on failure
604 public function makeUrl( $query = '', $entry = 'index' ) {
605 if ( isset( $this->scriptDirUrl
) ) {
606 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
607 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
613 * Get the URL of an image description page. May return false if it is
614 * unknown or not applicable. In general this should only be called by the
615 * File class, since it may return invalid results for certain kinds of
616 * repositories. Use File::getDescriptionUrl() in user code.
618 * In particular, it uses the article paths as specified to the repository
619 * constructor, whereas local repositories use the local Title functions.
621 * @param $name string
624 public function getDescriptionUrl( $name ) {
625 $encName = wfUrlencode( $name );
626 if ( !is_null( $this->descBaseUrl
) ) {
627 # "http://example.com/wiki/Image:"
628 return $this->descBaseUrl
. $encName;
630 if ( !is_null( $this->articleUrl
) ) {
631 # "http://example.com/wiki/$1"
633 # We use "Image:" as the canonical namespace for
634 # compatibility across all MediaWiki versions.
635 return str_replace( '$1',
636 "Image:$encName", $this->articleUrl
);
638 if ( !is_null( $this->scriptDirUrl
) ) {
639 # "http://example.com/w"
641 # We use "Image:" as the canonical namespace for
642 # compatibility across all MediaWiki versions,
643 # and just sort of hope index.php is right. ;)
644 return $this->makeUrl( "title=Image:$encName" );
650 * Get the URL of the content-only fragment of the description page. For
651 * MediaWiki this means action=render. This should only be called by the
652 * repository's file class, since it may return invalid results. User code
653 * should use File::getDescriptionText().
655 * @param $name String: name of image to fetch
656 * @param $lang String: language to fetch it in, if any.
659 public function getDescriptionRenderUrl( $name, $lang = null ) {
660 $query = 'action=render';
661 if ( !is_null( $lang ) ) {
662 $query .= '&uselang=' . $lang;
664 if ( isset( $this->scriptDirUrl
) ) {
665 return $this->makeUrl(
667 wfUrlencode( 'Image:' . $name ) .
670 $descUrl = $this->getDescriptionUrl( $name );
672 return wfAppendQuery( $descUrl, $query );
680 * Get the URL of the stylesheet to apply to description pages
682 * @return string|bool False on failure
684 public function getDescriptionStylesheetUrl() {
685 if ( isset( $this->scriptDirUrl
) ) {
686 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
687 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
693 * Store a file to a given destination.
695 * @param $srcPath String: source FS path, storage path, or virtual URL
696 * @param $dstZone String: destination zone
697 * @param $dstRel String: destination relative path
698 * @param $flags Integer: bitwise combination of the following flags:
699 * self::DELETE_SOURCE Delete the source file after upload
700 * self::OVERWRITE Overwrite an existing destination file instead of failing
701 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
702 * same contents as the source
703 * self::SKIP_LOCKING Skip any file locking when doing the store
704 * @return FileRepoStatus
706 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
707 $this->assertWritableRepo(); // fail out if read-only
709 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
710 if ( $status->successCount
== 0 ) {
718 * Store a batch of files
720 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
721 * @param $flags Integer: bitwise combination of the following flags:
722 * self::DELETE_SOURCE Delete the source file after upload
723 * self::OVERWRITE Overwrite an existing destination file instead of failing
724 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
725 * same contents as the source
726 * self::SKIP_LOCKING Skip any file locking when doing the store
727 * @throws MWException
728 * @return FileRepoStatus
730 public function storeBatch( array $triplets, $flags = 0 ) {
731 $this->assertWritableRepo(); // fail out if read-only
733 $status = $this->newGood();
734 $backend = $this->backend
; // convenience
736 $operations = array();
737 $sourceFSFilesToDelete = array(); // cleanup for disk source files
738 // Validate each triplet and get the store operation...
739 foreach ( $triplets as $triplet ) {
740 list( $srcPath, $dstZone, $dstRel ) = $triplet;
742 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
745 // Resolve destination path
746 $root = $this->getZonePath( $dstZone );
748 throw new MWException( "Invalid zone: $dstZone" );
750 if ( !$this->validateFilename( $dstRel ) ) {
751 throw new MWException( 'Validation error in $dstRel' );
753 $dstPath = "$root/$dstRel";
754 $dstDir = dirname( $dstPath );
755 // Create destination directories for this triplet
756 if ( !$this->initDirectory( $dstDir )->isOK() ) {
757 return $this->newFatal( 'directorycreateerror', $dstDir );
760 // Resolve source to a storage path if virtual
761 $srcPath = $this->resolveToStoragePath( $srcPath );
763 // Get the appropriate file operation
764 if ( FileBackend
::isStoragePath( $srcPath ) ) {
765 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
768 if ( $flags & self
::DELETE_SOURCE
) {
769 $sourceFSFilesToDelete[] = $srcPath;
772 $operations[] = array(
776 'overwrite' => $flags & self
::OVERWRITE
,
777 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
781 // Execute the store operation for each triplet
782 $opts = array( 'force' => true );
783 if ( $flags & self
::SKIP_LOCKING
) {
784 $opts['nonLocking'] = true;
786 $status->merge( $backend->doOperations( $operations, $opts ) );
787 // Cleanup for disk source files...
788 foreach ( $sourceFSFilesToDelete as $file ) {
789 wfSuppressWarnings();
790 unlink( $file ); // FS cleanup
798 * Deletes a batch of files.
799 * Each file can be a (zone, rel) pair, virtual url, storage path.
800 * It will try to delete each file, but ignores any errors that may occur.
802 * @param $files array List of files to delete
803 * @param $flags Integer: bitwise combination of the following flags:
804 * self::SKIP_LOCKING Skip any file locking when doing the deletions
805 * @return FileRepoStatus
807 public function cleanupBatch( array $files, $flags = 0 ) {
808 $this->assertWritableRepo(); // fail out if read-only
810 $status = $this->newGood();
812 $operations = array();
813 foreach ( $files as $path ) {
814 if ( is_array( $path ) ) {
815 // This is a pair, extract it
816 list( $zone, $rel ) = $path;
817 $path = $this->getZonePath( $zone ) . "/$rel";
819 // Resolve source to a storage path if virtual
820 $path = $this->resolveToStoragePath( $path );
822 $operations[] = array( 'op' => 'delete', 'src' => $path );
824 // Actually delete files from storage...
825 $opts = array( 'force' => true );
826 if ( $flags & self
::SKIP_LOCKING
) {
827 $opts['nonLocking'] = true;
829 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
835 * Import a file from the local file system into the repo.
836 * This does no locking nor journaling and overrides existing files.
837 * This function can be used to write to otherwise read-only foreign repos.
838 * This is intended for copying generated thumbnails into the repo.
840 * @param $src string File system path
841 * @param $dst string Virtual URL or storage path
842 * @return FileRepoStatus
844 final public function quickImport( $src, $dst ) {
845 return $this->quickImportBatch( array( array( $src, $dst ) ) );
849 * Purge a file from the repo. This does no locking nor journaling.
850 * This function can be used to write to otherwise read-only foreign repos.
851 * This is intended for purging thumbnails.
853 * @param $path string Virtual URL or storage path
854 * @return FileRepoStatus
856 final public function quickPurge( $path ) {
857 return $this->quickPurgeBatch( array( $path ) );
861 * Deletes a directory if empty.
862 * This function can be used to write to otherwise read-only foreign repos.
864 * @param $dir string Virtual URL (or storage path) of directory to clean
867 public function quickCleanDir( $dir ) {
868 $status = $this->newGood();
869 $status->merge( $this->backend
->clean(
870 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
876 * Import a batch of files from the local file system into the repo.
877 * This does no locking nor journaling and overrides existing files.
878 * This function can be used to write to otherwise read-only foreign repos.
879 * This is intended for copying generated thumbnails into the repo.
881 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
882 * @return FileRepoStatus
884 public function quickImportBatch( array $pairs ) {
885 $status = $this->newGood();
886 $operations = array();
887 foreach ( $pairs as $pair ) {
888 list ( $src, $dst ) = $pair;
889 $dst = $this->resolveToStoragePath( $dst );
890 $operations[] = array(
895 $status->merge( $this->initDirectory( dirname( $dst ) ) );
897 $status->merge( $this->backend
->doQuickOperations( $operations ) );
903 * Purge a batch of files from the repo.
904 * This function can be used to write to otherwise read-only foreign repos.
905 * This does no locking nor journaling and is intended for purging thumbnails.
907 * @param $paths Array List of virtual URLs or storage paths
908 * @return FileRepoStatus
910 public function quickPurgeBatch( array $paths ) {
911 $status = $this->newGood();
912 $operations = array();
913 foreach ( $paths as $path ) {
914 $operations[] = array(
916 'src' => $this->resolveToStoragePath( $path ),
917 'ignoreMissingSource' => true
920 $status->merge( $this->backend
->doQuickOperations( $operations ) );
926 * Pick a random name in the temp zone and store a file to it.
927 * Returns a FileRepoStatus object with the file Virtual URL in the value,
928 * file can later be disposed using FileRepo::freeTemp().
930 * @param $originalName String: the base name of the file as specified
931 * by the user. The file extension will be maintained.
932 * @param $srcPath String: the current location of the file.
933 * @return FileRepoStatus object with the URL in the value.
935 public function storeTemp( $originalName, $srcPath ) {
936 $this->assertWritableRepo(); // fail out if read-only
938 $date = gmdate( "YmdHis" );
939 $hashPath = $this->getHashPath( $originalName );
940 $dstRel = "{$hashPath}{$date}!{$originalName}";
941 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
943 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
944 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
950 * Concatenate a list of files into a target file location.
952 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
953 * @param $dstPath String Target file system path
954 * @param $flags Integer: bitwise combination of the following flags:
955 * self::DELETE_SOURCE Delete the source files
956 * @return FileRepoStatus
958 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
959 $this->assertWritableRepo(); // fail out if read-only
961 $status = $this->newGood();
964 $deleteOperations = array(); // post-concatenate ops
965 foreach ( $srcPaths as $srcPath ) {
966 // Resolve source to a storage path if virtual
967 $source = $this->resolveToStoragePath( $srcPath );
968 $sources[] = $source; // chunk to merge
969 if ( $flags & self
::DELETE_SOURCE
) {
970 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
974 // Concatenate the chunks into one FS file
975 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
976 $status->merge( $this->backend
->concatenate( $params ) );
977 if ( !$status->isOK() ) {
981 // Delete the sources if required
982 if ( $deleteOperations ) {
983 $opts = array( 'force' => true );
984 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
987 // Make sure status is OK, despite any $deleteOperations fatals
988 $status->setResult( true );
994 * Remove a temporary file or mark it for garbage collection
996 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
997 * @return Boolean: true on success, false on failure
999 public function freeTemp( $virtualUrl ) {
1000 $this->assertWritableRepo(); // fail out if read-only
1002 $temp = "mwrepo://{$this->name}/temp";
1003 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1004 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
1007 $path = $this->resolveVirtualUrl( $virtualUrl );
1009 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
1013 * Copy or move a file either from a storage path, virtual URL,
1014 * or FS path, into this repository at the specified destination location.
1016 * Returns a FileRepoStatus object. On success, the value contains "new" or
1017 * "archived", to indicate whether the file was new with that name.
1019 * @param $srcPath String: the source FS path, storage path, or URL
1020 * @param $dstRel String: the destination relative path
1021 * @param $archiveRel String: the relative path where the existing file is to
1022 * be archived, if there is one. Relative to the public zone root.
1023 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1024 * that the source file should be deleted if possible
1025 * @return FileRepoStatus
1027 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1028 $this->assertWritableRepo(); // fail out if read-only
1030 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1031 if ( $status->successCount
== 0 ) {
1032 $status->ok
= false;
1034 if ( isset( $status->value
[0] ) ) {
1035 $status->value
= $status->value
[0];
1037 $status->value
= false;
1044 * Publish a batch of files
1046 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1047 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1048 * that the source files should be deleted if possible
1049 * @throws MWException
1050 * @return FileRepoStatus
1052 public function publishBatch( array $triplets, $flags = 0 ) {
1053 $this->assertWritableRepo(); // fail out if read-only
1055 $backend = $this->backend
; // convenience
1056 // Try creating directories
1057 $status = $this->initZones( 'public' );
1058 if ( !$status->isOK() ) {
1062 $status = $this->newGood( array() );
1064 $operations = array();
1065 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1066 // Validate each triplet and get the store operation...
1067 foreach ( $triplets as $i => $triplet ) {
1068 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1069 // Resolve source to a storage path if virtual
1070 $srcPath = $this->resolveToStoragePath( $srcPath );
1071 if ( !$this->validateFilename( $dstRel ) ) {
1072 throw new MWException( 'Validation error in $dstRel' );
1074 if ( !$this->validateFilename( $archiveRel ) ) {
1075 throw new MWException( 'Validation error in $archiveRel' );
1078 $publicRoot = $this->getZonePath( 'public' );
1079 $dstPath = "$publicRoot/$dstRel";
1080 $archivePath = "$publicRoot/$archiveRel";
1082 $dstDir = dirname( $dstPath );
1083 $archiveDir = dirname( $archivePath );
1084 // Abort immediately on directory creation errors since they're likely to be repetitive
1085 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1086 return $this->newFatal( 'directorycreateerror', $dstDir );
1088 if ( !$this->initDirectory($archiveDir )->isOK() ) {
1089 return $this->newFatal( 'directorycreateerror', $archiveDir );
1092 // Archive destination file if it exists
1093 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1094 // Check if the archive file exists
1095 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1096 // unlinks the destination file if it exists. DB-based synchronisation in
1097 // publishBatch's caller should prevent races. In Windows there's no
1098 // problem because the rename primitive fails if the destination exists.
1099 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1100 $operations[] = array( 'op' => 'null' );
1103 $operations[] = array(
1106 'dst' => $archivePath
1109 $status->value
[$i] = 'archived';
1111 $status->value
[$i] = 'new';
1113 // Copy (or move) the source file to the destination
1114 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1115 if ( $flags & self
::DELETE_SOURCE
) {
1116 $operations[] = array(
1122 $operations[] = array(
1128 } else { // FS source path
1129 $operations[] = array(
1134 if ( $flags & self
::DELETE_SOURCE
) {
1135 $sourceFSFilesToDelete[] = $srcPath;
1140 // Execute the operations for each triplet
1141 $opts = array( 'force' => true );
1142 $status->merge( $backend->doOperations( $operations, $opts ) );
1143 // Cleanup for disk source files...
1144 foreach ( $sourceFSFilesToDelete as $file ) {
1145 wfSuppressWarnings();
1146 unlink( $file ); // FS cleanup
1147 wfRestoreWarnings();
1154 * Creates a directory with the appropriate zone permissions.
1155 * Callers are responsible for doing read-only and "writable repo" checks.
1157 * @param $dir string Virtual URL (or storage path) of directory to clean
1160 protected function initDirectory( $dir ) {
1161 $path = $this->resolveToStoragePath( $dir );
1162 list( $b, $container, $r ) = FileBackend
::splitStoragePath( $path );
1164 $params = array( 'dir' => $path );
1165 if ( $this->isPrivate ||
$container === $this->zones
['deleted']['container'] ) {
1166 # Take all available measures to prevent web accessibility of new deleted
1167 # directories, in case the user has not configured offline storage
1168 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1171 return $this->backend
->prepare( $params );
1175 * Deletes a directory if empty.
1177 * @param $dir string Virtual URL (or storage path) of directory to clean
1180 public function cleanDir( $dir ) {
1181 $this->assertWritableRepo(); // fail out if read-only
1183 $status = $this->newGood();
1184 $status->merge( $this->backend
->clean(
1185 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1191 * Checks existence of a a file
1193 * @param $file string Virtual URL (or storage path) of file to check
1196 public function fileExists( $file ) {
1197 $result = $this->fileExistsBatch( array( $file ) );
1202 * Checks existence of an array of files.
1204 * @param $files Array: Virtual URLs (or storage paths) of files to check
1205 * @return array|bool Either array of files and existence flags, or false
1207 public function fileExistsBatch( array $files ) {
1209 foreach ( $files as $key => $file ) {
1210 $file = $this->resolveToStoragePath( $file );
1211 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1217 * Move a file to the deletion archive.
1218 * If no valid deletion archive exists, this may either delete the file
1219 * or throw an exception, depending on the preference of the repository
1221 * @param $srcRel Mixed: relative path for the file to be deleted
1222 * @param $archiveRel Mixed: relative path for the archive location.
1223 * Relative to a private archive directory.
1224 * @return FileRepoStatus object
1226 public function delete( $srcRel, $archiveRel ) {
1227 $this->assertWritableRepo(); // fail out if read-only
1229 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1233 * Move a group of files to the deletion archive.
1235 * If no valid deletion archive is configured, this may either delete the
1236 * file or throw an exception, depending on the preference of the repository.
1238 * The overwrite policy is determined by the repository -- currently LocalRepo
1239 * assumes a naming scheme in the deleted zone based on content hash, as
1240 * opposed to the public zone which is assumed to be unique.
1242 * @param $sourceDestPairs Array of source/destination pairs. Each element
1243 * is a two-element array containing the source file path relative to the
1244 * public root in the first element, and the archive file path relative
1245 * to the deleted zone root in the second element.
1246 * @throws MWException
1247 * @return FileRepoStatus
1249 public function deleteBatch( array $sourceDestPairs ) {
1250 $this->assertWritableRepo(); // fail out if read-only
1252 // Try creating directories
1253 $status = $this->initZones( array( 'public', 'deleted' ) );
1254 if ( !$status->isOK() ) {
1258 $status = $this->newGood();
1260 $backend = $this->backend
; // convenience
1261 $operations = array();
1262 // Validate filenames and create archive directories
1263 foreach ( $sourceDestPairs as $pair ) {
1264 list( $srcRel, $archiveRel ) = $pair;
1265 if ( !$this->validateFilename( $srcRel ) ) {
1266 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1267 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1268 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1271 $publicRoot = $this->getZonePath( 'public' );
1272 $srcPath = "{$publicRoot}/$srcRel";
1274 $deletedRoot = $this->getZonePath( 'deleted' );
1275 $archivePath = "{$deletedRoot}/{$archiveRel}";
1276 $archiveDir = dirname( $archivePath ); // does not touch FS
1278 // Create destination directories
1279 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1280 return $this->newFatal( 'directorycreateerror', $archiveDir );
1283 $operations[] = array(
1286 'dst' => $archivePath,
1287 // We may have 2+ identical files being deleted,
1288 // all of which will map to the same destination file
1289 'overwriteSame' => true // also see bug 31792
1293 // Move the files by execute the operations for each pair.
1294 // We're now committed to returning an OK result, which will
1295 // lead to the files being moved in the DB also.
1296 $opts = array( 'force' => true );
1297 $status->merge( $backend->doOperations( $operations, $opts ) );
1303 * Delete files in the deleted directory if they are not referenced in the filearchive table
1307 public function cleanupDeletedBatch( array $storageKeys ) {
1308 $this->assertWritableRepo();
1312 * Get a relative path for a deletion archive key,
1313 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1315 * @param $key string
1318 public function getDeletedHashPath( $key ) {
1320 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1321 $path .= $key[$i] . '/';
1327 * If a path is a virtual URL, resolve it to a storage path.
1328 * Otherwise, just return the path as it is.
1330 * @param $path string
1332 * @throws MWException
1334 protected function resolveToStoragePath( $path ) {
1335 if ( $this->isVirtualUrl( $path ) ) {
1336 return $this->resolveVirtualUrl( $path );
1342 * Get a local FS copy of a file with a given virtual URL/storage path.
1343 * Temporary files may be purged when the file object falls out of scope.
1345 * @param $virtualUrl string
1346 * @return TempFSFile|null Returns null on failure
1348 public function getLocalCopy( $virtualUrl ) {
1349 $path = $this->resolveToStoragePath( $virtualUrl );
1350 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1354 * Get a local FS file with a given virtual URL/storage path.
1355 * The file is either an original or a copy. It should not be changed.
1356 * Temporary files may be purged when the file object falls out of scope.
1358 * @param $virtualUrl string
1359 * @return FSFile|null Returns null on failure.
1361 public function getLocalReference( $virtualUrl ) {
1362 $path = $this->resolveToStoragePath( $virtualUrl );
1363 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1367 * Get properties of a file with a given virtual URL/storage path.
1368 * Properties should ultimately be obtained via FSFile::getProps().
1370 * @param $virtualUrl string
1373 public function getFileProps( $virtualUrl ) {
1374 $path = $this->resolveToStoragePath( $virtualUrl );
1375 return $this->backend
->getFileProps( array( 'src' => $path ) );
1379 * Get the timestamp of a file with a given virtual URL/storage path
1381 * @param $virtualUrl string
1382 * @return string|bool False on failure
1384 public function getFileTimestamp( $virtualUrl ) {
1385 $path = $this->resolveToStoragePath( $virtualUrl );
1386 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1390 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1392 * @param $virtualUrl string
1393 * @return string|bool
1395 public function getFileSha1( $virtualUrl ) {
1396 $path = $this->resolveToStoragePath( $virtualUrl );
1397 return $this->backend
->getFileSha1Base36( array( 'src' => $path ) );
1401 * Attempt to stream a file with the given virtual URL/storage path
1403 * @param $virtualUrl string
1404 * @param $headers Array Additional HTTP headers to send on success
1405 * @return bool Success
1407 public function streamFile( $virtualUrl, $headers = array() ) {
1408 $path = $this->resolveToStoragePath( $virtualUrl );
1409 $params = array( 'src' => $path, 'headers' => $headers );
1410 return $this->backend
->streamFile( $params )->isOK();
1414 * Call a callback function for every public regular file in the repository.
1415 * This only acts on the current version of files, not any old versions.
1416 * May use either the database or the filesystem.
1418 * @param $callback Array|string
1421 public function enumFiles( $callback ) {
1422 $this->enumFilesInStorage( $callback );
1426 * Call a callback function for every public file in the repository.
1427 * May use either the database or the filesystem.
1429 * @param $callback Array|string
1432 protected function enumFilesInStorage( $callback ) {
1433 $publicRoot = $this->getZonePath( 'public' );
1434 $numDirs = 1 << ( $this->hashLevels
* 4 );
1435 // Use a priori assumptions about directory structure
1436 // to reduce the tree height of the scanning process.
1437 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1438 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1439 $path = $publicRoot;
1440 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1441 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1443 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1444 foreach ( $iterator as $name ) {
1445 // Each item returned is a public file
1446 call_user_func( $callback, "{$path}/{$name}" );
1452 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1454 * @param $filename string
1457 public function validateFilename( $filename ) {
1458 if ( strval( $filename ) == '' ) {
1461 return FileBackend
::isPathTraversalFree( $filename );
1465 * Get a callback function to use for cleaning error message parameters
1469 function getErrorCleanupFunction() {
1470 switch ( $this->pathDisclosureProtection
) {
1472 case 'simple': // b/c
1473 $callback = array( $this, 'passThrough' );
1475 default: // 'paranoid'
1476 $callback = array( $this, 'paranoidClean' );
1482 * Path disclosure protection function
1484 * @param $param string
1487 function paranoidClean( $param ) {
1492 * Path disclosure protection function
1494 * @param $param string
1497 function passThrough( $param ) {
1502 * Create a new fatal error
1504 * @return FileRepoStatus
1506 public function newFatal( $message /*, parameters...*/ ) {
1507 $params = func_get_args();
1508 array_unshift( $params, $this );
1509 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1513 * Create a new good result
1515 * @param $value null|string
1516 * @return FileRepoStatus
1518 public function newGood( $value = null ) {
1519 return FileRepoStatus
::newGood( $this, $value );
1523 * Checks if there is a redirect named as $title. If there is, return the
1524 * title object. If not, return false.
1527 * @param $title Title of image
1530 public function checkRedirect( Title
$title ) {
1535 * Invalidates image redirect cache related to that image
1536 * Doesn't do anything for repositories that don't support image redirects.
1539 * @param $title Title of image
1541 public function invalidateImageRedirect( Title
$title ) {}
1544 * Get the human-readable name of the repo
1548 public function getDisplayName() {
1549 // We don't name our own repo, return nothing
1550 if ( $this->isLocal() ) {
1553 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1554 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1558 * Returns true if this the local file repository.
1562 public function isLocal() {
1563 return $this->getName() == 'local';
1567 * Get a key on the primary cache for this repository.
1568 * Returns false if the repository's cache is not accessible at this site.
1569 * The parameters are the parts of the key, as for wfMemcKey().
1574 public function getSharedCacheKey( /*...*/ ) {
1579 * Get a key for this repo in the local cache domain. These cache keys are
1580 * not shared with remote instances of the repo.
1581 * The parameters are the parts of the key, as for wfMemcKey().
1585 public function getLocalCacheKey( /*...*/ ) {
1586 $args = func_get_args();
1587 array_unshift( $args, 'filerepo', $this->getName() );
1588 return call_user_func_array( 'wfMemcKey', $args );
1592 * Get an temporary FileRepo associated with this repo.
1593 * Files will be created in the temp zone of this repo and
1594 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1595 * It will have the same backend as this repo.
1597 * @return TempFileRepo
1599 public function getTempRepo() {
1600 return new TempFileRepo( array(
1601 'name' => "{$this->name}-temp",
1602 'backend' => $this->backend
,
1605 'container' => $this->zones
['temp']['container'],
1606 'directory' => $this->zones
['temp']['directory']
1609 'container' => $this->zones
['thumb']['container'],
1610 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1612 : $this->zones
['thumb']['directory'] . '/temp'
1615 'url' => $this->getZoneUrl( 'temp' ),
1616 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1617 'hashLevels' => $this->hashLevels
// performance
1622 * Get an UploadStash associated with this repo.
1624 * @return UploadStash
1626 public function getUploadStash() {
1627 return new UploadStash( $this );
1631 * Throw an exception if this repo is read-only by design.
1632 * This does not and should not check getReadOnlyReason().
1635 * @throws MWException
1637 protected function assertWritableRepo() {}
1641 * FileRepo for temporary files created via FileRepo::getTempRepo()
1643 class TempFileRepo
extends FileRepo
{
1644 public function getTempRepo() {
1645 throw new MWException( "Cannot get a temp repo from a temp repo." );