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 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->zones
= isset( $info['zones'] )
119 // Give defaults for the basic zones...
120 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
121 if ( !isset( $this->zones
[$zone] ) ) {
122 $this->zones
[$zone] = array(
123 'container' => "{$this->name}-{$zone}",
124 'directory' => '' // container root
131 * Get the file backend instance. Use this function wisely.
133 * @return FileBackend
135 public function getBackend() {
136 return $this->backend
;
140 * Get an explanatory message if this repo is read-only.
141 * This checks if an administrator disabled writes to the backend.
143 * @return string|bool Returns false if the repo is not read-only
145 public function getReadOnlyReason() {
146 return $this->backend
->getReadOnlyReason();
150 * Check if a single zone or list of zones is defined for usage
152 * @param $doZones Array Only do a particular zones
153 * @throws MWException
156 protected function initZones( $doZones = array() ) {
157 $status = $this->newGood();
158 foreach ( (array)$doZones as $zone ) {
159 $root = $this->getZonePath( $zone );
160 if ( $root === null ) {
161 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
168 * Take all available measures to prevent web accessibility of new deleted
169 * directories, in case the user has not configured offline storage
174 protected function initDeletedDir( $dir ) {
175 $this->backend
->secure( // prevent web access & dir listings
176 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
180 * Determine if a string is an mwrepo:// URL
185 public static function isVirtualUrl( $url ) {
186 return substr( $url, 0, 9 ) == 'mwrepo://';
190 * Get a URL referring to this repository, with the private mwrepo protocol.
191 * The suffix, if supplied, is considered to be unencoded, and will be
192 * URL-encoded before being returned.
194 * @param $suffix string|bool
197 public function getVirtualUrl( $suffix = false ) {
198 $path = 'mwrepo://' . $this->name
;
199 if ( $suffix !== false ) {
200 $path .= '/' . rawurlencode( $suffix );
206 * Get the URL corresponding to one of the four basic zones
208 * @param $zone String: one of: public, deleted, temp, thumb
209 * @return String or false
211 public function getZoneUrl( $zone ) {
216 return "{$this->url}/temp";
218 return false; // no public URL
220 return $this->thumbUrl
;
227 * Get the backend storage path corresponding to a virtual URL.
228 * Use this function wisely.
231 * @throws MWException
234 public function resolveVirtualUrl( $url ) {
235 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
236 throw new MWException( __METHOD__
.': unknown protocol' );
238 $bits = explode( '/', substr( $url, 9 ), 3 );
239 if ( count( $bits ) != 3 ) {
240 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
242 list( $repo, $zone, $rel ) = $bits;
243 if ( $repo !== $this->name
) {
244 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
246 $base = $this->getZonePath( $zone );
248 throw new MWException( __METHOD__
.": invalid zone: $zone" );
250 return $base . '/' . rawurldecode( $rel );
254 * The the storage container and base path of a zone
256 * @param $zone string
257 * @return Array (container, base path) or (null, null)
259 protected function getZoneLocation( $zone ) {
260 if ( !isset( $this->zones
[$zone] ) ) {
261 return array( null, null ); // bogus
263 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
267 * Get the storage path corresponding to one of the zones
269 * @param $zone string
270 * @return string|null Returns null if the zone is not defined
272 public function getZonePath( $zone ) {
273 list( $container, $base ) = $this->getZoneLocation( $zone );
274 if ( $container === null ||
$base === null ) {
277 $backendName = $this->backend
->getName();
278 if ( $base != '' ) { // may not be set
281 return "mwstore://$backendName/{$container}{$base}";
285 * Create a new File object from the local repository
287 * @param $title Mixed: Title object or string
288 * @param $time Mixed: Time at which the image was uploaded.
289 * If this is specified, the returned object will be an
290 * instance of the repository's old file class instead of a
291 * current file. Repositories not supporting version control
292 * should return false if this parameter is set.
293 * @return File|null A File, or null if passed an invalid Title
295 public function newFile( $title, $time = false ) {
296 $title = File
::normalizeTitle( $title );
301 if ( $this->oldFileFactory
) {
302 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
307 return call_user_func( $this->fileFactory
, $title, $this );
312 * Find an instance of the named file created at the specified time
313 * Returns false if the file does not exist. Repositories not supporting
314 * version control should return false if the time is specified.
316 * @param $title Mixed: Title object or string
317 * @param $options array Associative array of options:
318 * time: requested time for a specific file version, or false for the
319 * current version. An image object will be returned which was
320 * created at the specified time (which may be archived or current).
322 * ignoreRedirect: If true, do not follow file redirects
324 * private: If true, return restricted (deleted) files if the current
325 * user is allowed to view them. Otherwise, such files will not
327 * @return File|bool False on failure
329 public function findFile( $title, $options = array() ) {
330 $title = File
::normalizeTitle( $title );
334 $time = isset( $options['time'] ) ?
$options['time'] : false;
335 # First try the current version of the file to see if it precedes the timestamp
336 $img = $this->newFile( $title );
340 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
343 # Now try an old version of the file
344 if ( $time !== false ) {
345 $img = $this->newFile( $title, $time );
346 if ( $img && $img->exists() ) {
347 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
348 return $img; // always OK
349 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
356 if ( !empty( $options['ignoreRedirect'] ) ) {
359 $redir = $this->checkRedirect( $title );
360 if ( $redir && $title->getNamespace() == NS_FILE
) {
361 $img = $this->newFile( $redir );
365 if ( $img->exists() ) {
366 $img->redirectedFrom( $title->getDBkey() );
374 * Find many files at once.
376 * @param $items array An array of titles, or an array of findFile() options with
377 * the "title" option giving the title. Example:
379 * $findItem = array( 'title' => $title, 'private' => true );
380 * $findBatch = array( $findItem );
381 * $repo->findFiles( $findBatch );
384 public function findFiles( array $items ) {
386 foreach ( $items as $item ) {
387 if ( is_array( $item ) ) {
388 $title = $item['title'];
390 unset( $options['title'] );
395 $file = $this->findFile( $title, $options );
397 $result[$file->getTitle()->getDBkey()] = $file;
404 * Find an instance of the file with this key, created at the specified time
405 * Returns false if the file does not exist. Repositories not supporting
406 * version control should return false if the time is specified.
408 * @param $sha1 String base 36 SHA-1 hash
409 * @param $options array Option array, same as findFile().
410 * @return File|bool False on failure
412 public function findFileFromKey( $sha1, $options = array() ) {
413 $time = isset( $options['time'] ) ?
$options['time'] : false;
414 # First try to find a matching current version of a file...
415 if ( $this->fileFactoryKey
) {
416 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
418 return false; // find-by-sha1 not supported
420 if ( $img && $img->exists() ) {
423 # Now try to find a matching old version of a file...
424 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
425 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
426 if ( $img && $img->exists() ) {
427 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
428 return $img; // always OK
429 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
438 * Get an array or iterator of file objects for files that have a given
439 * SHA-1 content hash.
445 public function findBySha1( $hash ) {
450 * Get the public root URL of the repository
454 public function getRootUrl() {
459 * Get the URL of thumb.php
463 public function getThumbScriptUrl() {
464 return $this->thumbScriptUrl
;
468 * Returns true if the repository can transform files via a 404 handler
472 public function canTransformVia404() {
473 return $this->transformVia404
;
477 * Get the name of an image from its title object
479 * @param $title Title
482 public function getNameFromTitle( Title
$title ) {
484 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
485 $name = $title->getUserCaseDBKey();
486 if ( $this->initialCapital
) {
487 $name = $wgContLang->ucfirst( $name );
490 $name = $title->getDBkey();
496 * Get the public zone root storage directory of the repository
500 public function getRootDirectory() {
501 return $this->getZonePath( 'public' );
505 * Get a relative path including trailing slash, e.g. f/fa/
506 * If the repo is not hashed, returns an empty string
508 * @param $name string Name of file
511 public function getHashPath( $name ) {
512 return self
::getHashPathForLevel( $name, $this->hashLevels
);
516 * Get a relative path including trailing slash, e.g. f/fa/
517 * If the repo is not hashed, returns an empty string
519 * @param $suffix string Basename of file from FileRepo::storeTemp()
522 public function getTempHashPath( $suffix ) {
523 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
524 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
525 return self
::getHashPathForLevel( $name, $this->hashLevels
);
533 protected static function getHashPathForLevel( $name, $levels ) {
534 if ( $levels == 0 ) {
537 $hash = md5( $name );
539 for ( $i = 1; $i <= $levels; $i++
) {
540 $path .= substr( $hash, 0, $i ) . '/';
547 * Get the number of hash directory levels
551 public function getHashLevels() {
552 return $this->hashLevels
;
556 * Get the name of this repository, as specified by $info['name]' to the constructor
560 public function getName() {
565 * Make an url to this repo
567 * @param $query mixed Query string to append
568 * @param $entry string Entry point; defaults to index
569 * @return string|bool False on failure
571 public function makeUrl( $query = '', $entry = 'index' ) {
572 if ( isset( $this->scriptDirUrl
) ) {
573 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
574 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
580 * Get the URL of an image description page. May return false if it is
581 * unknown or not applicable. In general this should only be called by the
582 * File class, since it may return invalid results for certain kinds of
583 * repositories. Use File::getDescriptionUrl() in user code.
585 * In particular, it uses the article paths as specified to the repository
586 * constructor, whereas local repositories use the local Title functions.
588 * @param $name string
591 public function getDescriptionUrl( $name ) {
592 $encName = wfUrlencode( $name );
593 if ( !is_null( $this->descBaseUrl
) ) {
594 # "http://example.com/wiki/Image:"
595 return $this->descBaseUrl
. $encName;
597 if ( !is_null( $this->articleUrl
) ) {
598 # "http://example.com/wiki/$1"
600 # We use "Image:" as the canonical namespace for
601 # compatibility across all MediaWiki versions.
602 return str_replace( '$1',
603 "Image:$encName", $this->articleUrl
);
605 if ( !is_null( $this->scriptDirUrl
) ) {
606 # "http://example.com/w"
608 # We use "Image:" as the canonical namespace for
609 # compatibility across all MediaWiki versions,
610 # and just sort of hope index.php is right. ;)
611 return $this->makeUrl( "title=Image:$encName" );
617 * Get the URL of the content-only fragment of the description page. For
618 * MediaWiki this means action=render. This should only be called by the
619 * repository's file class, since it may return invalid results. User code
620 * should use File::getDescriptionText().
622 * @param $name String: name of image to fetch
623 * @param $lang String: language to fetch it in, if any.
626 public function getDescriptionRenderUrl( $name, $lang = null ) {
627 $query = 'action=render';
628 if ( !is_null( $lang ) ) {
629 $query .= '&uselang=' . $lang;
631 if ( isset( $this->scriptDirUrl
) ) {
632 return $this->makeUrl(
634 wfUrlencode( 'Image:' . $name ) .
637 $descUrl = $this->getDescriptionUrl( $name );
639 return wfAppendQuery( $descUrl, $query );
647 * Get the URL of the stylesheet to apply to description pages
649 * @return string|bool False on failure
651 public function getDescriptionStylesheetUrl() {
652 if ( isset( $this->scriptDirUrl
) ) {
653 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
654 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
660 * Store a file to a given destination.
662 * @param $srcPath String: source FS path, storage path, or virtual URL
663 * @param $dstZone String: destination zone
664 * @param $dstRel String: destination relative path
665 * @param $flags Integer: bitwise combination of the following flags:
666 * self::DELETE_SOURCE Delete the source file after upload
667 * self::OVERWRITE Overwrite an existing destination file instead of failing
668 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
669 * same contents as the source
670 * self::SKIP_LOCKING Skip any file locking when doing the store
671 * @return FileRepoStatus
673 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
674 $this->assertWritableRepo(); // fail out if read-only
676 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
677 if ( $status->successCount
== 0 ) {
685 * Store a batch of files
687 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
688 * @param $flags Integer: bitwise combination of the following flags:
689 * self::DELETE_SOURCE Delete the source file after upload
690 * self::OVERWRITE Overwrite an existing destination file instead of failing
691 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
692 * same contents as the source
693 * self::SKIP_LOCKING Skip any file locking when doing the store
694 * @throws MWException
695 * @return FileRepoStatus
697 public function storeBatch( array $triplets, $flags = 0 ) {
698 $this->assertWritableRepo(); // fail out if read-only
700 $status = $this->newGood();
701 $backend = $this->backend
; // convenience
703 $operations = array();
704 $sourceFSFilesToDelete = array(); // cleanup for disk source files
705 // Validate each triplet and get the store operation...
706 foreach ( $triplets as $triplet ) {
707 list( $srcPath, $dstZone, $dstRel ) = $triplet;
709 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
712 // Resolve destination path
713 $root = $this->getZonePath( $dstZone );
715 throw new MWException( "Invalid zone: $dstZone" );
717 if ( !$this->validateFilename( $dstRel ) ) {
718 throw new MWException( 'Validation error in $dstRel' );
720 $dstPath = "$root/$dstRel";
721 $dstDir = dirname( $dstPath );
722 // Create destination directories for this triplet
723 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
724 return $this->newFatal( 'directorycreateerror', $dstDir );
727 if ( $dstZone == 'deleted' ) {
728 $this->initDeletedDir( $dstDir );
731 // Resolve source to a storage path if virtual
732 $srcPath = $this->resolveToStoragePath( $srcPath );
734 // Get the appropriate file operation
735 if ( FileBackend
::isStoragePath( $srcPath ) ) {
736 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
739 if ( $flags & self
::DELETE_SOURCE
) {
740 $sourceFSFilesToDelete[] = $srcPath;
743 $operations[] = array(
747 'overwrite' => $flags & self
::OVERWRITE
,
748 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
752 // Execute the store operation for each triplet
753 $opts = array( 'force' => true );
754 if ( $flags & self
::SKIP_LOCKING
) {
755 $opts['nonLocking'] = true;
757 $status->merge( $backend->doOperations( $operations, $opts ) );
758 // Cleanup for disk source files...
759 foreach ( $sourceFSFilesToDelete as $file ) {
760 wfSuppressWarnings();
761 unlink( $file ); // FS cleanup
769 * Deletes a batch of files.
770 * Each file can be a (zone, rel) pair, virtual url, storage path.
771 * It will try to delete each file, but ignores any errors that may occur.
773 * @param $files array List of files to delete
774 * @param $flags Integer: bitwise combination of the following flags:
775 * self::SKIP_LOCKING Skip any file locking when doing the deletions
776 * @return FileRepoStatus
778 public function cleanupBatch( array $files, $flags = 0 ) {
779 $this->assertWritableRepo(); // fail out if read-only
781 $status = $this->newGood();
783 $operations = array();
784 foreach ( $files as $path ) {
785 if ( is_array( $path ) ) {
786 // This is a pair, extract it
787 list( $zone, $rel ) = $path;
788 $path = $this->getZonePath( $zone ) . "/$rel";
790 // Resolve source to a storage path if virtual
791 $path = $this->resolveToStoragePath( $path );
793 $operations[] = array( 'op' => 'delete', 'src' => $path );
795 // Actually delete files from storage...
796 $opts = array( 'force' => true );
797 if ( $flags & self
::SKIP_LOCKING
) {
798 $opts['nonLocking'] = true;
800 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
806 * Import a file from the local file system into the repo.
807 * This does no locking nor journaling and overrides existing files.
808 * This function can be used to write to otherwise read-only foreign repos.
809 * This is intended for copying generated thumbnails into the repo.
811 * @param $src string File system path
812 * @param $dst string Virtual URL or storage path
813 * @return FileRepoStatus
815 final public function quickImport( $src, $dst ) {
816 return $this->quickImportBatch( array( array( $src, $dst ) ) );
820 * Purge a file from the repo. This does no locking nor journaling.
821 * This function can be used to write to otherwise read-only foreign repos.
822 * This is intended for purging thumbnails.
824 * @param $path string Virtual URL or storage path
825 * @return FileRepoStatus
827 final public function quickPurge( $path ) {
828 return $this->quickPurgeBatch( array( $path ) );
832 * Deletes a directory if empty.
833 * This function can be used to write to otherwise read-only foreign repos.
835 * @param $dir string Virtual URL (or storage path) of directory to clean
838 public function quickCleanDir( $dir ) {
839 $status = $this->newGood();
840 $status->merge( $this->backend
->clean(
841 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
847 * Import a batch of files 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 $pairs Array List of tuples (file system path, virtual URL or storage path)
853 * @return FileRepoStatus
855 public function quickImportBatch( array $pairs ) {
856 $status = $this->newGood();
857 $operations = array();
858 foreach ( $pairs as $pair ) {
859 list ( $src, $dst ) = $pair;
860 $operations[] = array(
863 'dst' => $this->resolveToStoragePath( $dst )
865 $this->backend
->prepare( array( 'dir' => dirname( $dst ) ) );
867 $status->merge( $this->backend
->doQuickOperations( $operations ) );
873 * Purge a batch of files from the repo.
874 * This function can be used to write to otherwise read-only foreign repos.
875 * This does no locking nor journaling and is intended for purging thumbnails.
877 * @param $paths Array List of virtual URLs or storage paths
878 * @return FileRepoStatus
880 public function quickPurgeBatch( array $paths ) {
881 $status = $this->newGood();
882 $operations = array();
883 foreach ( $paths as $path ) {
884 $operations[] = array(
886 'src' => $this->resolveToStoragePath( $path ),
887 'ignoreMissingSource' => true
890 $status->merge( $this->backend
->doQuickOperations( $operations ) );
896 * Pick a random name in the temp zone and store a file to it.
897 * Returns a FileRepoStatus object with the file Virtual URL in the value,
898 * file can later be disposed using FileRepo::freeTemp().
900 * @param $originalName String: the base name of the file as specified
901 * by the user. The file extension will be maintained.
902 * @param $srcPath String: the current location of the file.
903 * @return FileRepoStatus object with the URL in the value.
905 public function storeTemp( $originalName, $srcPath ) {
906 $this->assertWritableRepo(); // fail out if read-only
908 $date = gmdate( "YmdHis" );
909 $hashPath = $this->getHashPath( $originalName );
910 $dstRel = "{$hashPath}{$date}!{$originalName}";
911 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
913 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
914 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
920 * Concatenate a list of files into a target file location.
922 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
923 * @param $dstPath String Target file system path
924 * @param $flags Integer: bitwise combination of the following flags:
925 * self::DELETE_SOURCE Delete the source files
926 * @return FileRepoStatus
928 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
929 $this->assertWritableRepo(); // fail out if read-only
931 $status = $this->newGood();
934 $deleteOperations = array(); // post-concatenate ops
935 foreach ( $srcPaths as $srcPath ) {
936 // Resolve source to a storage path if virtual
937 $source = $this->resolveToStoragePath( $srcPath );
938 $sources[] = $source; // chunk to merge
939 if ( $flags & self
::DELETE_SOURCE
) {
940 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
944 // Concatenate the chunks into one FS file
945 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
946 $status->merge( $this->backend
->concatenate( $params ) );
947 if ( !$status->isOK() ) {
951 // Delete the sources if required
952 if ( $deleteOperations ) {
953 $opts = array( 'force' => true );
954 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
957 // Make sure status is OK, despite any $deleteOperations fatals
958 $status->setResult( true );
964 * Remove a temporary file or mark it for garbage collection
966 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
967 * @return Boolean: true on success, false on failure
969 public function freeTemp( $virtualUrl ) {
970 $this->assertWritableRepo(); // fail out if read-only
972 $temp = "mwrepo://{$this->name}/temp";
973 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
974 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
977 $path = $this->resolveVirtualUrl( $virtualUrl );
979 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
983 * Copy or move a file either from a storage path, virtual URL,
984 * or FS path, into this repository at the specified destination location.
986 * Returns a FileRepoStatus object. On success, the value contains "new" or
987 * "archived", to indicate whether the file was new with that name.
989 * @param $srcPath String: the source FS path, storage path, or URL
990 * @param $dstRel String: the destination relative path
991 * @param $archiveRel String: the relative path where the existing file is to
992 * be archived, if there is one. Relative to the public zone root.
993 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
994 * that the source file should be deleted if possible
995 * @return FileRepoStatus
997 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
998 $this->assertWritableRepo(); // fail out if read-only
1000 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1001 if ( $status->successCount
== 0 ) {
1002 $status->ok
= false;
1004 if ( isset( $status->value
[0] ) ) {
1005 $status->value
= $status->value
[0];
1007 $status->value
= false;
1014 * Publish a batch of files
1016 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1017 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1018 * that the source files should be deleted if possible
1019 * @throws MWException
1020 * @return FileRepoStatus
1022 public function publishBatch( array $triplets, $flags = 0 ) {
1023 $this->assertWritableRepo(); // fail out if read-only
1025 $backend = $this->backend
; // convenience
1026 // Try creating directories
1027 $status = $this->initZones( 'public' );
1028 if ( !$status->isOK() ) {
1032 $status = $this->newGood( array() );
1034 $operations = array();
1035 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1036 // Validate each triplet and get the store operation...
1037 foreach ( $triplets as $i => $triplet ) {
1038 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1039 // Resolve source to a storage path if virtual
1040 $srcPath = $this->resolveToStoragePath( $srcPath );
1041 if ( !$this->validateFilename( $dstRel ) ) {
1042 throw new MWException( 'Validation error in $dstRel' );
1044 if ( !$this->validateFilename( $archiveRel ) ) {
1045 throw new MWException( 'Validation error in $archiveRel' );
1048 $publicRoot = $this->getZonePath( 'public' );
1049 $dstPath = "$publicRoot/$dstRel";
1050 $archivePath = "$publicRoot/$archiveRel";
1052 $dstDir = dirname( $dstPath );
1053 $archiveDir = dirname( $archivePath );
1054 // Abort immediately on directory creation errors since they're likely to be repetitive
1055 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1056 return $this->newFatal( 'directorycreateerror', $dstDir );
1058 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1059 return $this->newFatal( 'directorycreateerror', $archiveDir );
1062 // Archive destination file if it exists
1063 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1064 // Check if the archive file exists
1065 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1066 // unlinks the destination file if it exists. DB-based synchronisation in
1067 // publishBatch's caller should prevent races. In Windows there's no
1068 // problem because the rename primitive fails if the destination exists.
1069 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1070 $operations[] = array( 'op' => 'null' );
1073 $operations[] = array(
1076 'dst' => $archivePath
1079 $status->value
[$i] = 'archived';
1081 $status->value
[$i] = 'new';
1083 // Copy (or move) the source file to the destination
1084 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1085 if ( $flags & self
::DELETE_SOURCE
) {
1086 $operations[] = array(
1092 $operations[] = array(
1098 } else { // FS source path
1099 $operations[] = array(
1104 if ( $flags & self
::DELETE_SOURCE
) {
1105 $sourceFSFilesToDelete[] = $srcPath;
1110 // Execute the operations for each triplet
1111 $opts = array( 'force' => true );
1112 $status->merge( $backend->doOperations( $operations, $opts ) );
1113 // Cleanup for disk source files...
1114 foreach ( $sourceFSFilesToDelete as $file ) {
1115 wfSuppressWarnings();
1116 unlink( $file ); // FS cleanup
1117 wfRestoreWarnings();
1124 * Deletes a directory if empty.
1126 * @param $dir string Virtual URL (or storage path) of directory to clean
1129 public function cleanDir( $dir ) {
1130 $this->assertWritableRepo(); // fail out if read-only
1132 $status = $this->newGood();
1133 $status->merge( $this->backend
->clean(
1134 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1140 * Checks existence of a a file
1142 * @param $file string Virtual URL (or storage path) of file to check
1145 public function fileExists( $file ) {
1146 $result = $this->fileExistsBatch( array( $file ) );
1151 * Checks existence of an array of files.
1153 * @param $files Array: Virtual URLs (or storage paths) of files to check
1154 * @return array|bool Either array of files and existence flags, or false
1156 public function fileExistsBatch( array $files ) {
1158 foreach ( $files as $key => $file ) {
1159 $file = $this->resolveToStoragePath( $file );
1160 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1166 * Move a file to the deletion archive.
1167 * If no valid deletion archive exists, this may either delete the file
1168 * or throw an exception, depending on the preference of the repository
1170 * @param $srcRel Mixed: relative path for the file to be deleted
1171 * @param $archiveRel Mixed: relative path for the archive location.
1172 * Relative to a private archive directory.
1173 * @return FileRepoStatus object
1175 public function delete( $srcRel, $archiveRel ) {
1176 $this->assertWritableRepo(); // fail out if read-only
1178 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1182 * Move a group of files to the deletion archive.
1184 * If no valid deletion archive is configured, this may either delete the
1185 * file or throw an exception, depending on the preference of the repository.
1187 * The overwrite policy is determined by the repository -- currently LocalRepo
1188 * assumes a naming scheme in the deleted zone based on content hash, as
1189 * opposed to the public zone which is assumed to be unique.
1191 * @param $sourceDestPairs Array of source/destination pairs. Each element
1192 * is a two-element array containing the source file path relative to the
1193 * public root in the first element, and the archive file path relative
1194 * to the deleted zone root in the second element.
1195 * @throws MWException
1196 * @return FileRepoStatus
1198 public function deleteBatch( array $sourceDestPairs ) {
1199 $this->assertWritableRepo(); // fail out if read-only
1201 // Try creating directories
1202 $status = $this->initZones( array( 'public', 'deleted' ) );
1203 if ( !$status->isOK() ) {
1207 $status = $this->newGood();
1209 $backend = $this->backend
; // convenience
1210 $operations = array();
1211 // Validate filenames and create archive directories
1212 foreach ( $sourceDestPairs as $pair ) {
1213 list( $srcRel, $archiveRel ) = $pair;
1214 if ( !$this->validateFilename( $srcRel ) ) {
1215 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1216 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1217 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1220 $publicRoot = $this->getZonePath( 'public' );
1221 $srcPath = "{$publicRoot}/$srcRel";
1223 $deletedRoot = $this->getZonePath( 'deleted' );
1224 $archivePath = "{$deletedRoot}/{$archiveRel}";
1225 $archiveDir = dirname( $archivePath ); // does not touch FS
1227 // Create destination directories
1228 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1229 return $this->newFatal( 'directorycreateerror', $archiveDir );
1231 $this->initDeletedDir( $archiveDir );
1233 $operations[] = array(
1236 'dst' => $archivePath,
1237 // We may have 2+ identical files being deleted,
1238 // all of which will map to the same destination file
1239 'overwriteSame' => true // also see bug 31792
1243 // Move the files by execute the operations for each pair.
1244 // We're now committed to returning an OK result, which will
1245 // lead to the files being moved in the DB also.
1246 $opts = array( 'force' => true );
1247 $status->merge( $backend->doOperations( $operations, $opts ) );
1253 * Delete files in the deleted directory if they are not referenced in the filearchive table
1257 public function cleanupDeletedBatch( array $storageKeys ) {
1258 $this->assertWritableRepo();
1262 * Get a relative path for a deletion archive key,
1263 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1265 * @param $key string
1268 public function getDeletedHashPath( $key ) {
1270 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1271 $path .= $key[$i] . '/';
1277 * If a path is a virtual URL, resolve it to a storage path.
1278 * Otherwise, just return the path as it is.
1280 * @param $path string
1282 * @throws MWException
1284 protected function resolveToStoragePath( $path ) {
1285 if ( $this->isVirtualUrl( $path ) ) {
1286 return $this->resolveVirtualUrl( $path );
1292 * Get a local FS copy of a file with a given virtual URL/storage path.
1293 * Temporary files may be purged when the file object falls out of scope.
1295 * @param $virtualUrl string
1296 * @return TempFSFile|null Returns null on failure
1298 public function getLocalCopy( $virtualUrl ) {
1299 $path = $this->resolveToStoragePath( $virtualUrl );
1300 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1304 * Get a local FS file with a given virtual URL/storage path.
1305 * The file is either an original or a copy. It should not be changed.
1306 * Temporary files may be purged when the file object falls out of scope.
1308 * @param $virtualUrl string
1309 * @return FSFile|null Returns null on failure.
1311 public function getLocalReference( $virtualUrl ) {
1312 $path = $this->resolveToStoragePath( $virtualUrl );
1313 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1317 * Get properties of a file with a given virtual URL/storage path.
1318 * Properties should ultimately be obtained via FSFile::getProps().
1320 * @param $virtualUrl string
1323 public function getFileProps( $virtualUrl ) {
1324 $path = $this->resolveToStoragePath( $virtualUrl );
1325 return $this->backend
->getFileProps( array( 'src' => $path ) );
1329 * Get the timestamp of a file with a given virtual URL/storage path
1331 * @param $virtualUrl string
1332 * @return string|bool False on failure
1334 public function getFileTimestamp( $virtualUrl ) {
1335 $path = $this->resolveToStoragePath( $virtualUrl );
1336 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1340 * Get the sha1 of a file with a given virtual URL/storage path
1342 * @param $virtualUrl string
1343 * @return string|bool
1345 public function getFileSha1( $virtualUrl ) {
1346 $path = $this->resolveToStoragePath( $virtualUrl );
1347 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1351 return $tmpFile->getSha1Base36();
1355 * Attempt to stream a file with the given virtual URL/storage path
1357 * @param $virtualUrl string
1358 * @param $headers Array Additional HTTP headers to send on success
1359 * @return bool Success
1361 public function streamFile( $virtualUrl, $headers = array() ) {
1362 $path = $this->resolveToStoragePath( $virtualUrl );
1363 $params = array( 'src' => $path, 'headers' => $headers );
1364 return $this->backend
->streamFile( $params )->isOK();
1368 * Call a callback function for every public regular file in the repository.
1369 * This only acts on the current version of files, not any old versions.
1370 * May use either the database or the filesystem.
1372 * @param $callback Array|string
1375 public function enumFiles( $callback ) {
1376 $this->enumFilesInStorage( $callback );
1380 * Call a callback function for every public file in the repository.
1381 * May use either the database or the filesystem.
1383 * @param $callback Array|string
1386 protected function enumFilesInStorage( $callback ) {
1387 $publicRoot = $this->getZonePath( 'public' );
1388 $numDirs = 1 << ( $this->hashLevels
* 4 );
1389 // Use a priori assumptions about directory structure
1390 // to reduce the tree height of the scanning process.
1391 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1392 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1393 $path = $publicRoot;
1394 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1395 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1397 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1398 foreach ( $iterator as $name ) {
1399 // Each item returned is a public file
1400 call_user_func( $callback, "{$path}/{$name}" );
1406 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1408 * @param $filename string
1411 public function validateFilename( $filename ) {
1412 if ( strval( $filename ) == '' ) {
1415 return FileBackend
::isPathTraversalFree( $filename );
1419 * Get a callback function to use for cleaning error message parameters
1423 function getErrorCleanupFunction() {
1424 switch ( $this->pathDisclosureProtection
) {
1426 case 'simple': // b/c
1427 $callback = array( $this, 'passThrough' );
1429 default: // 'paranoid'
1430 $callback = array( $this, 'paranoidClean' );
1436 * Path disclosure protection function
1438 * @param $param string
1441 function paranoidClean( $param ) {
1446 * Path disclosure protection function
1448 * @param $param string
1451 function passThrough( $param ) {
1456 * Create a new fatal error
1458 * @return FileRepoStatus
1460 public function newFatal( $message /*, parameters...*/ ) {
1461 $params = func_get_args();
1462 array_unshift( $params, $this );
1463 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1467 * Create a new good result
1469 * @param $value null|string
1470 * @return FileRepoStatus
1472 public function newGood( $value = null ) {
1473 return FileRepoStatus
::newGood( $this, $value );
1477 * Checks if there is a redirect named as $title. If there is, return the
1478 * title object. If not, return false.
1481 * @param $title Title of image
1484 public function checkRedirect( Title
$title ) {
1489 * Invalidates image redirect cache related to that image
1490 * Doesn't do anything for repositories that don't support image redirects.
1493 * @param $title Title of image
1495 public function invalidateImageRedirect( Title
$title ) {}
1498 * Get the human-readable name of the repo
1502 public function getDisplayName() {
1503 // We don't name our own repo, return nothing
1504 if ( $this->isLocal() ) {
1507 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1508 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1512 * Returns true if this the local file repository.
1516 public function isLocal() {
1517 return $this->getName() == 'local';
1521 * Get a key on the primary cache for this repository.
1522 * Returns false if the repository's cache is not accessible at this site.
1523 * The parameters are the parts of the key, as for wfMemcKey().
1528 public function getSharedCacheKey( /*...*/ ) {
1533 * Get a key for this repo in the local cache domain. These cache keys are
1534 * not shared with remote instances of the repo.
1535 * The parameters are the parts of the key, as for wfMemcKey().
1539 public function getLocalCacheKey( /*...*/ ) {
1540 $args = func_get_args();
1541 array_unshift( $args, 'filerepo', $this->getName() );
1542 return call_user_func_array( 'wfMemcKey', $args );
1546 * Get an temporary FileRepo associated with this repo.
1547 * Files will be created in the temp zone of this repo and
1548 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1549 * It will have the same backend as this repo.
1551 * @return TempFileRepo
1553 public function getTempRepo() {
1554 return new TempFileRepo( array(
1555 'name' => "{$this->name}-temp",
1556 'backend' => $this->backend
,
1559 'container' => $this->zones
['temp']['container'],
1560 'directory' => $this->zones
['temp']['directory']
1563 'container' => $this->zones
['thumb']['container'],
1564 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1566 : $this->zones
['thumb']['directory'] . '/temp'
1569 'url' => $this->getZoneUrl( 'temp' ),
1570 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1571 'hashLevels' => $this->hashLevels
// performance
1576 * Get an UploadStash associated with this repo.
1578 * @return UploadStash
1580 public function getUploadStash() {
1581 return new UploadStash( $this );
1585 * Throw an exception if this repo is read-only by design.
1586 * This does not and should not check getReadOnlyReason().
1589 * @throws MWException
1591 protected function assertWritableRepo() {}
1595 * FileRepo for temporary files created via FileRepo::getTempRepo()
1597 class TempFileRepo
extends FileRepo
{
1598 public function getTempRepo() {
1599 throw new MWException( "Cannot get a temp repo from a temp repo." );