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->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]['container'] ) ) {
122 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
124 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
125 $this->zones
[$zone]['directory'] = '';
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 * Determine if a string is an mwrepo:// URL
173 public static function isVirtualUrl( $url ) {
174 return substr( $url, 0, 9 ) == 'mwrepo://';
178 * Get a URL referring to this repository, with the private mwrepo protocol.
179 * The suffix, if supplied, is considered to be unencoded, and will be
180 * URL-encoded before being returned.
182 * @param $suffix string|bool
185 public function getVirtualUrl( $suffix = false ) {
186 $path = 'mwrepo://' . $this->name
;
187 if ( $suffix !== false ) {
188 $path .= '/' . rawurlencode( $suffix );
194 * Get the URL corresponding to one of the four basic zones
196 * @param $zone String: one of: public, deleted, temp, thumb
197 * @return String or false
199 public function getZoneUrl( $zone ) {
200 if ( isset( $this->zones
[$zone]['url'] )
201 && in_array( $zone, array( 'public', 'temp', 'thumb' ) ) )
203 return $this->zones
[$zone]['url']; // custom URL
209 return "{$this->url}/temp";
211 return false; // no public URL
213 return $this->thumbUrl
;
220 * Get the backend storage path corresponding to a virtual URL.
221 * Use this function wisely.
224 * @throws MWException
227 public function resolveVirtualUrl( $url ) {
228 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
229 throw new MWException( __METHOD__
.': unknown protocol' );
231 $bits = explode( '/', substr( $url, 9 ), 3 );
232 if ( count( $bits ) != 3 ) {
233 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
235 list( $repo, $zone, $rel ) = $bits;
236 if ( $repo !== $this->name
) {
237 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
239 $base = $this->getZonePath( $zone );
241 throw new MWException( __METHOD__
.": invalid zone: $zone" );
243 return $base . '/' . rawurldecode( $rel );
247 * The the storage container and base path of a zone
249 * @param $zone string
250 * @return Array (container, base path) or (null, null)
252 protected function getZoneLocation( $zone ) {
253 if ( !isset( $this->zones
[$zone] ) ) {
254 return array( null, null ); // bogus
256 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
260 * Get the storage path corresponding to one of the zones
262 * @param $zone string
263 * @return string|null Returns null if the zone is not defined
265 public function getZonePath( $zone ) {
266 list( $container, $base ) = $this->getZoneLocation( $zone );
267 if ( $container === null ||
$base === null ) {
270 $backendName = $this->backend
->getName();
271 if ( $base != '' ) { // may not be set
274 return "mwstore://$backendName/{$container}{$base}";
278 * Create a new File object from the local repository
280 * @param $title Mixed: Title object or string
281 * @param $time Mixed: Time at which the image was uploaded.
282 * If this is specified, the returned object will be an
283 * instance of the repository's old file class instead of a
284 * current file. Repositories not supporting version control
285 * should return false if this parameter is set.
286 * @return File|null A File, or null if passed an invalid Title
288 public function newFile( $title, $time = false ) {
289 $title = File
::normalizeTitle( $title );
294 if ( $this->oldFileFactory
) {
295 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
300 return call_user_func( $this->fileFactory
, $title, $this );
305 * Find an instance of the named file created at the specified time
306 * Returns false if the file does not exist. Repositories not supporting
307 * version control should return false if the time is specified.
309 * @param $title Mixed: Title object or string
310 * @param $options array Associative array of options:
311 * time: requested time for a specific file version, or false for the
312 * current version. An image object will be returned which was
313 * created at the specified time (which may be archived or current).
315 * ignoreRedirect: If true, do not follow file redirects
317 * private: If true, return restricted (deleted) files if the current
318 * user is allowed to view them. Otherwise, such files will not
320 * @return File|bool False on failure
322 public function findFile( $title, $options = array() ) {
323 $title = File
::normalizeTitle( $title );
327 $time = isset( $options['time'] ) ?
$options['time'] : false;
328 # First try the current version of the file to see if it precedes the timestamp
329 $img = $this->newFile( $title );
333 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
336 # Now try an old version of the file
337 if ( $time !== false ) {
338 $img = $this->newFile( $title, $time );
339 if ( $img && $img->exists() ) {
340 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
341 return $img; // always OK
342 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
349 if ( !empty( $options['ignoreRedirect'] ) ) {
352 $redir = $this->checkRedirect( $title );
353 if ( $redir && $title->getNamespace() == NS_FILE
) {
354 $img = $this->newFile( $redir );
358 if ( $img->exists() ) {
359 $img->redirectedFrom( $title->getDBkey() );
367 * Find many files at once.
369 * @param $items array An array of titles, or an array of findFile() options with
370 * the "title" option giving the title. Example:
372 * $findItem = array( 'title' => $title, 'private' => true );
373 * $findBatch = array( $findItem );
374 * $repo->findFiles( $findBatch );
377 public function findFiles( array $items ) {
379 foreach ( $items as $item ) {
380 if ( is_array( $item ) ) {
381 $title = $item['title'];
383 unset( $options['title'] );
388 $file = $this->findFile( $title, $options );
390 $result[$file->getTitle()->getDBkey()] = $file;
397 * Find an instance of the file with this key, created at the specified time
398 * Returns false if the file does not exist. Repositories not supporting
399 * version control should return false if the time is specified.
401 * @param $sha1 String base 36 SHA-1 hash
402 * @param $options array Option array, same as findFile().
403 * @return File|bool False on failure
405 public function findFileFromKey( $sha1, $options = array() ) {
406 $time = isset( $options['time'] ) ?
$options['time'] : false;
407 # First try to find a matching current version of a file...
408 if ( $this->fileFactoryKey
) {
409 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
411 return false; // find-by-sha1 not supported
413 if ( $img && $img->exists() ) {
416 # Now try to find a matching old version of a file...
417 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
418 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
419 if ( $img && $img->exists() ) {
420 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
421 return $img; // always OK
422 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
431 * Get an array or iterator of file objects for files that have a given
432 * SHA-1 content hash.
438 public function findBySha1( $hash ) {
443 * Get an array of arrays or iterators of file objects for files that
444 * have the given SHA-1 content hashes.
446 * @param $hashes array An array of hashes
447 * @return array An Array of arrays or iterators of file objects and the hash as key
449 public function findBySha1s( array $hashes ) {
451 foreach ( $hashes as $hash ) {
452 $files = $this->findBySha1( $hash );
453 if ( count( $files ) ) {
454 $result[$hash] = $files;
461 * Get the public root URL of the repository
463 * @deprecated since 1.20
466 public function getRootUrl() {
467 return $this->getZoneUrl( 'public' );
471 * Get the URL of thumb.php
475 public function getThumbScriptUrl() {
476 return $this->thumbScriptUrl
;
480 * Returns true if the repository can transform files via a 404 handler
484 public function canTransformVia404() {
485 return $this->transformVia404
;
489 * Get the name of an image from its title object
491 * @param $title Title
494 public function getNameFromTitle( Title
$title ) {
496 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
497 $name = $title->getUserCaseDBKey();
498 if ( $this->initialCapital
) {
499 $name = $wgContLang->ucfirst( $name );
502 $name = $title->getDBkey();
508 * Get the public zone root storage directory of the repository
512 public function getRootDirectory() {
513 return $this->getZonePath( 'public' );
517 * Get a relative path including trailing slash, e.g. f/fa/
518 * If the repo is not hashed, returns an empty string
520 * @param $name string Name of file
523 public function getHashPath( $name ) {
524 return self
::getHashPathForLevel( $name, $this->hashLevels
);
528 * Get a relative path including trailing slash, e.g. f/fa/
529 * If the repo is not hashed, returns an empty string
531 * @param $suffix string Basename of file from FileRepo::storeTemp()
534 public function getTempHashPath( $suffix ) {
535 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
536 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
537 return self
::getHashPathForLevel( $name, $this->hashLevels
);
545 protected static function getHashPathForLevel( $name, $levels ) {
546 if ( $levels == 0 ) {
549 $hash = md5( $name );
551 for ( $i = 1; $i <= $levels; $i++
) {
552 $path .= substr( $hash, 0, $i ) . '/';
559 * Get the number of hash directory levels
563 public function getHashLevels() {
564 return $this->hashLevels
;
568 * Get the name of this repository, as specified by $info['name]' to the constructor
572 public function getName() {
577 * Make an url to this repo
579 * @param $query mixed Query string to append
580 * @param $entry string Entry point; defaults to index
581 * @return string|bool False on failure
583 public function makeUrl( $query = '', $entry = 'index' ) {
584 if ( isset( $this->scriptDirUrl
) ) {
585 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
586 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
592 * Get the URL of an image description page. May return false if it is
593 * unknown or not applicable. In general this should only be called by the
594 * File class, since it may return invalid results for certain kinds of
595 * repositories. Use File::getDescriptionUrl() in user code.
597 * In particular, it uses the article paths as specified to the repository
598 * constructor, whereas local repositories use the local Title functions.
600 * @param $name string
603 public function getDescriptionUrl( $name ) {
604 $encName = wfUrlencode( $name );
605 if ( !is_null( $this->descBaseUrl
) ) {
606 # "http://example.com/wiki/Image:"
607 return $this->descBaseUrl
. $encName;
609 if ( !is_null( $this->articleUrl
) ) {
610 # "http://example.com/wiki/$1"
612 # We use "Image:" as the canonical namespace for
613 # compatibility across all MediaWiki versions.
614 return str_replace( '$1',
615 "Image:$encName", $this->articleUrl
);
617 if ( !is_null( $this->scriptDirUrl
) ) {
618 # "http://example.com/w"
620 # We use "Image:" as the canonical namespace for
621 # compatibility across all MediaWiki versions,
622 # and just sort of hope index.php is right. ;)
623 return $this->makeUrl( "title=Image:$encName" );
629 * Get the URL of the content-only fragment of the description page. For
630 * MediaWiki this means action=render. This should only be called by the
631 * repository's file class, since it may return invalid results. User code
632 * should use File::getDescriptionText().
634 * @param $name String: name of image to fetch
635 * @param $lang String: language to fetch it in, if any.
638 public function getDescriptionRenderUrl( $name, $lang = null ) {
639 $query = 'action=render';
640 if ( !is_null( $lang ) ) {
641 $query .= '&uselang=' . $lang;
643 if ( isset( $this->scriptDirUrl
) ) {
644 return $this->makeUrl(
646 wfUrlencode( 'Image:' . $name ) .
649 $descUrl = $this->getDescriptionUrl( $name );
651 return wfAppendQuery( $descUrl, $query );
659 * Get the URL of the stylesheet to apply to description pages
661 * @return string|bool False on failure
663 public function getDescriptionStylesheetUrl() {
664 if ( isset( $this->scriptDirUrl
) ) {
665 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
666 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
672 * Store a file to a given destination.
674 * @param $srcPath String: source FS path, storage path, or virtual URL
675 * @param $dstZone String: destination zone
676 * @param $dstRel String: destination relative path
677 * @param $flags Integer: bitwise combination of the following flags:
678 * self::DELETE_SOURCE Delete the source file after upload
679 * self::OVERWRITE Overwrite an existing destination file instead of failing
680 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
681 * same contents as the source
682 * self::SKIP_LOCKING Skip any file locking when doing the store
683 * @return FileRepoStatus
685 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
686 $this->assertWritableRepo(); // fail out if read-only
688 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
689 if ( $status->successCount
== 0 ) {
697 * Store a batch of files
699 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
700 * @param $flags Integer: bitwise combination of the following flags:
701 * self::DELETE_SOURCE Delete the source file after upload
702 * self::OVERWRITE Overwrite an existing destination file instead of failing
703 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
704 * same contents as the source
705 * self::SKIP_LOCKING Skip any file locking when doing the store
706 * @throws MWException
707 * @return FileRepoStatus
709 public function storeBatch( array $triplets, $flags = 0 ) {
710 $this->assertWritableRepo(); // fail out if read-only
712 $status = $this->newGood();
713 $backend = $this->backend
; // convenience
715 $operations = array();
716 $sourceFSFilesToDelete = array(); // cleanup for disk source files
717 // Validate each triplet and get the store operation...
718 foreach ( $triplets as $triplet ) {
719 list( $srcPath, $dstZone, $dstRel ) = $triplet;
721 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
724 // Resolve destination path
725 $root = $this->getZonePath( $dstZone );
727 throw new MWException( "Invalid zone: $dstZone" );
729 if ( !$this->validateFilename( $dstRel ) ) {
730 throw new MWException( 'Validation error in $dstRel' );
732 $dstPath = "$root/$dstRel";
733 $dstDir = dirname( $dstPath );
734 // Create destination directories for this triplet
735 if ( !$this->initDirectory( $dstDir )->isOK() ) {
736 return $this->newFatal( 'directorycreateerror', $dstDir );
739 // Resolve source to a storage path if virtual
740 $srcPath = $this->resolveToStoragePath( $srcPath );
742 // Get the appropriate file operation
743 if ( FileBackend
::isStoragePath( $srcPath ) ) {
744 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
747 if ( $flags & self
::DELETE_SOURCE
) {
748 $sourceFSFilesToDelete[] = $srcPath;
751 $operations[] = array(
755 'overwrite' => $flags & self
::OVERWRITE
,
756 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
760 // Execute the store operation for each triplet
761 $opts = array( 'force' => true );
762 if ( $flags & self
::SKIP_LOCKING
) {
763 $opts['nonLocking'] = true;
765 $status->merge( $backend->doOperations( $operations, $opts ) );
766 // Cleanup for disk source files...
767 foreach ( $sourceFSFilesToDelete as $file ) {
768 wfSuppressWarnings();
769 unlink( $file ); // FS cleanup
777 * Deletes a batch of files.
778 * Each file can be a (zone, rel) pair, virtual url, storage path.
779 * It will try to delete each file, but ignores any errors that may occur.
781 * @param $files array List of files to delete
782 * @param $flags Integer: bitwise combination of the following flags:
783 * self::SKIP_LOCKING Skip any file locking when doing the deletions
784 * @return FileRepoStatus
786 public function cleanupBatch( array $files, $flags = 0 ) {
787 $this->assertWritableRepo(); // fail out if read-only
789 $status = $this->newGood();
791 $operations = array();
792 foreach ( $files as $path ) {
793 if ( is_array( $path ) ) {
794 // This is a pair, extract it
795 list( $zone, $rel ) = $path;
796 $path = $this->getZonePath( $zone ) . "/$rel";
798 // Resolve source to a storage path if virtual
799 $path = $this->resolveToStoragePath( $path );
801 $operations[] = array( 'op' => 'delete', 'src' => $path );
803 // Actually delete files from storage...
804 $opts = array( 'force' => true );
805 if ( $flags & self
::SKIP_LOCKING
) {
806 $opts['nonLocking'] = true;
808 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
814 * Import a file from the local file system into the repo.
815 * This does no locking nor journaling and overrides existing files.
816 * This function can be used to write to otherwise read-only foreign repos.
817 * This is intended for copying generated thumbnails into the repo.
819 * @param $src string File system path
820 * @param $dst string Virtual URL or storage path
821 * @return FileRepoStatus
823 final public function quickImport( $src, $dst ) {
824 return $this->quickImportBatch( array( array( $src, $dst ) ) );
828 * Purge a file from the repo. This does no locking nor journaling.
829 * This function can be used to write to otherwise read-only foreign repos.
830 * This is intended for purging thumbnails.
832 * @param $path string Virtual URL or storage path
833 * @return FileRepoStatus
835 final public function quickPurge( $path ) {
836 return $this->quickPurgeBatch( array( $path ) );
840 * Deletes a directory if empty.
841 * This function can be used to write to otherwise read-only foreign repos.
843 * @param $dir string Virtual URL (or storage path) of directory to clean
846 public function quickCleanDir( $dir ) {
847 $status = $this->newGood();
848 $status->merge( $this->backend
->clean(
849 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
855 * Import a batch of files from the local file system into the repo.
856 * This does no locking nor journaling and overrides existing files.
857 * This function can be used to write to otherwise read-only foreign repos.
858 * This is intended for copying generated thumbnails into the repo.
860 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
861 * @return FileRepoStatus
863 public function quickImportBatch( array $pairs ) {
864 $status = $this->newGood();
865 $operations = array();
866 foreach ( $pairs as $pair ) {
867 list ( $src, $dst ) = $pair;
868 $dst = $this->resolveToStoragePath( $dst );
869 $operations[] = array(
874 $status->merge( $this->initDirectory( dirname( $dst ) ) );
876 $status->merge( $this->backend
->doQuickOperations( $operations ) );
882 * Purge a batch of files from the repo.
883 * This function can be used to write to otherwise read-only foreign repos.
884 * This does no locking nor journaling and is intended for purging thumbnails.
886 * @param $paths Array List of virtual URLs or storage paths
887 * @return FileRepoStatus
889 public function quickPurgeBatch( array $paths ) {
890 $status = $this->newGood();
891 $operations = array();
892 foreach ( $paths as $path ) {
893 $operations[] = array(
895 'src' => $this->resolveToStoragePath( $path ),
896 'ignoreMissingSource' => true
899 $status->merge( $this->backend
->doQuickOperations( $operations ) );
905 * Pick a random name in the temp zone and store a file to it.
906 * Returns a FileRepoStatus object with the file Virtual URL in the value,
907 * file can later be disposed using FileRepo::freeTemp().
909 * @param $originalName String: the base name of the file as specified
910 * by the user. The file extension will be maintained.
911 * @param $srcPath String: the current location of the file.
912 * @return FileRepoStatus object with the URL in the value.
914 public function storeTemp( $originalName, $srcPath ) {
915 $this->assertWritableRepo(); // fail out if read-only
917 $date = gmdate( "YmdHis" );
918 $hashPath = $this->getHashPath( $originalName );
919 $dstRel = "{$hashPath}{$date}!{$originalName}";
920 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
922 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
923 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
929 * Concatenate a list of files into a target file location.
931 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
932 * @param $dstPath String Target file system path
933 * @param $flags Integer: bitwise combination of the following flags:
934 * self::DELETE_SOURCE Delete the source files
935 * @return FileRepoStatus
937 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
938 $this->assertWritableRepo(); // fail out if read-only
940 $status = $this->newGood();
943 $deleteOperations = array(); // post-concatenate ops
944 foreach ( $srcPaths as $srcPath ) {
945 // Resolve source to a storage path if virtual
946 $source = $this->resolveToStoragePath( $srcPath );
947 $sources[] = $source; // chunk to merge
948 if ( $flags & self
::DELETE_SOURCE
) {
949 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
953 // Concatenate the chunks into one FS file
954 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
955 $status->merge( $this->backend
->concatenate( $params ) );
956 if ( !$status->isOK() ) {
960 // Delete the sources if required
961 if ( $deleteOperations ) {
962 $opts = array( 'force' => true );
963 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
966 // Make sure status is OK, despite any $deleteOperations fatals
967 $status->setResult( true );
973 * Remove a temporary file or mark it for garbage collection
975 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
976 * @return Boolean: true on success, false on failure
978 public function freeTemp( $virtualUrl ) {
979 $this->assertWritableRepo(); // fail out if read-only
981 $temp = "mwrepo://{$this->name}/temp";
982 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
983 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
986 $path = $this->resolveVirtualUrl( $virtualUrl );
988 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
992 * Copy or move a file either from a storage path, virtual URL,
993 * or FS path, into this repository at the specified destination location.
995 * Returns a FileRepoStatus object. On success, the value contains "new" or
996 * "archived", to indicate whether the file was new with that name.
998 * @param $srcPath String: the source FS path, storage path, or URL
999 * @param $dstRel String: the destination relative path
1000 * @param $archiveRel String: the relative path where the existing file is to
1001 * be archived, if there is one. Relative to the public zone root.
1002 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1003 * that the source file should be deleted if possible
1004 * @return FileRepoStatus
1006 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1007 $this->assertWritableRepo(); // fail out if read-only
1009 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1010 if ( $status->successCount
== 0 ) {
1011 $status->ok
= false;
1013 if ( isset( $status->value
[0] ) ) {
1014 $status->value
= $status->value
[0];
1016 $status->value
= false;
1023 * Publish a batch of files
1025 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1026 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1027 * that the source files should be deleted if possible
1028 * @throws MWException
1029 * @return FileRepoStatus
1031 public function publishBatch( array $triplets, $flags = 0 ) {
1032 $this->assertWritableRepo(); // fail out if read-only
1034 $backend = $this->backend
; // convenience
1035 // Try creating directories
1036 $status = $this->initZones( 'public' );
1037 if ( !$status->isOK() ) {
1041 $status = $this->newGood( array() );
1043 $operations = array();
1044 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1045 // Validate each triplet and get the store operation...
1046 foreach ( $triplets as $i => $triplet ) {
1047 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1048 // Resolve source to a storage path if virtual
1049 $srcPath = $this->resolveToStoragePath( $srcPath );
1050 if ( !$this->validateFilename( $dstRel ) ) {
1051 throw new MWException( 'Validation error in $dstRel' );
1053 if ( !$this->validateFilename( $archiveRel ) ) {
1054 throw new MWException( 'Validation error in $archiveRel' );
1057 $publicRoot = $this->getZonePath( 'public' );
1058 $dstPath = "$publicRoot/$dstRel";
1059 $archivePath = "$publicRoot/$archiveRel";
1061 $dstDir = dirname( $dstPath );
1062 $archiveDir = dirname( $archivePath );
1063 // Abort immediately on directory creation errors since they're likely to be repetitive
1064 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1065 return $this->newFatal( 'directorycreateerror', $dstDir );
1067 if ( !$this->initDirectory($archiveDir )->isOK() ) {
1068 return $this->newFatal( 'directorycreateerror', $archiveDir );
1071 // Archive destination file if it exists
1072 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1073 // Check if the archive file exists
1074 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1075 // unlinks the destination file if it exists. DB-based synchronisation in
1076 // publishBatch's caller should prevent races. In Windows there's no
1077 // problem because the rename primitive fails if the destination exists.
1078 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1079 $operations[] = array( 'op' => 'null' );
1082 $operations[] = array(
1085 'dst' => $archivePath
1088 $status->value
[$i] = 'archived';
1090 $status->value
[$i] = 'new';
1092 // Copy (or move) the source file to the destination
1093 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1094 if ( $flags & self
::DELETE_SOURCE
) {
1095 $operations[] = array(
1101 $operations[] = array(
1107 } else { // FS source path
1108 $operations[] = array(
1113 if ( $flags & self
::DELETE_SOURCE
) {
1114 $sourceFSFilesToDelete[] = $srcPath;
1119 // Execute the operations for each triplet
1120 $opts = array( 'force' => true );
1121 $status->merge( $backend->doOperations( $operations, $opts ) );
1122 // Cleanup for disk source files...
1123 foreach ( $sourceFSFilesToDelete as $file ) {
1124 wfSuppressWarnings();
1125 unlink( $file ); // FS cleanup
1126 wfRestoreWarnings();
1133 * Creates a directory with the appropriate zone permissions.
1134 * Callers are responsible for doing read-only and "writable repo" checks.
1136 * @param $dir string Virtual URL (or storage path) of directory to clean
1139 protected function initDirectory( $dir ) {
1140 $path = $this->resolveToStoragePath( $dir );
1141 list( $b, $container, $r ) = FileBackend
::splitStoragePath( $path );
1143 $params = array( 'dir' => $path );
1144 if ( $container === $this->zones
['deleted']['container'] ) {
1145 # Take all available measures to prevent web accessibility of new deleted
1146 # directories, in case the user has not configured offline storage
1147 $params = array( 'noAccess' => true, 'noListing' => true ) +
$params;
1150 return $this->backend
->prepare( $params );
1154 * Deletes a directory if empty.
1156 * @param $dir string Virtual URL (or storage path) of directory to clean
1159 public function cleanDir( $dir ) {
1160 $this->assertWritableRepo(); // fail out if read-only
1162 $status = $this->newGood();
1163 $status->merge( $this->backend
->clean(
1164 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1170 * Checks existence of a a file
1172 * @param $file string Virtual URL (or storage path) of file to check
1175 public function fileExists( $file ) {
1176 $result = $this->fileExistsBatch( array( $file ) );
1181 * Checks existence of an array of files.
1183 * @param $files Array: Virtual URLs (or storage paths) of files to check
1184 * @return array|bool Either array of files and existence flags, or false
1186 public function fileExistsBatch( array $files ) {
1188 foreach ( $files as $key => $file ) {
1189 $file = $this->resolveToStoragePath( $file );
1190 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1196 * Move a file to the deletion archive.
1197 * If no valid deletion archive exists, this may either delete the file
1198 * or throw an exception, depending on the preference of the repository
1200 * @param $srcRel Mixed: relative path for the file to be deleted
1201 * @param $archiveRel Mixed: relative path for the archive location.
1202 * Relative to a private archive directory.
1203 * @return FileRepoStatus object
1205 public function delete( $srcRel, $archiveRel ) {
1206 $this->assertWritableRepo(); // fail out if read-only
1208 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1212 * Move a group of files to the deletion archive.
1214 * If no valid deletion archive is configured, this may either delete the
1215 * file or throw an exception, depending on the preference of the repository.
1217 * The overwrite policy is determined by the repository -- currently LocalRepo
1218 * assumes a naming scheme in the deleted zone based on content hash, as
1219 * opposed to the public zone which is assumed to be unique.
1221 * @param $sourceDestPairs Array of source/destination pairs. Each element
1222 * is a two-element array containing the source file path relative to the
1223 * public root in the first element, and the archive file path relative
1224 * to the deleted zone root in the second element.
1225 * @throws MWException
1226 * @return FileRepoStatus
1228 public function deleteBatch( array $sourceDestPairs ) {
1229 $this->assertWritableRepo(); // fail out if read-only
1231 // Try creating directories
1232 $status = $this->initZones( array( 'public', 'deleted' ) );
1233 if ( !$status->isOK() ) {
1237 $status = $this->newGood();
1239 $backend = $this->backend
; // convenience
1240 $operations = array();
1241 // Validate filenames and create archive directories
1242 foreach ( $sourceDestPairs as $pair ) {
1243 list( $srcRel, $archiveRel ) = $pair;
1244 if ( !$this->validateFilename( $srcRel ) ) {
1245 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1246 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1247 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1250 $publicRoot = $this->getZonePath( 'public' );
1251 $srcPath = "{$publicRoot}/$srcRel";
1253 $deletedRoot = $this->getZonePath( 'deleted' );
1254 $archivePath = "{$deletedRoot}/{$archiveRel}";
1255 $archiveDir = dirname( $archivePath ); // does not touch FS
1257 // Create destination directories
1258 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1259 return $this->newFatal( 'directorycreateerror', $archiveDir );
1262 $operations[] = array(
1265 'dst' => $archivePath,
1266 // We may have 2+ identical files being deleted,
1267 // all of which will map to the same destination file
1268 'overwriteSame' => true // also see bug 31792
1272 // Move the files by execute the operations for each pair.
1273 // We're now committed to returning an OK result, which will
1274 // lead to the files being moved in the DB also.
1275 $opts = array( 'force' => true );
1276 $status->merge( $backend->doOperations( $operations, $opts ) );
1282 * Delete files in the deleted directory if they are not referenced in the filearchive table
1286 public function cleanupDeletedBatch( array $storageKeys ) {
1287 $this->assertWritableRepo();
1291 * Get a relative path for a deletion archive key,
1292 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1294 * @param $key string
1297 public function getDeletedHashPath( $key ) {
1299 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1300 $path .= $key[$i] . '/';
1306 * If a path is a virtual URL, resolve it to a storage path.
1307 * Otherwise, just return the path as it is.
1309 * @param $path string
1311 * @throws MWException
1313 protected function resolveToStoragePath( $path ) {
1314 if ( $this->isVirtualUrl( $path ) ) {
1315 return $this->resolveVirtualUrl( $path );
1321 * Get a local FS copy of a file with a given virtual URL/storage path.
1322 * Temporary files may be purged when the file object falls out of scope.
1324 * @param $virtualUrl string
1325 * @return TempFSFile|null Returns null on failure
1327 public function getLocalCopy( $virtualUrl ) {
1328 $path = $this->resolveToStoragePath( $virtualUrl );
1329 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1333 * Get a local FS file with a given virtual URL/storage path.
1334 * The file is either an original or a copy. It should not be changed.
1335 * Temporary files may be purged when the file object falls out of scope.
1337 * @param $virtualUrl string
1338 * @return FSFile|null Returns null on failure.
1340 public function getLocalReference( $virtualUrl ) {
1341 $path = $this->resolveToStoragePath( $virtualUrl );
1342 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1346 * Get properties of a file with a given virtual URL/storage path.
1347 * Properties should ultimately be obtained via FSFile::getProps().
1349 * @param $virtualUrl string
1352 public function getFileProps( $virtualUrl ) {
1353 $path = $this->resolveToStoragePath( $virtualUrl );
1354 return $this->backend
->getFileProps( array( 'src' => $path ) );
1358 * Get the timestamp of a file with a given virtual URL/storage path
1360 * @param $virtualUrl string
1361 * @return string|bool False on failure
1363 public function getFileTimestamp( $virtualUrl ) {
1364 $path = $this->resolveToStoragePath( $virtualUrl );
1365 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1369 * Get the sha1 of a file with a given virtual URL/storage path
1371 * @param $virtualUrl string
1372 * @return string|bool
1374 public function getFileSha1( $virtualUrl ) {
1375 $path = $this->resolveToStoragePath( $virtualUrl );
1376 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1380 return $tmpFile->getSha1Base36();
1384 * Attempt to stream a file with the given virtual URL/storage path
1386 * @param $virtualUrl string
1387 * @param $headers Array Additional HTTP headers to send on success
1388 * @return bool Success
1390 public function streamFile( $virtualUrl, $headers = array() ) {
1391 $path = $this->resolveToStoragePath( $virtualUrl );
1392 $params = array( 'src' => $path, 'headers' => $headers );
1393 return $this->backend
->streamFile( $params )->isOK();
1397 * Call a callback function for every public regular file in the repository.
1398 * This only acts on the current version of files, not any old versions.
1399 * May use either the database or the filesystem.
1401 * @param $callback Array|string
1404 public function enumFiles( $callback ) {
1405 $this->enumFilesInStorage( $callback );
1409 * Call a callback function for every public file in the repository.
1410 * May use either the database or the filesystem.
1412 * @param $callback Array|string
1415 protected function enumFilesInStorage( $callback ) {
1416 $publicRoot = $this->getZonePath( 'public' );
1417 $numDirs = 1 << ( $this->hashLevels
* 4 );
1418 // Use a priori assumptions about directory structure
1419 // to reduce the tree height of the scanning process.
1420 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1421 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1422 $path = $publicRoot;
1423 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1424 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1426 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1427 foreach ( $iterator as $name ) {
1428 // Each item returned is a public file
1429 call_user_func( $callback, "{$path}/{$name}" );
1435 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1437 * @param $filename string
1440 public function validateFilename( $filename ) {
1441 if ( strval( $filename ) == '' ) {
1444 return FileBackend
::isPathTraversalFree( $filename );
1448 * Get a callback function to use for cleaning error message parameters
1452 function getErrorCleanupFunction() {
1453 switch ( $this->pathDisclosureProtection
) {
1455 case 'simple': // b/c
1456 $callback = array( $this, 'passThrough' );
1458 default: // 'paranoid'
1459 $callback = array( $this, 'paranoidClean' );
1465 * Path disclosure protection function
1467 * @param $param string
1470 function paranoidClean( $param ) {
1475 * Path disclosure protection function
1477 * @param $param string
1480 function passThrough( $param ) {
1485 * Create a new fatal error
1487 * @return FileRepoStatus
1489 public function newFatal( $message /*, parameters...*/ ) {
1490 $params = func_get_args();
1491 array_unshift( $params, $this );
1492 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1496 * Create a new good result
1498 * @param $value null|string
1499 * @return FileRepoStatus
1501 public function newGood( $value = null ) {
1502 return FileRepoStatus
::newGood( $this, $value );
1506 * Checks if there is a redirect named as $title. If there is, return the
1507 * title object. If not, return false.
1510 * @param $title Title of image
1513 public function checkRedirect( Title
$title ) {
1518 * Invalidates image redirect cache related to that image
1519 * Doesn't do anything for repositories that don't support image redirects.
1522 * @param $title Title of image
1524 public function invalidateImageRedirect( Title
$title ) {}
1527 * Get the human-readable name of the repo
1531 public function getDisplayName() {
1532 // We don't name our own repo, return nothing
1533 if ( $this->isLocal() ) {
1536 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1537 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1541 * Returns true if this the local file repository.
1545 public function isLocal() {
1546 return $this->getName() == 'local';
1550 * Get a key on the primary cache for this repository.
1551 * Returns false if the repository's cache is not accessible at this site.
1552 * The parameters are the parts of the key, as for wfMemcKey().
1557 public function getSharedCacheKey( /*...*/ ) {
1562 * Get a key for this repo in the local cache domain. These cache keys are
1563 * not shared with remote instances of the repo.
1564 * The parameters are the parts of the key, as for wfMemcKey().
1568 public function getLocalCacheKey( /*...*/ ) {
1569 $args = func_get_args();
1570 array_unshift( $args, 'filerepo', $this->getName() );
1571 return call_user_func_array( 'wfMemcKey', $args );
1575 * Get an temporary FileRepo associated with this repo.
1576 * Files will be created in the temp zone of this repo and
1577 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1578 * It will have the same backend as this repo.
1580 * @return TempFileRepo
1582 public function getTempRepo() {
1583 return new TempFileRepo( array(
1584 'name' => "{$this->name}-temp",
1585 'backend' => $this->backend
,
1588 'container' => $this->zones
['temp']['container'],
1589 'directory' => $this->zones
['temp']['directory']
1592 'container' => $this->zones
['thumb']['container'],
1593 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1595 : $this->zones
['thumb']['directory'] . '/temp'
1598 'url' => $this->getZoneUrl( 'temp' ),
1599 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1600 'hashLevels' => $this->hashLevels
// performance
1605 * Get an UploadStash associated with this repo.
1607 * @return UploadStash
1609 public function getUploadStash() {
1610 return new UploadStash( $this );
1614 * Throw an exception if this repo is read-only by design.
1615 * This does not and should not check getReadOnlyReason().
1618 * @throws MWException
1620 protected function assertWritableRepo() {}
1624 * FileRepo for temporary files created via FileRepo::getTempRepo()
1626 class TempFileRepo
extends FileRepo
{
1627 public function getTempRepo() {
1628 throw new MWException( "Cannot get a temp repo from a temp repo." );