7e92b4db12323f6d8b53c46dc454bf20268513f9
3 * Base code for file repositories.
10 * Base class for file repositories
17 const DELETE_SOURCE
= 1;
19 const OVERWRITE_SAME
= 4;
20 const SKIP_LOCKING
= 8;
22 /** @var FileBackendBase */
24 /** @var Array Map of zones to config */
25 protected $zones = array();
27 var $thumbScriptUrl, $transformVia404;
28 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
29 var $fetchDescription, $initialCapital;
30 var $pathDisclosureProtection = 'simple'; // 'paranoid'
31 var $descriptionCacheExpiry, $url, $thumbUrl;
32 var $hashLevels, $deletedHashLevels;
35 * Factory functions for creating new files
36 * Override these in the base class
38 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
39 var $oldFileFactory = false;
40 var $fileFactoryKey = false, $oldFileFactoryKey = false;
42 function __construct( $info ) {
44 $this->name
= $info['name'];
45 if ( $info['backend'] instanceof FileBackendBase
) {
46 $this->backend
= $info['backend']; // useful for testing
48 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
51 // Optional settings that can have no value
52 $optionalSettings = array(
53 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
54 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
57 foreach ( $optionalSettings as $var ) {
58 if ( isset( $info[$var] ) ) {
59 $this->$var = $info[$var];
63 // Optional settings that have a default
64 $this->initialCapital
= isset( $info['initialCapital'] )
65 ?
$info['initialCapital']
66 : MWNamespace
::isCapitalized( NS_FILE
);
67 $this->url
= isset( $info['url'] )
69 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
70 if ( isset( $info['thumbUrl'] ) ) {
71 $this->thumbUrl
= $info['thumbUrl'];
73 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
75 $this->hashLevels
= isset( $info['hashLevels'] )
78 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
79 ?
$info['deletedHashLevels']
81 $this->transformVia404
= !empty( $info['transformVia404'] );
82 $this->zones
= isset( $info['zones'] )
85 // Give defaults for the basic zones...
86 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
87 if ( !isset( $this->zones
[$zone] ) ) {
88 $this->zones
[$zone] = array(
89 'container' => "{$this->name}-{$zone}",
90 'directory' => '' // container root
97 * Get the file backend instance
99 * @return FileBackendBase
101 public function getBackend() {
102 return $this->backend
;
106 * Prepare a single zone or list of zones for usage.
107 * See initDeletedDir() for additional setup needed for the 'deleted' zone.
109 * @param $doZones Array Only do a particular zones
112 protected function initZones( $doZones = array() ) {
113 $status = $this->newGood();
114 foreach ( (array)$doZones as $zone ) {
115 $root = $this->getZonePath( $zone );
116 if ( $root === null ) {
117 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
124 * Take all available measures to prevent web accessibility of new deleted
125 * directories, in case the user has not configured offline storage
130 protected function initDeletedDir( $dir ) {
131 $this->backend
->secure( // prevent web access & dir listings
132 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
136 * Determine if a string is an mwrepo:// URL
141 public static function isVirtualUrl( $url ) {
142 return substr( $url, 0, 9 ) == 'mwrepo://';
146 * Get a URL referring to this repository, with the private mwrepo protocol.
147 * The suffix, if supplied, is considered to be unencoded, and will be
148 * URL-encoded before being returned.
150 * @param $suffix string
153 public function getVirtualUrl( $suffix = false ) {
154 $path = 'mwrepo://' . $this->name
;
155 if ( $suffix !== false ) {
156 $path .= '/' . rawurlencode( $suffix );
162 * Get the URL corresponding to one of the four basic zones
164 * @param $zone String: one of: public, deleted, temp, thumb
165 * @return String or false
167 public function getZoneUrl( $zone ) {
172 return "{$this->url}/temp";
174 return false; // no public URL
176 return $this->thumbUrl
;
183 * Get the backend storage path corresponding to a virtual URL
188 function resolveVirtualUrl( $url ) {
189 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
190 throw new MWException( __METHOD__
.': unknown protocol' );
192 $bits = explode( '/', substr( $url, 9 ), 3 );
193 if ( count( $bits ) != 3 ) {
194 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
196 list( $repo, $zone, $rel ) = $bits;
197 if ( $repo !== $this->name
) {
198 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
200 $base = $this->getZonePath( $zone );
202 throw new MWException( __METHOD__
.": invalid zone: $zone" );
204 return $base . '/' . rawurldecode( $rel );
208 * The the storage container and base path of a zone
210 * @param $zone string
211 * @return Array (container, base path) or (null, null)
213 protected function getZoneLocation( $zone ) {
214 if ( !isset( $this->zones
[$zone] ) ) {
215 return array( null, null ); // bogus
217 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
221 * Get the storage path corresponding to one of the zones
223 * @param $zone string
224 * @return string|null
226 public function getZonePath( $zone ) {
227 list( $container, $base ) = $this->getZoneLocation( $zone );
228 if ( $container === null ||
$base === null ) {
231 $backendName = $this->backend
->getName();
232 if ( $base != '' ) { // may not be set
235 return "mwstore://$backendName/{$container}{$base}";
239 * Create a new File object from the local repository
241 * @param $title Mixed: Title object or string
242 * @param $time Mixed: Time at which the image was uploaded.
243 * If this is specified, the returned object will be an
244 * instance of the repository's old file class instead of a
245 * current file. Repositories not supporting version control
246 * should return false if this parameter is set.
247 * @return File|null A File, or null if passed an invalid Title
249 public function newFile( $title, $time = false ) {
250 $title = File
::normalizeTitle( $title );
255 if ( $this->oldFileFactory
) {
256 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
261 return call_user_func( $this->fileFactory
, $title, $this );
266 * Find an instance of the named file created at the specified time
267 * Returns false if the file does not exist. Repositories not supporting
268 * version control should return false if the time is specified.
270 * @param $title Mixed: Title object or string
271 * @param $options array Associative array of options:
272 * time: requested time for an archived image, or false for the
273 * current version. An image object will be returned which was
274 * created at the specified time.
276 * ignoreRedirect: If true, do not follow file redirects
278 * private: If true, return restricted (deleted) files if the current
279 * user is allowed to view them. Otherwise, such files will not
283 public function findFile( $title, $options = array() ) {
284 $title = File
::normalizeTitle( $title );
288 $time = isset( $options['time'] ) ?
$options['time'] : false;
289 # First try the current version of the file to see if it precedes the timestamp
290 $img = $this->newFile( $title );
294 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
297 # Now try an old version of the file
298 if ( $time !== false ) {
299 $img = $this->newFile( $title, $time );
300 if ( $img && $img->exists() ) {
301 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
302 return $img; // always OK
303 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
310 if ( !empty( $options['ignoreRedirect'] ) ) {
313 $redir = $this->checkRedirect( $title );
314 if ( $redir && $title->getNamespace() == NS_FILE
) {
315 $img = $this->newFile( $redir );
319 if ( $img->exists() ) {
320 $img->redirectedFrom( $title->getDBkey() );
328 * Find many files at once.
330 * @param $items An array of titles, or an array of findFile() options with
331 * the "title" option giving the title. Example:
333 * $findItem = array( 'title' => $title, 'private' => true );
334 * $findBatch = array( $findItem );
335 * $repo->findFiles( $findBatch );
338 public function findFiles( $items ) {
340 foreach ( $items as $item ) {
341 if ( is_array( $item ) ) {
342 $title = $item['title'];
344 unset( $options['title'] );
349 $file = $this->findFile( $title, $options );
351 $result[$file->getTitle()->getDBkey()] = $file;
358 * Find an instance of the file with this key, created at the specified time
359 * Returns false if the file does not exist. Repositories not supporting
360 * version control should return false if the time is specified.
362 * @param $sha1 String base 36 SHA-1 hash
363 * @param $options Option array, same as findFile().
366 public function findFileFromKey( $sha1, $options = array() ) {
367 $time = isset( $options['time'] ) ?
$options['time'] : false;
369 # First try to find a matching current version of a file...
370 if ( $this->fileFactoryKey
) {
371 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
373 return false; // find-by-sha1 not supported
375 if ( $img && $img->exists() ) {
378 # Now try to find a matching old version of a file...
379 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
380 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
381 if ( $img && $img->exists() ) {
382 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
383 return $img; // always OK
384 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
393 * Get an array or iterator of file objects for files that have a given
394 * SHA-1 content hash.
398 public function findBySha1( $hash ) {
403 * Get the public root URL of the repository
405 * @return string|false
407 public function getRootUrl() {
412 * Returns true if the repository uses a multi-level directory structure
416 public function isHashed() {
417 return (bool)$this->hashLevels
;
421 * Get the URL of thumb.php
425 public function getThumbScriptUrl() {
426 return $this->thumbScriptUrl
;
430 * Returns true if the repository can transform files via a 404 handler
434 public function canTransformVia404() {
435 return $this->transformVia404
;
439 * Get the name of an image from its title object
441 * @param $title Title
443 public function getNameFromTitle( Title
$title ) {
445 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
446 $name = $title->getUserCaseDBKey();
447 if ( $this->initialCapital
) {
448 $name = $wgContLang->ucfirst( $name );
451 $name = $title->getDBkey();
457 * Get the public zone root storage directory of the repository
461 public function getRootDirectory() {
462 return $this->getZonePath( 'public' );
466 * Get a relative path including trailing slash, e.g. f/fa/
467 * If the repo is not hashed, returns an empty string
469 * @param $name string
472 public function getHashPath( $name ) {
473 return self
::getHashPathForLevel( $name, $this->hashLevels
);
481 static function getHashPathForLevel( $name, $levels ) {
482 if ( $levels == 0 ) {
485 $hash = md5( $name );
487 for ( $i = 1; $i <= $levels; $i++
) {
488 $path .= substr( $hash, 0, $i ) . '/';
495 * Get the number of hash directory levels
499 public function getHashLevels() {
500 return $this->hashLevels
;
504 * Get the name of this repository, as specified by $info['name]' to the constructor
508 public function getName() {
513 * Make an url to this repo
515 * @param $query mixed Query string to append
516 * @param $entry string Entry point; defaults to index
517 * @return string|false
519 public function makeUrl( $query = '', $entry = 'index' ) {
520 if ( isset( $this->scriptDirUrl
) ) {
521 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
522 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
528 * Get the URL of an image description page. May return false if it is
529 * unknown or not applicable. In general this should only be called by the
530 * File class, since it may return invalid results for certain kinds of
531 * repositories. Use File::getDescriptionUrl() in user code.
533 * In particular, it uses the article paths as specified to the repository
534 * constructor, whereas local repositories use the local Title functions.
536 * @param $name string
539 public function getDescriptionUrl( $name ) {
540 $encName = wfUrlencode( $name );
541 if ( !is_null( $this->descBaseUrl
) ) {
542 # "http://example.com/wiki/Image:"
543 return $this->descBaseUrl
. $encName;
545 if ( !is_null( $this->articleUrl
) ) {
546 # "http://example.com/wiki/$1"
548 # We use "Image:" as the canonical namespace for
549 # compatibility across all MediaWiki versions.
550 return str_replace( '$1',
551 "Image:$encName", $this->articleUrl
);
553 if ( !is_null( $this->scriptDirUrl
) ) {
554 # "http://example.com/w"
556 # We use "Image:" as the canonical namespace for
557 # compatibility across all MediaWiki versions,
558 # and just sort of hope index.php is right. ;)
559 return $this->makeUrl( "title=Image:$encName" );
565 * Get the URL of the content-only fragment of the description page. For
566 * MediaWiki this means action=render. This should only be called by the
567 * repository's file class, since it may return invalid results. User code
568 * should use File::getDescriptionText().
570 * @param $name String: name of image to fetch
571 * @param $lang String: language to fetch it in, if any.
574 public function getDescriptionRenderUrl( $name, $lang = null ) {
575 $query = 'action=render';
576 if ( !is_null( $lang ) ) {
577 $query .= '&uselang=' . $lang;
579 if ( isset( $this->scriptDirUrl
) ) {
580 return $this->makeUrl(
582 wfUrlencode( 'Image:' . $name ) .
585 $descUrl = $this->getDescriptionUrl( $name );
587 return wfAppendQuery( $descUrl, $query );
595 * Get the URL of the stylesheet to apply to description pages
597 * @return string|false
599 public function getDescriptionStylesheetUrl() {
600 if ( isset( $this->scriptDirUrl
) ) {
601 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
602 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
608 * Store a file to a given destination.
610 * @param $srcPath String: source FS path, storage path, or virtual URL
611 * @param $dstZone String: destination zone
612 * @param $dstRel String: destination relative path
613 * @param $flags Integer: bitwise combination of the following flags:
614 * self::DELETE_SOURCE Delete the source file after upload
615 * self::OVERWRITE Overwrite an existing destination file instead of failing
616 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
617 * same contents as the source
618 * self::SKIP_LOCKING Skip any file locking when doing the store
619 * @return FileRepoStatus
621 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
622 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
623 if ( $status->successCount
== 0 ) {
630 * Store a batch of files
632 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
633 * @param $flags Integer: bitwise combination of the following flags:
634 * self::DELETE_SOURCE Delete the source file after upload
635 * self::OVERWRITE Overwrite an existing destination file instead of failing
636 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
637 * same contents as the source
638 * self::SKIP_LOCKING Skip any file locking when doing the store
639 * @return FileRepoStatus
641 public function storeBatch( $triplets, $flags = 0 ) {
642 $backend = $this->backend
; // convenience
644 $status = $this->newGood();
646 $operations = array();
647 $sourceFSFilesToDelete = array(); // cleanup for disk source files
648 // Validate each triplet and get the store operation...
649 foreach ( $triplets as $triplet ) {
650 list( $srcPath, $dstZone, $dstRel ) = $triplet;
652 // Resolve destination path
653 $root = $this->getZonePath( $dstZone );
655 throw new MWException( "Invalid zone: $dstZone" );
657 if ( !$this->validateFilename( $dstRel ) ) {
658 throw new MWException( 'Validation error in $dstRel' );
660 $dstPath = "$root/$dstRel";
661 $dstDir = dirname( $dstPath );
663 // Create destination directories for this triplet
664 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
665 return $this->newFatal( 'directorycreateerror', $dstDir );
668 if ( $dstZone == 'deleted' ) {
669 $this->initDeletedDir( $dstDir );
672 // Resolve source to a storage path if virtual
673 if ( self
::isVirtualUrl( $srcPath ) ) {
674 $srcPath = $this->resolveVirtualUrl( $srcPath );
677 // Get the appropriate file operation
678 if ( FileBackend
::isStoragePath( $srcPath ) ) {
679 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
682 if ( $flags & self
::DELETE_SOURCE
) {
683 $sourceFSFilesToDelete[] = $srcPath;
686 $operations[] = array(
690 'overwrite' => $flags & self
::OVERWRITE
,
691 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
695 // Execute the store operation for each triplet
696 $opts = array( 'force' => true );
697 if ( $flags & self
::SKIP_LOCKING
) {
698 $opts['nonLocking'] = true;
700 $status->merge( $backend->doOperations( $operations, $opts ) );
701 // Cleanup for disk source files...
702 foreach ( $sourceFSFilesToDelete as $file ) {
703 wfSuppressWarnings();
704 unlink( $file ); // FS cleanup
712 * Deletes a batch of files.
713 * Each file can be a (zone, rel) pair, virtual url, storage path, or FS path.
714 * It will try to delete each file, but ignores any errors that may occur.
716 * @param $pairs array List of files to delete
719 public function cleanupBatch( $files ) {
720 $operations = array();
721 $sourceFSFilesToDelete = array(); // cleanup for disk source files
722 foreach ( $files as $file ) {
723 if ( is_array( $file ) ) {
724 // This is a pair, extract it
725 list( $zone, $rel ) = $file;
726 $root = $this->getZonePath( $zone );
727 $path = "$root/$rel";
729 if ( self
::isVirtualUrl( $file ) ) {
730 // This is a virtual url, resolve it
731 $path = $this->resolveVirtualUrl( $file );
733 // This is a full file name
737 // Get a file operation if needed
738 if ( FileBackend
::isStoragePath( $path ) ) {
739 $operations[] = array(
744 $sourceFSFilesToDelete[] = $path;
747 // Actually delete files from storage...
748 $opts = array( 'force' => true );
749 $this->backend
->doOperations( $operations, $opts );
750 // Cleanup for disk source files...
751 foreach ( $sourceFSFilesToDelete as $file ) {
752 wfSuppressWarnings();
753 unlink( $file ); // FS cleanup
759 * Pick a random name in the temp zone and store a file to it.
760 * Returns a FileRepoStatus object with the URL in the value.
762 * @param $originalName String: the base name of the file as specified
763 * by the user. The file extension will be maintained.
764 * @param $srcPath String: the current location of the file.
765 * @return FileRepoStatus object with the URL in the value.
767 public function storeTemp( $originalName, $srcPath ) {
768 $date = gmdate( "YmdHis" );
769 $hashPath = $this->getHashPath( $originalName );
770 $dstRel = "{$hashPath}{$date}!{$originalName}";
771 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
773 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
774 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
779 * Concatenate a list of files into a target file location.
781 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
782 * @param $dstPath String Target file system path
783 * @param $flags Integer: bitwise combination of the following flags:
784 * self::DELETE_SOURCE Delete the source files
785 * @return FileRepoStatus
787 function concatenate( $srcPaths, $dstPath, $flags = 0 ) {
788 $status = $this->newGood();
791 $deleteOperations = array(); // post-concatenate ops
792 foreach ( $srcPaths as $srcPath ) {
793 // Resolve source to a storage path if virtual
794 $source = $this->resolveToStoragePath( $srcPath );
795 $sources[] = $source; // chunk to merge
796 if ( $flags & self
::DELETE_SOURCE
) {
797 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
801 // Concatenate the chunks into one FS file
802 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
803 $status->merge( $this->backend
->concatenate( $params ) );
804 if ( !$status->isOK() ) {
808 // Delete the sources if required
809 if ( $deleteOperations ) {
810 $opts = array( 'force' => true );
811 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
814 // Make sure status is OK, despite any $deleteOperations fatals
815 $status->setResult( true );
821 * Remove a temporary file or mark it for garbage collection
823 * @param $virtualUrl String: the virtual URL returned by storeTemp
824 * @return Boolean: true on success, false on failure
826 public function freeTemp( $virtualUrl ) {
827 $temp = "mwrepo://{$this->name}/temp";
828 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
829 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
832 $path = $this->resolveVirtualUrl( $virtualUrl );
833 $op = array( 'op' => 'delete', 'src' => $path );
834 $status = $this->backend
->doOperation( $op );
835 return $status->isOK();
839 * Copy or move a file either from a storage path, virtual URL,
840 * or FS path, into this repository at the specified destination location.
842 * Returns a FileRepoStatus object. On success, the value contains "new" or
843 * "archived", to indicate whether the file was new with that name.
845 * @param $srcPath String: the source FS path, storage path, or URL
846 * @param $dstRel String: the destination relative path
847 * @param $archiveRel String: the relative path where the existing file is to
848 * be archived, if there is one. Relative to the public zone root.
849 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
850 * that the source file should be deleted if possible
852 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
853 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
854 if ( $status->successCount
== 0 ) {
857 if ( isset( $status->value
[0] ) ) {
858 $status->value
= $status->value
[0];
860 $status->value
= false;
866 * Publish a batch of files
868 * @param $triplets Array: (source, dest, archive) triplets as per publish()
869 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
870 * that the source files should be deleted if possible
871 * @return FileRepoStatus
873 public function publishBatch( $triplets, $flags = 0 ) {
874 $backend = $this->backend
; // convenience
876 // Try creating directories
877 $status = $this->initZones( 'public' );
878 if ( !$status->isOK() ) {
882 $status = $this->newGood( array() );
884 $operations = array();
885 $sourceFSFilesToDelete = array(); // cleanup for disk source files
886 // Validate each triplet and get the store operation...
887 foreach ( $triplets as $i => $triplet ) {
888 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
889 // Resolve source to a storage path if virtual
890 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
891 $srcPath = $this->resolveVirtualUrl( $srcPath );
893 if ( !$this->validateFilename( $dstRel ) ) {
894 throw new MWException( 'Validation error in $dstRel' );
896 if ( !$this->validateFilename( $archiveRel ) ) {
897 throw new MWException( 'Validation error in $archiveRel' );
900 $publicRoot = $this->getZonePath( 'public' );
901 $dstPath = "$publicRoot/$dstRel";
902 $archivePath = "$publicRoot/$archiveRel";
904 $dstDir = dirname( $dstPath );
905 $archiveDir = dirname( $archivePath );
906 // Abort immediately on directory creation errors since they're likely to be repetitive
907 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
908 return $this->newFatal( 'directorycreateerror', $dstDir );
910 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
911 return $this->newFatal( 'directorycreateerror', $archiveDir );
914 // Archive destination file if it exists
915 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
916 // Check if the archive file exists
917 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
918 // unlinks the destination file if it exists. DB-based synchronisation in
919 // publishBatch's caller should prevent races. In Windows there's no
920 // problem because the rename primitive fails if the destination exists.
921 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
922 $operations[] = array( 'op' => 'null' );
925 $operations[] = array(
928 'dst' => $archivePath
931 $status->value
[$i] = 'archived';
933 $status->value
[$i] = 'new';
935 // Copy (or move) the source file to the destination
936 if ( FileBackend
::isStoragePath( $srcPath ) ) {
937 if ( $flags & self
::DELETE_SOURCE
) {
938 $operations[] = array(
944 $operations[] = array(
950 } else { // FS source path
951 $operations[] = array(
956 if ( $flags & self
::DELETE_SOURCE
) {
957 $sourceFSFilesToDelete[] = $srcPath;
962 // Execute the operations for each triplet
963 $opts = array( 'force' => true );
964 $status->merge( $backend->doOperations( $operations, $opts ) );
965 // Cleanup for disk source files...
966 foreach ( $sourceFSFilesToDelete as $file ) {
967 wfSuppressWarnings();
968 unlink( $file ); // FS cleanup
976 * Checks existence of a a file
978 * @param $file Virtual URL (or storage path) of file to check
979 * @param $flags Integer: bitwise combination of the following flags:
980 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
983 public function fileExists( $file, $flags = 0 ) {
984 $result = $this->fileExistsBatch( array( $file ), $flags );
989 * Checks existence of an array of files.
991 * @param $files Array: Virtual URLs (or storage paths) of files to check
992 * @param $flags Integer: bitwise combination of the following flags:
993 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
994 * @return Either array of files and existence flags, or false
996 public function fileExistsBatch( $files, $flags = 0 ) {
998 foreach ( $files as $key => $file ) {
999 if ( self
::isVirtualUrl( $file ) ) {
1000 $file = $this->resolveVirtualUrl( $file );
1002 if ( FileBackend
::isStoragePath( $file ) ) {
1003 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1005 if ( $flags & self
::FILES_ONLY
) {
1006 $result[$key] = is_file( $file ); // FS only
1008 $result[$key] = file_exists( $file ); // FS only
1017 * Move a file to the deletion archive.
1018 * If no valid deletion archive exists, this may either delete the file
1019 * or throw an exception, depending on the preference of the repository
1021 * @param $srcRel Mixed: relative path for the file to be deleted
1022 * @param $archiveRel Mixed: relative path for the archive location.
1023 * Relative to a private archive directory.
1024 * @return FileRepoStatus object
1026 public function delete( $srcRel, $archiveRel ) {
1027 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1031 * Move a group of files to the deletion archive.
1033 * If no valid deletion archive is configured, this may either delete the
1034 * file or throw an exception, depending on the preference of the repository.
1036 * The overwrite policy is determined by the repository -- currently LocalRepo
1037 * assumes a naming scheme in the deleted zone based on content hash, as
1038 * opposed to the public zone which is assumed to be unique.
1040 * @param $sourceDestPairs Array of source/destination pairs. Each element
1041 * is a two-element array containing the source file path relative to the
1042 * public root in the first element, and the archive file path relative
1043 * to the deleted zone root in the second element.
1044 * @return FileRepoStatus
1046 public function deleteBatch( $sourceDestPairs ) {
1047 $backend = $this->backend
; // convenience
1049 // Try creating directories
1050 $status = $this->initZones( array( 'public', 'deleted' ) );
1051 if ( !$status->isOK() ) {
1055 $status = $this->newGood();
1057 $operations = array();
1058 // Validate filenames and create archive directories
1059 foreach ( $sourceDestPairs as $pair ) {
1060 list( $srcRel, $archiveRel ) = $pair;
1061 if ( !$this->validateFilename( $srcRel ) ) {
1062 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1064 if ( !$this->validateFilename( $archiveRel ) ) {
1065 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1068 $publicRoot = $this->getZonePath( 'public' );
1069 $srcPath = "{$publicRoot}/$srcRel";
1071 $deletedRoot = $this->getZonePath( 'deleted' );
1072 $archivePath = "{$deletedRoot}/{$archiveRel}";
1073 $archiveDir = dirname( $archivePath ); // does not touch FS
1075 // Create destination directories
1076 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1077 return $this->newFatal( 'directorycreateerror', $archiveDir );
1079 $this->initDeletedDir( $archiveDir );
1081 $operations[] = array(
1084 'dst' => $archivePath,
1085 // We may have 2+ identical files being deleted,
1086 // all of which will map to the same destination file
1087 'overwriteSame' => true
1091 // Move the files by execute the operations for each pair.
1092 // We're now committed to returning an OK result, which will
1093 // lead to the files being moved in the DB also.
1094 $opts = array( 'force' => true );
1095 $status->merge( $backend->doOperations( $operations, $opts ) );
1101 * Get a relative path for a deletion archive key,
1102 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1106 public function getDeletedHashPath( $key ) {
1108 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1109 $path .= $key[$i] . '/';
1115 * If a path is a virtual URL, resolve it to a storage path.
1116 * Otherwise, just return the path as it is.
1118 * @param $path string
1120 * @throws MWException
1122 protected function resolveToStoragePath( $path ) {
1123 if ( $this->isVirtualUrl( $path ) ) {
1124 return $this->resolveVirtualUrl( $path );
1130 * Get a local FS copy of a file with a given virtual URL/storage path.
1131 * Temporary files may be purged when the file object falls out of scope.
1133 * @param $virtualUrl string
1134 * @return TempFSFile|null Returns null on failure
1136 public function getLocalCopy( $virtualUrl ) {
1137 $path = $this->resolveToStoragePath( $virtualUrl );
1138 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1142 * Get a local FS file with a given virtual URL/storage path.
1143 * The file is either an original or a copy. It should not be changed.
1144 * Temporary files may be purged when the file object falls out of scope.
1146 * @param $virtualUrl string
1147 * @return FSFile|null Returns null on failure.
1149 public function getLocalReference( $virtualUrl ) {
1150 $path = $this->resolveToStoragePath( $virtualUrl );
1151 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1155 * Get properties of a file with a given virtual URL/storage path.
1156 * Properties should ultimately be obtained via FSFile::getProps().
1158 * @param $virtualUrl string
1161 public function getFileProps( $virtualUrl ) {
1162 $path = $this->resolveToStoragePath( $virtualUrl );
1163 return $this->backend
->getFileProps( array( 'src' => $path ) );
1167 * Get the timestamp of a file with a given virtual URL/storage path
1169 * @param $virtualUrl string
1170 * @return string|false
1172 public function getFileTimestamp( $virtualUrl ) {
1173 $path = $this->resolveToStoragePath( $virtualUrl );
1174 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1178 * Get the sha1 of a file with a given virtual URL/storage path
1180 * @param $virtualUrl string
1181 * @return string|false
1183 public function getFileSha1( $virtualUrl ) {
1184 $path = $this->resolveToStoragePath( $virtualUrl );
1185 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1189 return $tmpFile->getSha1Base36();
1193 * Attempt to stream a file with the given virtual URL/storage path
1195 * @param $virtualUrl string
1196 * @param $headers Array Additional HTTP headers to send on success
1197 * @return bool Success
1199 public function streamFile( $virtualUrl, $headers = array() ) {
1200 $path = $this->resolveToStoragePath( $virtualUrl );
1201 $params = array( 'src' => $path, 'headers' => $headers );
1202 return $this->backend
->streamFile( $params )->isOK();
1206 * Call a callback function for every public regular file in the repository.
1207 * This only acts on the current version of files, not any old versions.
1208 * May use either the database or the filesystem.
1210 * @param $callback Array|string
1213 public function enumFiles( $callback ) {
1214 $this->enumFilesInStorage( $callback );
1218 * Call a callback function for every public file in the repository.
1219 * May use either the database or the filesystem.
1221 * @param $callback Array|string
1224 protected function enumFilesInStorage( $callback ) {
1225 $publicRoot = $this->getZonePath( 'public' );
1226 $numDirs = 1 << ( $this->hashLevels
* 4 );
1227 // Use a priori assumptions about directory structure
1228 // to reduce the tree height of the scanning process.
1229 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1230 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1231 $path = $publicRoot;
1232 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1233 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1235 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1236 foreach ( $iterator as $name ) {
1237 // Each item returned is a public file
1238 call_user_func( $callback, "{$path}/{$name}" );
1244 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1246 * @param $filename string
1249 public function validateFilename( $filename ) {
1250 if ( strval( $filename ) == '' ) {
1253 if ( wfIsWindows() ) {
1254 $filename = strtr( $filename, '\\', '/' );
1257 * Use the same traversal protection as Title::secureAndSplit()
1259 if ( strpos( $filename, '.' ) !== false &&
1260 ( $filename === '.' ||
$filename === '..' ||
1261 strpos( $filename, './' ) === 0 ||
1262 strpos( $filename, '../' ) === 0 ||
1263 strpos( $filename, '/./' ) !== false ||
1264 strpos( $filename, '/../' ) !== false ) )
1273 * Get a callback function to use for cleaning error message parameters
1277 function getErrorCleanupFunction() {
1278 switch ( $this->pathDisclosureProtection
) {
1280 $callback = array( $this, 'passThrough' );
1283 $callback = array( $this, 'simpleClean' );
1285 default: // 'paranoid'
1286 $callback = array( $this, 'paranoidClean' );
1292 * Path disclosure protection function
1294 * @param $param string
1297 function paranoidClean( $param ) {
1302 * Path disclosure protection function
1304 * @param $param string
1307 function simpleClean( $param ) {
1309 if ( !isset( $this->simpleCleanPairs
) ) {
1310 $this->simpleCleanPairs
= array(
1311 $IP => '$IP', // sanity
1314 return strtr( $param, $this->simpleCleanPairs
);
1318 * Path disclosure protection function
1320 * @param $param string
1323 function passThrough( $param ) {
1328 * Create a new fatal error
1330 * @return FileRepoStatus
1332 function newFatal( $message /*, parameters...*/ ) {
1333 $params = func_get_args();
1334 array_unshift( $params, $this );
1335 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1339 * Create a new good result
1341 * @return FileRepoStatus
1343 function newGood( $value = null ) {
1344 return FileRepoStatus
::newGood( $this, $value );
1348 * Delete files in the deleted directory if they are not referenced in the filearchive table
1352 public function cleanupDeletedBatch( $storageKeys ) {}
1355 * Checks if there is a redirect named as $title. If there is, return the
1356 * title object. If not, return false.
1359 * @param $title Title of image
1362 public function checkRedirect( Title
$title ) {
1367 * Invalidates image redirect cache related to that image
1368 * Doesn't do anything for repositories that don't support image redirects.
1371 * @param $title Title of image
1373 public function invalidateImageRedirect( Title
$title ) {}
1376 * Get the human-readable name of the repo
1380 public function getDisplayName() {
1381 // We don't name our own repo, return nothing
1382 if ( $this->isLocal() ) {
1385 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1386 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1390 * Returns true if this the local file repository.
1394 public function isLocal() {
1395 return $this->getName() == 'local';
1399 * Get a key on the primary cache for this repository.
1400 * Returns false if the repository's cache is not accessible at this site.
1401 * The parameters are the parts of the key, as for wfMemcKey().
1405 function getSharedCacheKey( /*...*/ ) {
1410 * Get a key for this repo in the local cache domain. These cache keys are
1411 * not shared with remote instances of the repo.
1412 * The parameters are the parts of the key, as for wfMemcKey().
1416 function getLocalCacheKey( /*...*/ ) {
1417 $args = func_get_args();
1418 array_unshift( $args, 'filerepo', $this->getName() );
1419 return call_user_func_array( 'wfMemcKey', $args );
1423 * Get an UploadStash associated with this repo.
1425 * @return UploadStash
1427 public function getUploadStash() {
1428 return new UploadStash( $this );