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;
63 function __construct( array $info = null ) {
64 // Verify required settings presence
67 ||
!array_key_exists( 'name', $info )
68 ||
!array_key_exists( 'backend', $info )
70 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
74 $this->name
= $info['name'];
75 if ( $info['backend'] instanceof FileBackend
) {
76 $this->backend
= $info['backend']; // useful for testing
78 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
81 // Optional settings that can have no value
82 $optionalSettings = array(
83 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
84 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
87 foreach ( $optionalSettings as $var ) {
88 if ( isset( $info[$var] ) ) {
89 $this->$var = $info[$var];
93 // Optional settings that have a default
94 $this->initialCapital
= isset( $info['initialCapital'] )
95 ?
$info['initialCapital']
96 : MWNamespace
::isCapitalized( NS_FILE
);
97 $this->url
= isset( $info['url'] )
99 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
100 if ( isset( $info['thumbUrl'] ) ) {
101 $this->thumbUrl
= $info['thumbUrl'];
103 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
105 $this->hashLevels
= isset( $info['hashLevels'] )
106 ?
$info['hashLevels']
108 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
109 ?
$info['deletedHashLevels']
111 $this->transformVia404
= !empty( $info['transformVia404'] );
112 $this->zones
= isset( $info['zones'] )
115 // Give defaults for the basic zones...
116 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
117 if ( !isset( $this->zones
[$zone] ) ) {
118 $this->zones
[$zone] = array(
119 'container' => "{$this->name}-{$zone}",
120 'directory' => '' // container root
127 * Get the file backend instance. Use this function wisely.
129 * @return FileBackend
131 public function getBackend() {
132 return $this->backend
;
136 * Get an explanatory message if this repo is read-only.
137 * This checks if an administrator disabled writes to the backend.
139 * @return string|bool Returns false if the repo is not read-only
141 public function getReadOnlyReason() {
142 return $this->backend
->getReadOnlyReason();
146 * Check if a single zone or list of zones is defined for usage
148 * @param $doZones Array Only do a particular zones
151 protected function initZones( $doZones = array() ) {
152 $status = $this->newGood();
153 foreach ( (array)$doZones as $zone ) {
154 $root = $this->getZonePath( $zone );
155 if ( $root === null ) {
156 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
163 * Take all available measures to prevent web accessibility of new deleted
164 * directories, in case the user has not configured offline storage
169 protected function initDeletedDir( $dir ) {
170 $this->backend
->secure( // prevent web access & dir listings
171 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
175 * Determine if a string is an mwrepo:// URL
180 public static function isVirtualUrl( $url ) {
181 return substr( $url, 0, 9 ) == 'mwrepo://';
185 * Get a URL referring to this repository, with the private mwrepo protocol.
186 * The suffix, if supplied, is considered to be unencoded, and will be
187 * URL-encoded before being returned.
189 * @param $suffix string
192 public function getVirtualUrl( $suffix = false ) {
193 $path = 'mwrepo://' . $this->name
;
194 if ( $suffix !== false ) {
195 $path .= '/' . rawurlencode( $suffix );
201 * Get the URL corresponding to one of the four basic zones
203 * @param $zone String: one of: public, deleted, temp, thumb
204 * @return String or false
206 public function getZoneUrl( $zone ) {
211 return "{$this->url}/temp";
213 return false; // no public URL
215 return $this->thumbUrl
;
222 * Get the backend storage path corresponding to a virtual URL.
223 * Use this function wisely.
228 public function resolveVirtualUrl( $url ) {
229 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
230 throw new MWException( __METHOD__
.': unknown protocol' );
232 $bits = explode( '/', substr( $url, 9 ), 3 );
233 if ( count( $bits ) != 3 ) {
234 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
236 list( $repo, $zone, $rel ) = $bits;
237 if ( $repo !== $this->name
) {
238 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
240 $base = $this->getZonePath( $zone );
242 throw new MWException( __METHOD__
.": invalid zone: $zone" );
244 return $base . '/' . rawurldecode( $rel );
248 * The the storage container and base path of a zone
250 * @param $zone string
251 * @return Array (container, base path) or (null, null)
253 protected function getZoneLocation( $zone ) {
254 if ( !isset( $this->zones
[$zone] ) ) {
255 return array( null, null ); // bogus
257 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
261 * Get the storage path corresponding to one of the zones
263 * @param $zone string
264 * @return string|null Returns null if the zone is not defined
266 public function getZonePath( $zone ) {
267 list( $container, $base ) = $this->getZoneLocation( $zone );
268 if ( $container === null ||
$base === null ) {
271 $backendName = $this->backend
->getName();
272 if ( $base != '' ) { // may not be set
275 return "mwstore://$backendName/{$container}{$base}";
279 * Create a new File object from the local repository
281 * @param $title Mixed: Title object or string
282 * @param $time Mixed: Time at which the image was uploaded.
283 * If this is specified, the returned object will be an
284 * instance of the repository's old file class instead of a
285 * current file. Repositories not supporting version control
286 * should return false if this parameter is set.
287 * @return File|null A File, or null if passed an invalid Title
289 public function newFile( $title, $time = false ) {
290 $title = File
::normalizeTitle( $title );
295 if ( $this->oldFileFactory
) {
296 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
301 return call_user_func( $this->fileFactory
, $title, $this );
306 * Find an instance of the named file created at the specified time
307 * Returns false if the file does not exist. Repositories not supporting
308 * version control should return false if the time is specified.
310 * @param $title Mixed: Title object or string
311 * @param $options array Associative array of options:
312 * time: requested time for a specific file version, or false for the
313 * current version. An image object will be returned which was
314 * created at the specified time (which may be archived or current).
316 * ignoreRedirect: If true, do not follow file redirects
318 * private: If true, return restricted (deleted) files if the current
319 * user is allowed to view them. Otherwise, such files will not
321 * @return File|bool False on failure
323 public function findFile( $title, $options = array() ) {
324 $title = File
::normalizeTitle( $title );
328 $time = isset( $options['time'] ) ?
$options['time'] : false;
329 # First try the current version of the file to see if it precedes the timestamp
330 $img = $this->newFile( $title );
334 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
337 # Now try an old version of the file
338 if ( $time !== false ) {
339 $img = $this->newFile( $title, $time );
340 if ( $img && $img->exists() ) {
341 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
342 return $img; // always OK
343 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
350 if ( !empty( $options['ignoreRedirect'] ) ) {
353 $redir = $this->checkRedirect( $title );
354 if ( $redir && $title->getNamespace() == NS_FILE
) {
355 $img = $this->newFile( $redir );
359 if ( $img->exists() ) {
360 $img->redirectedFrom( $title->getDBkey() );
368 * Find many files at once.
370 * @param $items array An array of titles, or an array of findFile() options with
371 * the "title" option giving the title. Example:
373 * $findItem = array( 'title' => $title, 'private' => true );
374 * $findBatch = array( $findItem );
375 * $repo->findFiles( $findBatch );
378 public function findFiles( array $items ) {
380 foreach ( $items as $item ) {
381 if ( is_array( $item ) ) {
382 $title = $item['title'];
384 unset( $options['title'] );
389 $file = $this->findFile( $title, $options );
391 $result[$file->getTitle()->getDBkey()] = $file;
398 * Find an instance of the file with this key, created at the specified time
399 * Returns false if the file does not exist. Repositories not supporting
400 * version control should return false if the time is specified.
402 * @param $sha1 String base 36 SHA-1 hash
403 * @param $options array Option array, same as findFile().
404 * @return File|bool False on failure
406 public function findFileFromKey( $sha1, $options = array() ) {
407 $time = isset( $options['time'] ) ?
$options['time'] : false;
408 # First try to find a matching current version of a file...
409 if ( $this->fileFactoryKey
) {
410 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
412 return false; // find-by-sha1 not supported
414 if ( $img && $img->exists() ) {
417 # Now try to find a matching old version of a file...
418 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
419 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
420 if ( $img && $img->exists() ) {
421 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
422 return $img; // always OK
423 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
432 * Get an array or iterator of file objects for files that have a given
433 * SHA-1 content hash.
438 public function findBySha1( $hash ) {
443 * Get the public root URL of the repository
447 public function getRootUrl() {
452 * Get the URL of thumb.php
456 public function getThumbScriptUrl() {
457 return $this->thumbScriptUrl
;
461 * Returns true if the repository can transform files via a 404 handler
465 public function canTransformVia404() {
466 return $this->transformVia404
;
470 * Get the name of an image from its title object
472 * @param $title Title
475 public function getNameFromTitle( Title
$title ) {
477 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
478 $name = $title->getUserCaseDBKey();
479 if ( $this->initialCapital
) {
480 $name = $wgContLang->ucfirst( $name );
483 $name = $title->getDBkey();
489 * Get the public zone root storage directory of the repository
493 public function getRootDirectory() {
494 return $this->getZonePath( 'public' );
498 * Get a relative path including trailing slash, e.g. f/fa/
499 * If the repo is not hashed, returns an empty string
501 * @param $name string Name of file
504 public function getHashPath( $name ) {
505 return self
::getHashPathForLevel( $name, $this->hashLevels
);
509 * Get a relative path including trailing slash, e.g. f/fa/
510 * If the repo is not hashed, returns an empty string
512 * @param $suffix string Basename of file from FileRepo::storeTemp()
515 public function getTempHashPath( $suffix ) {
516 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
517 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
518 return self
::getHashPathForLevel( $name, $this->hashLevels
);
526 protected static function getHashPathForLevel( $name, $levels ) {
527 if ( $levels == 0 ) {
530 $hash = md5( $name );
532 for ( $i = 1; $i <= $levels; $i++
) {
533 $path .= substr( $hash, 0, $i ) . '/';
540 * Get the number of hash directory levels
544 public function getHashLevels() {
545 return $this->hashLevels
;
549 * Get the name of this repository, as specified by $info['name]' to the constructor
553 public function getName() {
558 * Make an url to this repo
560 * @param $query mixed Query string to append
561 * @param $entry string Entry point; defaults to index
562 * @return string|bool False on failure
564 public function makeUrl( $query = '', $entry = 'index' ) {
565 if ( isset( $this->scriptDirUrl
) ) {
566 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
567 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
573 * Get the URL of an image description page. May return false if it is
574 * unknown or not applicable. In general this should only be called by the
575 * File class, since it may return invalid results for certain kinds of
576 * repositories. Use File::getDescriptionUrl() in user code.
578 * In particular, it uses the article paths as specified to the repository
579 * constructor, whereas local repositories use the local Title functions.
581 * @param $name string
584 public function getDescriptionUrl( $name ) {
585 $encName = wfUrlencode( $name );
586 if ( !is_null( $this->descBaseUrl
) ) {
587 # "http://example.com/wiki/Image:"
588 return $this->descBaseUrl
. $encName;
590 if ( !is_null( $this->articleUrl
) ) {
591 # "http://example.com/wiki/$1"
593 # We use "Image:" as the canonical namespace for
594 # compatibility across all MediaWiki versions.
595 return str_replace( '$1',
596 "Image:$encName", $this->articleUrl
);
598 if ( !is_null( $this->scriptDirUrl
) ) {
599 # "http://example.com/w"
601 # We use "Image:" as the canonical namespace for
602 # compatibility across all MediaWiki versions,
603 # and just sort of hope index.php is right. ;)
604 return $this->makeUrl( "title=Image:$encName" );
610 * Get the URL of the content-only fragment of the description page. For
611 * MediaWiki this means action=render. This should only be called by the
612 * repository's file class, since it may return invalid results. User code
613 * should use File::getDescriptionText().
615 * @param $name String: name of image to fetch
616 * @param $lang String: language to fetch it in, if any.
619 public function getDescriptionRenderUrl( $name, $lang = null ) {
620 $query = 'action=render';
621 if ( !is_null( $lang ) ) {
622 $query .= '&uselang=' . $lang;
624 if ( isset( $this->scriptDirUrl
) ) {
625 return $this->makeUrl(
627 wfUrlencode( 'Image:' . $name ) .
630 $descUrl = $this->getDescriptionUrl( $name );
632 return wfAppendQuery( $descUrl, $query );
640 * Get the URL of the stylesheet to apply to description pages
642 * @return string|bool False on failure
644 public function getDescriptionStylesheetUrl() {
645 if ( isset( $this->scriptDirUrl
) ) {
646 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
647 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
653 * Store a file to a given destination.
655 * @param $srcPath String: source FS path, storage path, or virtual URL
656 * @param $dstZone String: destination zone
657 * @param $dstRel String: destination relative path
658 * @param $flags Integer: bitwise combination of the following flags:
659 * self::DELETE_SOURCE Delete the source file after upload
660 * self::OVERWRITE Overwrite an existing destination file instead of failing
661 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
662 * same contents as the source
663 * self::SKIP_LOCKING Skip any file locking when doing the store
664 * @return FileRepoStatus
666 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
667 $this->assertWritableRepo(); // fail out if read-only
669 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
670 if ( $status->successCount
== 0 ) {
678 * Store a batch of files
680 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
681 * @param $flags Integer: bitwise combination of the following flags:
682 * self::DELETE_SOURCE Delete the source file after upload
683 * self::OVERWRITE Overwrite an existing destination file instead of failing
684 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
685 * same contents as the source
686 * self::SKIP_LOCKING Skip any file locking when doing the store
687 * @return FileRepoStatus
689 public function storeBatch( array $triplets, $flags = 0 ) {
690 $this->assertWritableRepo(); // fail out if read-only
692 $status = $this->newGood();
693 $backend = $this->backend
; // convenience
695 $operations = array();
696 $sourceFSFilesToDelete = array(); // cleanup for disk source files
697 // Validate each triplet and get the store operation...
698 foreach ( $triplets as $triplet ) {
699 list( $srcPath, $dstZone, $dstRel ) = $triplet;
701 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
704 // Resolve destination path
705 $root = $this->getZonePath( $dstZone );
707 throw new MWException( "Invalid zone: $dstZone" );
709 if ( !$this->validateFilename( $dstRel ) ) {
710 throw new MWException( 'Validation error in $dstRel' );
712 $dstPath = "$root/$dstRel";
713 $dstDir = dirname( $dstPath );
714 // Create destination directories for this triplet
715 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
716 return $this->newFatal( 'directorycreateerror', $dstDir );
719 if ( $dstZone == 'deleted' ) {
720 $this->initDeletedDir( $dstDir );
723 // Resolve source to a storage path if virtual
724 $srcPath = $this->resolveToStoragePath( $srcPath );
726 // Get the appropriate file operation
727 if ( FileBackend
::isStoragePath( $srcPath ) ) {
728 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
731 if ( $flags & self
::DELETE_SOURCE
) {
732 $sourceFSFilesToDelete[] = $srcPath;
735 $operations[] = array(
739 'overwrite' => $flags & self
::OVERWRITE
,
740 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
744 // Execute the store operation for each triplet
745 $opts = array( 'force' => true );
746 if ( $flags & self
::SKIP_LOCKING
) {
747 $opts['nonLocking'] = true;
749 $status->merge( $backend->doOperations( $operations, $opts ) );
750 // Cleanup for disk source files...
751 foreach ( $sourceFSFilesToDelete as $file ) {
752 wfSuppressWarnings();
753 unlink( $file ); // FS cleanup
761 * Deletes a batch of files.
762 * Each file can be a (zone, rel) pair, virtual url, storage path.
763 * It will try to delete each file, but ignores any errors that may occur.
765 * @param $pairs array List of files to delete
766 * @param $flags Integer: bitwise combination of the following flags:
767 * self::SKIP_LOCKING Skip any file locking when doing the deletions
768 * @return FileRepoStatus
770 public function cleanupBatch( array $files, $flags = 0 ) {
771 $this->assertWritableRepo(); // fail out if read-only
773 $status = $this->newGood();
775 $operations = array();
776 foreach ( $files as $path ) {
777 if ( is_array( $path ) ) {
778 // This is a pair, extract it
779 list( $zone, $rel ) = $path;
780 $path = $this->getZonePath( $zone ) . "/$rel";
782 // Resolve source to a storage path if virtual
783 $path = $this->resolveToStoragePath( $path );
785 $operations[] = array( 'op' => 'delete', 'src' => $path );
787 // Actually delete files from storage...
788 $opts = array( 'force' => true );
789 if ( $flags & self
::SKIP_LOCKING
) {
790 $opts['nonLocking'] = true;
792 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
798 * Import a file from the local file system into the repo.
799 * This does no locking nor journaling and overrides existing files.
800 * This function can be used to write to otherwise read-only foreign repos.
801 * This is intended for copying generated thumbnails into the repo.
803 * @param $src string File system path
804 * @param $dst string Virtual URL or storage path
805 * @return FileRepoStatus
807 final public function quickImport( $src, $dst ) {
808 return $this->quickImportBatch( array( array( $src, $dst ) ) );
812 * Purge a file from the repo. This does no locking nor journaling.
813 * This function can be used to write to otherwise read-only foreign repos.
814 * This is intended for purging thumbnails.
816 * @param $path string Virtual URL or storage path
817 * @return FileRepoStatus
819 final public function quickPurge( $path ) {
820 return $this->quickPurgeBatch( array( $path ) );
824 * Deletes a directory if empty.
825 * This function can be used to write to otherwise read-only foreign repos.
827 * @param $dir string Virtual URL (or storage path) of directory to clean
830 public function quickCleanDir( $dir ) {
831 $status = $this->newGood();
832 $status->merge( $this->backend
->clean(
833 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
839 * Import a batch of files from the local file system into the repo.
840 * This does no locking nor journaling and overrides existing files.
841 * This function can be used to write to otherwise read-only foreign repos.
842 * This is intended for copying generated thumbnails into the repo.
844 * @param $src Array List of tuples (file system path, virtual URL or storage path)
845 * @return FileRepoStatus
847 public function quickImportBatch( array $pairs ) {
848 $status = $this->newGood();
849 $operations = array();
850 foreach ( $pairs as $pair ) {
851 list ( $src, $dst ) = $pair;
852 $operations[] = array(
855 'dst' => $this->resolveToStoragePath( $dst )
857 $this->backend
->prepare( array( 'dir' => dirname( $dst ) ) );
859 $status->merge( $this->backend
->doQuickOperations( $operations ) );
865 * Purge a batch of files from the repo.
866 * This function can be used to write to otherwise read-only foreign repos.
867 * This does no locking nor journaling and is intended for purging thumbnails.
869 * @param $path Array List of virtual URLs or storage paths
870 * @return FileRepoStatus
872 public function quickPurgeBatch( array $paths ) {
873 $status = $this->newGood();
874 $operations = array();
875 foreach ( $paths as $path ) {
876 $operations[] = array(
878 'src' => $this->resolveToStoragePath( $path ),
879 'ignoreMissingSource' => true
882 $status->merge( $this->backend
->doQuickOperations( $operations ) );
888 * Pick a random name in the temp zone and store a file to it.
889 * Returns a FileRepoStatus object with the file Virtual URL in the value,
890 * file can later be disposed using FileRepo::freeTemp().
892 * @param $originalName String: the base name of the file as specified
893 * by the user. The file extension will be maintained.
894 * @param $srcPath String: the current location of the file.
895 * @return FileRepoStatus object with the URL in the value.
897 public function storeTemp( $originalName, $srcPath ) {
898 $this->assertWritableRepo(); // fail out if read-only
900 $date = gmdate( "YmdHis" );
901 $hashPath = $this->getHashPath( $originalName );
902 $dstRel = "{$hashPath}{$date}!{$originalName}";
903 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
905 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
906 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
912 * Concatenate a list of files into a target file location.
914 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
915 * @param $dstPath String Target file system path
916 * @param $flags Integer: bitwise combination of the following flags:
917 * self::DELETE_SOURCE Delete the source files
918 * @return FileRepoStatus
920 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
921 $this->assertWritableRepo(); // fail out if read-only
923 $status = $this->newGood();
926 $deleteOperations = array(); // post-concatenate ops
927 foreach ( $srcPaths as $srcPath ) {
928 // Resolve source to a storage path if virtual
929 $source = $this->resolveToStoragePath( $srcPath );
930 $sources[] = $source; // chunk to merge
931 if ( $flags & self
::DELETE_SOURCE
) {
932 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
936 // Concatenate the chunks into one FS file
937 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
938 $status->merge( $this->backend
->concatenate( $params ) );
939 if ( !$status->isOK() ) {
943 // Delete the sources if required
944 if ( $deleteOperations ) {
945 $opts = array( 'force' => true );
946 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
949 // Make sure status is OK, despite any $deleteOperations fatals
950 $status->setResult( true );
956 * Remove a temporary file or mark it for garbage collection
958 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
959 * @return Boolean: true on success, false on failure
961 public function freeTemp( $virtualUrl ) {
962 $this->assertWritableRepo(); // fail out if read-only
964 $temp = "mwrepo://{$this->name}/temp";
965 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
966 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
969 $path = $this->resolveVirtualUrl( $virtualUrl );
971 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
975 * Copy or move a file either from a storage path, virtual URL,
976 * or FS path, into this repository at the specified destination location.
978 * Returns a FileRepoStatus object. On success, the value contains "new" or
979 * "archived", to indicate whether the file was new with that name.
981 * @param $srcPath String: the source FS path, storage path, or URL
982 * @param $dstRel String: the destination relative path
983 * @param $archiveRel String: the relative path where the existing file is to
984 * be archived, if there is one. Relative to the public zone root.
985 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
986 * that the source file should be deleted if possible
987 * @return FileRepoStatus
989 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
990 $this->assertWritableRepo(); // fail out if read-only
992 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
993 if ( $status->successCount
== 0 ) {
996 if ( isset( $status->value
[0] ) ) {
997 $status->value
= $status->value
[0];
999 $status->value
= false;
1006 * Publish a batch of files
1008 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1009 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1010 * that the source files should be deleted if possible
1011 * @return FileRepoStatus
1013 public function publishBatch( array $triplets, $flags = 0 ) {
1014 $this->assertWritableRepo(); // fail out if read-only
1016 $backend = $this->backend
; // convenience
1017 // Try creating directories
1018 $status = $this->initZones( 'public' );
1019 if ( !$status->isOK() ) {
1023 $status = $this->newGood( array() );
1025 $operations = array();
1026 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1027 // Validate each triplet and get the store operation...
1028 foreach ( $triplets as $i => $triplet ) {
1029 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1030 // Resolve source to a storage path if virtual
1031 $srcPath = $this->resolveToStoragePath( $srcPath );
1032 if ( !$this->validateFilename( $dstRel ) ) {
1033 throw new MWException( 'Validation error in $dstRel' );
1035 if ( !$this->validateFilename( $archiveRel ) ) {
1036 throw new MWException( 'Validation error in $archiveRel' );
1039 $publicRoot = $this->getZonePath( 'public' );
1040 $dstPath = "$publicRoot/$dstRel";
1041 $archivePath = "$publicRoot/$archiveRel";
1043 $dstDir = dirname( $dstPath );
1044 $archiveDir = dirname( $archivePath );
1045 // Abort immediately on directory creation errors since they're likely to be repetitive
1046 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1047 return $this->newFatal( 'directorycreateerror', $dstDir );
1049 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1050 return $this->newFatal( 'directorycreateerror', $archiveDir );
1053 // Archive destination file if it exists
1054 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1055 // Check if the archive file exists
1056 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1057 // unlinks the destination file if it exists. DB-based synchronisation in
1058 // publishBatch's caller should prevent races. In Windows there's no
1059 // problem because the rename primitive fails if the destination exists.
1060 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1061 $operations[] = array( 'op' => 'null' );
1064 $operations[] = array(
1067 'dst' => $archivePath
1070 $status->value
[$i] = 'archived';
1072 $status->value
[$i] = 'new';
1074 // Copy (or move) the source file to the destination
1075 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1076 if ( $flags & self
::DELETE_SOURCE
) {
1077 $operations[] = array(
1083 $operations[] = array(
1089 } else { // FS source path
1090 $operations[] = array(
1095 if ( $flags & self
::DELETE_SOURCE
) {
1096 $sourceFSFilesToDelete[] = $srcPath;
1101 // Execute the operations for each triplet
1102 $opts = array( 'force' => true );
1103 $status->merge( $backend->doOperations( $operations, $opts ) );
1104 // Cleanup for disk source files...
1105 foreach ( $sourceFSFilesToDelete as $file ) {
1106 wfSuppressWarnings();
1107 unlink( $file ); // FS cleanup
1108 wfRestoreWarnings();
1115 * Deletes a directory if empty.
1117 * @param $dir string Virtual URL (or storage path) of directory to clean
1120 public function cleanDir( $dir ) {
1121 $this->assertWritableRepo(); // fail out if read-only
1123 $status = $this->newGood();
1124 $status->merge( $this->backend
->clean(
1125 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1131 * Checks existence of a a file
1133 * @param $file string Virtual URL (or storage path) of file to check
1136 public function fileExists( $file ) {
1137 $result = $this->fileExistsBatch( array( $file ) );
1142 * Checks existence of an array of files.
1144 * @param $files Array: Virtual URLs (or storage paths) of files to check
1145 * @return array|bool Either array of files and existence flags, or false
1147 public function fileExistsBatch( array $files ) {
1149 foreach ( $files as $key => $file ) {
1150 $file = $this->resolveToStoragePath( $file );
1151 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1157 * Move a file to the deletion archive.
1158 * If no valid deletion archive exists, this may either delete the file
1159 * or throw an exception, depending on the preference of the repository
1161 * @param $srcRel Mixed: relative path for the file to be deleted
1162 * @param $archiveRel Mixed: relative path for the archive location.
1163 * Relative to a private archive directory.
1164 * @return FileRepoStatus object
1166 public function delete( $srcRel, $archiveRel ) {
1167 $this->assertWritableRepo(); // fail out if read-only
1169 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1173 * Move a group of files to the deletion archive.
1175 * If no valid deletion archive is configured, this may either delete the
1176 * file or throw an exception, depending on the preference of the repository.
1178 * The overwrite policy is determined by the repository -- currently LocalRepo
1179 * assumes a naming scheme in the deleted zone based on content hash, as
1180 * opposed to the public zone which is assumed to be unique.
1182 * @param $sourceDestPairs Array of source/destination pairs. Each element
1183 * is a two-element array containing the source file path relative to the
1184 * public root in the first element, and the archive file path relative
1185 * to the deleted zone root in the second element.
1186 * @return FileRepoStatus
1188 public function deleteBatch( array $sourceDestPairs ) {
1189 $this->assertWritableRepo(); // fail out if read-only
1191 // Try creating directories
1192 $status = $this->initZones( array( 'public', 'deleted' ) );
1193 if ( !$status->isOK() ) {
1197 $status = $this->newGood();
1199 $backend = $this->backend
; // convenience
1200 $operations = array();
1201 // Validate filenames and create archive directories
1202 foreach ( $sourceDestPairs as $pair ) {
1203 list( $srcRel, $archiveRel ) = $pair;
1204 if ( !$this->validateFilename( $srcRel ) ) {
1205 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1206 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1207 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1210 $publicRoot = $this->getZonePath( 'public' );
1211 $srcPath = "{$publicRoot}/$srcRel";
1213 $deletedRoot = $this->getZonePath( 'deleted' );
1214 $archivePath = "{$deletedRoot}/{$archiveRel}";
1215 $archiveDir = dirname( $archivePath ); // does not touch FS
1217 // Create destination directories
1218 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1219 return $this->newFatal( 'directorycreateerror', $archiveDir );
1221 $this->initDeletedDir( $archiveDir );
1223 $operations[] = array(
1226 'dst' => $archivePath,
1227 // We may have 2+ identical files being deleted,
1228 // all of which will map to the same destination file
1229 'overwriteSame' => true // also see bug 31792
1233 // Move the files by execute the operations for each pair.
1234 // We're now committed to returning an OK result, which will
1235 // lead to the files being moved in the DB also.
1236 $opts = array( 'force' => true );
1237 $status->merge( $backend->doOperations( $operations, $opts ) );
1243 * Delete files in the deleted directory if they are not referenced in the filearchive table
1247 public function cleanupDeletedBatch( array $storageKeys ) {
1248 $this->assertWritableRepo();
1252 * Get a relative path for a deletion archive key,
1253 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1257 public function getDeletedHashPath( $key ) {
1259 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1260 $path .= $key[$i] . '/';
1266 * If a path is a virtual URL, resolve it to a storage path.
1267 * Otherwise, just return the path as it is.
1269 * @param $path string
1271 * @throws MWException
1273 protected function resolveToStoragePath( $path ) {
1274 if ( $this->isVirtualUrl( $path ) ) {
1275 return $this->resolveVirtualUrl( $path );
1281 * Get a local FS copy of a file with a given virtual URL/storage path.
1282 * Temporary files may be purged when the file object falls out of scope.
1284 * @param $virtualUrl string
1285 * @return TempFSFile|null Returns null on failure
1287 public function getLocalCopy( $virtualUrl ) {
1288 $path = $this->resolveToStoragePath( $virtualUrl );
1289 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1293 * Get a local FS file with a given virtual URL/storage path.
1294 * The file is either an original or a copy. It should not be changed.
1295 * Temporary files may be purged when the file object falls out of scope.
1297 * @param $virtualUrl string
1298 * @return FSFile|null Returns null on failure.
1300 public function getLocalReference( $virtualUrl ) {
1301 $path = $this->resolveToStoragePath( $virtualUrl );
1302 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1306 * Get properties of a file with a given virtual URL/storage path.
1307 * Properties should ultimately be obtained via FSFile::getProps().
1309 * @param $virtualUrl string
1312 public function getFileProps( $virtualUrl ) {
1313 $path = $this->resolveToStoragePath( $virtualUrl );
1314 return $this->backend
->getFileProps( array( 'src' => $path ) );
1318 * Get the timestamp of a file with a given virtual URL/storage path
1320 * @param $virtualUrl string
1321 * @return string|bool False on failure
1323 public function getFileTimestamp( $virtualUrl ) {
1324 $path = $this->resolveToStoragePath( $virtualUrl );
1325 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1329 * Get the sha1 of a file with a given virtual URL/storage path
1331 * @param $virtualUrl string
1332 * @return string|bool
1334 public function getFileSha1( $virtualUrl ) {
1335 $path = $this->resolveToStoragePath( $virtualUrl );
1336 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1340 return $tmpFile->getSha1Base36();
1344 * Attempt to stream a file with the given virtual URL/storage path
1346 * @param $virtualUrl string
1347 * @param $headers Array Additional HTTP headers to send on success
1348 * @return bool Success
1350 public function streamFile( $virtualUrl, $headers = array() ) {
1351 $path = $this->resolveToStoragePath( $virtualUrl );
1352 $params = array( 'src' => $path, 'headers' => $headers );
1353 return $this->backend
->streamFile( $params )->isOK();
1357 * Call a callback function for every public regular file in the repository.
1358 * This only acts on the current version of files, not any old versions.
1359 * May use either the database or the filesystem.
1361 * @param $callback Array|string
1364 public function enumFiles( $callback ) {
1365 $this->enumFilesInStorage( $callback );
1369 * Call a callback function for every public file in the repository.
1370 * May use either the database or the filesystem.
1372 * @param $callback Array|string
1375 protected function enumFilesInStorage( $callback ) {
1376 $publicRoot = $this->getZonePath( 'public' );
1377 $numDirs = 1 << ( $this->hashLevels
* 4 );
1378 // Use a priori assumptions about directory structure
1379 // to reduce the tree height of the scanning process.
1380 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1381 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1382 $path = $publicRoot;
1383 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1384 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1386 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1387 foreach ( $iterator as $name ) {
1388 // Each item returned is a public file
1389 call_user_func( $callback, "{$path}/{$name}" );
1395 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1397 * @param $filename string
1400 public function validateFilename( $filename ) {
1401 if ( strval( $filename ) == '' ) {
1404 return FileBackend
::isPathTraversalFree( $filename );
1408 * Get a callback function to use for cleaning error message parameters
1412 function getErrorCleanupFunction() {
1413 switch ( $this->pathDisclosureProtection
) {
1415 case 'simple': // b/c
1416 $callback = array( $this, 'passThrough' );
1418 default: // 'paranoid'
1419 $callback = array( $this, 'paranoidClean' );
1425 * Path disclosure protection function
1427 * @param $param string
1430 function paranoidClean( $param ) {
1435 * Path disclosure protection function
1437 * @param $param string
1440 function passThrough( $param ) {
1445 * Create a new fatal error
1447 * @return FileRepoStatus
1449 public function newFatal( $message /*, parameters...*/ ) {
1450 $params = func_get_args();
1451 array_unshift( $params, $this );
1452 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1456 * Create a new good result
1458 * @return FileRepoStatus
1460 public function newGood( $value = null ) {
1461 return FileRepoStatus
::newGood( $this, $value );
1465 * Checks if there is a redirect named as $title. If there is, return the
1466 * title object. If not, return false.
1469 * @param $title Title of image
1472 public function checkRedirect( Title
$title ) {
1477 * Invalidates image redirect cache related to that image
1478 * Doesn't do anything for repositories that don't support image redirects.
1481 * @param $title Title of image
1483 public function invalidateImageRedirect( Title
$title ) {}
1486 * Get the human-readable name of the repo
1490 public function getDisplayName() {
1491 // We don't name our own repo, return nothing
1492 if ( $this->isLocal() ) {
1495 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1496 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1500 * Returns true if this the local file repository.
1504 public function isLocal() {
1505 return $this->getName() == 'local';
1509 * Get a key on the primary cache for this repository.
1510 * Returns false if the repository's cache is not accessible at this site.
1511 * The parameters are the parts of the key, as for wfMemcKey().
1516 public function getSharedCacheKey( /*...*/ ) {
1521 * Get a key for this repo in the local cache domain. These cache keys are
1522 * not shared with remote instances of the repo.
1523 * The parameters are the parts of the key, as for wfMemcKey().
1527 public function getLocalCacheKey( /*...*/ ) {
1528 $args = func_get_args();
1529 array_unshift( $args, 'filerepo', $this->getName() );
1530 return call_user_func_array( 'wfMemcKey', $args );
1534 * Get an temporary FileRepo associated with this repo.
1535 * Files will be created in the temp zone of this repo and
1536 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1537 * It will have the same backend as this repo.
1539 * @return TempFileRepo
1541 public function getTempRepo() {
1542 return new TempFileRepo( array(
1543 'name' => "{$this->name}-temp",
1544 'backend' => $this->backend
,
1547 'container' => $this->zones
['temp']['container'],
1548 'directory' => $this->zones
['temp']['directory']
1551 'container' => $this->zones
['thumb']['container'],
1552 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1554 : $this->zones
['thumb']['directory'] . '/temp'
1557 'url' => $this->getZoneUrl( 'temp' ),
1558 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1559 'hashLevels' => $this->hashLevels
// performance
1564 * Get an UploadStash associated with this repo.
1566 * @return UploadStash
1568 public function getUploadStash() {
1569 return new UploadStash( $this );
1573 * Throw an exception if this repo is read-only by design.
1574 * This does not and should not check getReadOnlyReason().
1577 * @throws MWException
1579 protected function assertWritableRepo() {}
1583 * FileRepo for temporary files created via FileRepo::getTempRepo()
1585 class TempFileRepo
extends FileRepo
{
1586 public function getTempRepo() {
1587 throw new MWException( "Cannot get a temp repo from a temp repo." );