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;
21 const ALLOW_STALE
= 16;
23 /** @var FileBackendBase */
25 /** @var Array Map of zones to config */
26 protected $zones = array();
28 var $thumbScriptUrl, $transformVia404;
29 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
30 var $fetchDescription, $initialCapital;
31 var $pathDisclosureProtection = 'simple'; // 'paranoid'
32 var $descriptionCacheExpiry, $url, $thumbUrl;
33 var $hashLevels, $deletedHashLevels;
36 * Factory functions for creating new files
37 * Override these in the base class
39 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
40 var $oldFileFactory = false;
41 var $fileFactoryKey = false, $oldFileFactoryKey = false;
43 function __construct( $info ) {
45 $this->name
= $info['name'];
46 if ( $info['backend'] instanceof FileBackendBase
) {
47 $this->backend
= $info['backend']; // useful for testing
49 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
52 // Optional settings that can have no value
53 $optionalSettings = array(
54 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
55 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
58 foreach ( $optionalSettings as $var ) {
59 if ( isset( $info[$var] ) ) {
60 $this->$var = $info[$var];
64 // Optional settings that have a default
65 $this->initialCapital
= isset( $info['initialCapital'] )
66 ?
$info['initialCapital']
67 : MWNamespace
::isCapitalized( NS_FILE
);
68 $this->url
= isset( $info['url'] )
70 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
71 if ( isset( $info['thumbUrl'] ) ) {
72 $this->thumbUrl
= $info['thumbUrl'];
74 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
76 $this->hashLevels
= isset( $info['hashLevels'] )
79 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
80 ?
$info['deletedHashLevels']
82 $this->transformVia404
= !empty( $info['transformVia404'] );
83 $this->zones
= isset( $info['zones'] )
86 // Give defaults for the basic zones...
87 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
88 if ( !isset( $this->zones
[$zone] ) ) {
89 $this->zones
[$zone] = array(
90 'container' => "media-$zone",
91 'directory' => '' // container root
98 * Get the file backend instance
100 * @return FileBackendBase
102 public function getBackend() {
103 return $this->backend
;
107 * Prepare a single zone or list of zones for usage.
108 * See initDeletedDir() for additional setup needed for the 'deleted' zone.
110 * @param $doZones Array Only do a particular zones
113 protected function initZones( $doZones = array() ) {
114 $status = $this->newGood();
115 foreach ( (array)$doZones as $zone ) {
116 $root = $this->getZonePath( $zone );
117 if ( $root === null ) {
118 throw new MWException( "No '$zone' zone defined in the $this->name repo." );
120 $params = array( 'dir' => $this->getZonePath( $zone ) );
121 $status->merge( $this->backend
->prepare( $params ) );
128 * Take all available measures to prevent web accessibility of new deleted
129 * directories, in case the user has not configured offline storage
133 protected function initDeletedDir( $dir ) {
134 // Add a .htaccess file to the root of the deleted zone
135 $root = $this->getZonePath( 'deleted' );
136 $this->backend
->secure( array( 'dir' => $root, 'noAccess' => true ) );
137 // Seed new directories with a blank index.html, to prevent crawling
138 $this->backend
->secure( array( 'dir' => $dir, 'noListing' => true ) );
142 * Determine if a string is an mwrepo:// URL
147 public static function isVirtualUrl( $url ) {
148 return substr( $url, 0, 9 ) == 'mwrepo://';
152 * Get a URL referring to this repository, with the private mwrepo protocol.
153 * The suffix, if supplied, is considered to be unencoded, and will be
154 * URL-encoded before being returned.
156 * @param $suffix string
159 public function getVirtualUrl( $suffix = false ) {
160 $path = 'mwrepo://' . $this->name
;
161 if ( $suffix !== false ) {
162 $path .= '/' . rawurlencode( $suffix );
168 * Get the URL corresponding to one of the four basic zones
170 * @param $zone String: one of: public, deleted, temp, thumb
171 * @return String or false
173 public function getZoneUrl( $zone ) {
178 return "{$this->url}/temp";
180 return false; // no public URL
182 return $this->thumbUrl
;
189 * Get the backend storage path corresponding to a virtual URL
194 function resolveVirtualUrl( $url ) {
195 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
196 throw new MWException( __METHOD__
.': unknown protocol' );
198 $bits = explode( '/', substr( $url, 9 ), 3 );
199 if ( count( $bits ) != 3 ) {
200 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
202 list( $repo, $zone, $rel ) = $bits;
203 if ( $repo !== $this->name
) {
204 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
206 $base = $this->getZonePath( $zone );
208 throw new MWException( __METHOD__
.": invalid zone: $zone" );
210 return $base . '/' . rawurldecode( $rel );
214 * The the storage container and base path of a zone
216 * @param $zone string
217 * @return Array (container, base path) or (null, null)
219 protected function getZoneLocation( $zone ) {
220 if ( !isset( $this->zones
[$zone] ) ) {
221 return array( null, null ); // bogus
223 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
227 * Get the storage path corresponding to one of the zones
229 * @param $zone string
230 * @return string|null
232 public function getZonePath( $zone ) {
233 list( $container, $base ) = $this->getZoneLocation( $zone );
234 if ( $container === null ||
$base === null ) {
237 $backendName = $this->backend
->getName();
238 if ( $base != '' ) { // may not be set
241 return "mwstore://$backendName/{$container}{$base}";
245 * Create a new File object from the local repository
247 * @param $title Mixed: Title object or string
248 * @param $time Mixed: Time at which the image was uploaded.
249 * If this is specified, the returned object will be an
250 * instance of the repository's old file class instead of a
251 * current file. Repositories not supporting version control
252 * should return false if this parameter is set.
253 * @return File|null A File, or null if passed an invalid Title
255 public function newFile( $title, $time = false ) {
256 $title = File
::normalizeTitle( $title );
261 if ( $this->oldFileFactory
) {
262 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
267 return call_user_func( $this->fileFactory
, $title, $this );
272 * Find an instance of the named file created at the specified time
273 * Returns false if the file does not exist. Repositories not supporting
274 * version control should return false if the time is specified.
276 * @param $title Mixed: Title object or string
277 * @param $options array Associative array of options:
278 * time: requested time for an archived image, or false for the
279 * current version. An image object will be returned which was
280 * created at the specified time.
282 * ignoreRedirect: If true, do not follow file redirects
284 * private: If true, return restricted (deleted) files if the current
285 * user is allowed to view them. Otherwise, such files will not
289 public function findFile( $title, $options = array() ) {
290 $title = File
::normalizeTitle( $title );
294 $time = isset( $options['time'] ) ?
$options['time'] : false;
295 # First try the current version of the file to see if it precedes the timestamp
296 $img = $this->newFile( $title );
300 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
303 # Now try an old version of the file
304 if ( $time !== false ) {
305 $img = $this->newFile( $title, $time );
306 if ( $img && $img->exists() ) {
307 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
308 return $img; // always OK
309 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
316 if ( !empty( $options['ignoreRedirect'] ) ) {
319 $redir = $this->checkRedirect( $title );
320 if ( $redir && $title->getNamespace() == NS_FILE
) {
321 $img = $this->newFile( $redir );
325 if ( $img->exists() ) {
326 $img->redirectedFrom( $title->getDBkey() );
334 * Find many files at once.
336 * @param $items An array of titles, or an array of findFile() options with
337 * the "title" option giving the title. Example:
339 * $findItem = array( 'title' => $title, 'private' => true );
340 * $findBatch = array( $findItem );
341 * $repo->findFiles( $findBatch );
344 public function findFiles( $items ) {
346 foreach ( $items as $item ) {
347 if ( is_array( $item ) ) {
348 $title = $item['title'];
350 unset( $options['title'] );
355 $file = $this->findFile( $title, $options );
357 $result[$file->getTitle()->getDBkey()] = $file;
364 * Find an instance of the file with this key, created at the specified time
365 * Returns false if the file does not exist. Repositories not supporting
366 * version control should return false if the time is specified.
368 * @param $sha1 String base 36 SHA-1 hash
369 * @param $options Option array, same as findFile().
372 public function findFileFromKey( $sha1, $options = array() ) {
373 $time = isset( $options['time'] ) ?
$options['time'] : false;
375 # First try to find a matching current version of a file...
376 if ( $this->fileFactoryKey
) {
377 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
379 return false; // find-by-sha1 not supported
381 if ( $img && $img->exists() ) {
384 # Now try to find a matching old version of a file...
385 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
386 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
387 if ( $img && $img->exists() ) {
388 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
389 return $img; // always OK
390 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
399 * Get an array or iterator of file objects for files that have a given
400 * SHA-1 content hash.
404 public function findBySha1( $hash ) {
409 * Get the public root URL of the repository
411 * @return string|false
413 public function getRootUrl() {
418 * Returns true if the repository uses a multi-level directory structure
422 public function isHashed() {
423 return (bool)$this->hashLevels
;
427 * Get the URL of thumb.php
431 public function getThumbScriptUrl() {
432 return $this->thumbScriptUrl
;
436 * Returns true if the repository can transform files via a 404 handler
440 public function canTransformVia404() {
441 return $this->transformVia404
;
445 * Get the name of an image from its title object
447 * @param $title Title
449 public function getNameFromTitle( Title
$title ) {
451 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
452 $name = $title->getUserCaseDBKey();
453 if ( $this->initialCapital
) {
454 $name = $wgContLang->ucfirst( $name );
457 $name = $title->getDBkey();
463 * Get the public zone root storage directory of the repository
467 public function getRootDirectory() {
468 return $this->getZonePath( 'public' );
472 * Get a relative path including trailing slash, e.g. f/fa/
473 * If the repo is not hashed, returns an empty string
475 * @param $name string
478 public function getHashPath( $name ) {
479 return self
::getHashPathForLevel( $name, $this->hashLevels
);
487 static function getHashPathForLevel( $name, $levels ) {
488 if ( $levels == 0 ) {
491 $hash = md5( $name );
493 for ( $i = 1; $i <= $levels; $i++
) {
494 $path .= substr( $hash, 0, $i ) . '/';
501 * Get the number of hash directory levels
505 public function getHashLevels() {
506 return $this->hashLevels
;
510 * Get the name of this repository, as specified by $info['name]' to the constructor
514 public function getName() {
519 * Make an url to this repo
521 * @param $query mixed Query string to append
522 * @param $entry string Entry point; defaults to index
523 * @return string|false
525 public function makeUrl( $query = '', $entry = 'index' ) {
526 if ( isset( $this->scriptDirUrl
) ) {
527 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
528 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
534 * Get the URL of an image description page. May return false if it is
535 * unknown or not applicable. In general this should only be called by the
536 * File class, since it may return invalid results for certain kinds of
537 * repositories. Use File::getDescriptionUrl() in user code.
539 * In particular, it uses the article paths as specified to the repository
540 * constructor, whereas local repositories use the local Title functions.
542 * @param $name string
545 public function getDescriptionUrl( $name ) {
546 $encName = wfUrlencode( $name );
547 if ( !is_null( $this->descBaseUrl
) ) {
548 # "http://example.com/wiki/Image:"
549 return $this->descBaseUrl
. $encName;
551 if ( !is_null( $this->articleUrl
) ) {
552 # "http://example.com/wiki/$1"
554 # We use "Image:" as the canonical namespace for
555 # compatibility across all MediaWiki versions.
556 return str_replace( '$1',
557 "Image:$encName", $this->articleUrl
);
559 if ( !is_null( $this->scriptDirUrl
) ) {
560 # "http://example.com/w"
562 # We use "Image:" as the canonical namespace for
563 # compatibility across all MediaWiki versions,
564 # and just sort of hope index.php is right. ;)
565 return $this->makeUrl( "title=Image:$encName" );
571 * Get the URL of the content-only fragment of the description page. For
572 * MediaWiki this means action=render. This should only be called by the
573 * repository's file class, since it may return invalid results. User code
574 * should use File::getDescriptionText().
576 * @param $name String: name of image to fetch
577 * @param $lang String: language to fetch it in, if any.
580 public function getDescriptionRenderUrl( $name, $lang = null ) {
581 $query = 'action=render';
582 if ( !is_null( $lang ) ) {
583 $query .= '&uselang=' . $lang;
585 if ( isset( $this->scriptDirUrl
) ) {
586 return $this->makeUrl(
588 wfUrlencode( 'Image:' . $name ) .
591 $descUrl = $this->getDescriptionUrl( $name );
593 return wfAppendQuery( $descUrl, $query );
601 * Get the URL of the stylesheet to apply to description pages
603 * @return string|false
605 public function getDescriptionStylesheetUrl() {
606 if ( isset( $this->scriptDirUrl
) ) {
607 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
608 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
614 * Store a file to a given destination.
616 * @param $srcPath String: source FS path, storage path, or virtual URL
617 * @param $dstZone String: destination zone
618 * @param $dstRel String: destination relative path
619 * @param $flags Integer: bitwise combination of the following flags:
620 * self::DELETE_SOURCE Delete the source file after upload
621 * self::OVERWRITE Overwrite an existing destination file instead of failing
622 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
623 * same contents as the source
624 * self::SKIP_LOCKING Skip any file locking when doing the store
625 * self::ALLOW_STALE Don't require latest data for existence checks
626 * @return FileRepoStatus
628 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
629 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
630 if ( $status->successCount
== 0 ) {
637 * Store a batch of files
639 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
640 * @param $flags Integer: bitwise combination of the following flags:
641 * self::DELETE_SOURCE Delete the source file after upload
642 * self::OVERWRITE Overwrite an existing destination file instead of failing
643 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
644 * same contents as the source
645 * self::SKIP_LOCKING Skip any file locking when doing the store
646 * @return FileRepoStatus
648 public function storeBatch( $triplets, $flags = 0 ) {
649 $backend = $this->backend
; // convenience
651 $status = $this->newGood();
653 $operations = array();
654 $sourceFSFilesToDelete = array(); // cleanup for disk source files
655 // Validate each triplet and get the store operation...
656 foreach ( $triplets as $triplet ) {
657 list( $srcPath, $dstZone, $dstRel ) = $triplet;
659 // Resolve destination path
660 $root = $this->getZonePath( $dstZone );
662 throw new MWException( "Invalid zone: $dstZone" );
664 if ( !$this->validateFilename( $dstRel ) ) {
665 throw new MWException( 'Validation error in $dstRel' );
667 $dstPath = "$root/$dstRel";
668 $dstDir = dirname( $dstPath );
670 // Create destination directories for this triplet
671 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
672 return $this->newFatal( 'directorycreateerror', $dstDir );
675 if ( $dstZone == 'deleted' ) {
676 $this->initDeletedDir( $dstDir );
679 // Resolve source to a storage path if virtual
680 if ( self
::isVirtualUrl( $srcPath ) ) {
681 $srcPath = $this->resolveVirtualUrl( $srcPath );
684 // Get the appropriate file operation
685 if ( FileBackend
::isStoragePath( $srcPath ) ) {
686 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
689 if ( $flags & self
::DELETE_SOURCE
) {
690 $sourceFSFilesToDelete[] = $srcPath;
693 $operations[] = array(
697 'overwriteDest' => $flags & self
::OVERWRITE
,
698 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
702 // Execute the store operation for each triplet
703 $opts = array( 'ignoreErrors' => true );
704 if ( $flags & self
::SKIP_LOCKING
) {
705 $opts['nonLocking'] = true;
707 if ( $flags & self
::ALLOW_STALE
) {
708 $opts['allowStale'] = true;
710 $status->merge( $backend->doOperations( $operations, $opts ) );
711 // Cleanup for disk source files...
712 foreach ( $sourceFSFilesToDelete as $file ) {
713 wfSuppressWarnings();
714 unlink( $file ); // FS cleanup
722 * Deletes a batch of files.
723 * Each file can be a (zone, rel) pair, virtual url, storage path, or FS path.
724 * It will try to delete each file, but ignores any errors that may occur.
726 * @param $pairs array List of files to delete
729 public function cleanupBatch( $files ) {
730 $operations = array();
731 $sourceFSFilesToDelete = array(); // cleanup for disk source files
732 foreach ( $files as $file ) {
733 if ( is_array( $file ) ) {
734 // This is a pair, extract it
735 list( $zone, $rel ) = $file;
736 $root = $this->getZonePath( $zone );
737 $path = "$root/$rel";
739 if ( self
::isVirtualUrl( $file ) ) {
740 // This is a virtual url, resolve it
741 $path = $this->resolveVirtualUrl( $file );
743 // This is a full file name
747 // Get a file operation if needed
748 if ( FileBackend
::isStoragePath( $path ) ) {
749 $operations[] = array(
754 $sourceFSFilesToDelete[] = $path;
757 // Actually delete files from storage...
758 $opts = array( 'ignoreErrors' => true );
759 $this->backend
->doOperations( $operations, $opts );
760 // Cleanup for disk source files...
761 foreach ( $sourceFSFilesToDelete as $file ) {
762 wfSuppressWarnings();
763 unlink( $file ); // FS cleanup
769 * Pick a random name in the temp zone and store a file to it.
770 * Returns a FileRepoStatus object with the URL in the value.
772 * @param $originalName String: the base name of the file as specified
773 * by the user. The file extension will be maintained.
774 * @param $srcPath String: the current location of the file.
775 * @return FileRepoStatus object with the URL in the value.
777 public function storeTemp( $originalName, $srcPath ) {
778 $date = gmdate( "YmdHis" );
779 $hashPath = $this->getHashPath( $originalName );
780 $dstRel = "{$hashPath}{$date}!{$originalName}";
781 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
783 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
784 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
789 * Concatenate a list of files into a target file location.
791 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
792 * @param $dstPath String Target file system path
793 * @param $flags Integer: bitwise combination of the following flags:
794 * self::DELETE_SOURCE Delete the source files
795 * @return FileRepoStatus
797 function concatenate( $srcPaths, $dstPath, $flags = 0 ) {
798 $status = $this->newGood();
799 // Resolve target to a storage path if virtual
800 $dest = $this->resolveToStoragePath( $dstPath );
803 $deleteOperations = array(); // post-concatenate ops
804 foreach ( $srcPaths as $srcPath ) {
805 // Resolve source to a storage path if virtual
806 $source = $this->resolveToStoragePath( $srcPath );
807 $sources[] = $source; // chunk to merge
808 if ( $flags & self
::DELETE_SOURCE
) {
809 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
813 // Concatenate the chunks into one file
814 $op = array( 'op' => 'concatenate', 'srcs' => $sources, 'dst' => $dest );
815 $status->merge( $this->backend
->doOperation( $op ) );
816 if ( !$status->isOK() ) {
820 // Delete the sources if required
821 if ( $deleteOperations ) {
822 $opts = array( 'ignoreErrors' => true );
823 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
826 // Make sure status is OK, despite any $deleteOperations fatals
827 $status->setResult( true );
833 * Remove a temporary file or mark it for garbage collection
835 * @param $virtualUrl String: the virtual URL returned by storeTemp
836 * @return Boolean: true on success, false on failure
838 public function freeTemp( $virtualUrl ) {
839 $temp = "mwrepo://{$this->name}/temp";
840 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
841 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
844 $path = $this->resolveVirtualUrl( $virtualUrl );
845 $op = array( 'op' => 'delete', 'src' => $path );
846 $status = $this->backend
->doOperation( $op );
847 return $status->isOK();
851 * Copy or move a file either from a storage path, virtual URL,
852 * or FS path, into this repository at the specified destination location.
854 * Returns a FileRepoStatus object. On success, the value contains "new" or
855 * "archived", to indicate whether the file was new with that name.
857 * @param $srcPath String: the source FS path, storage path, or URL
858 * @param $dstRel String: the destination relative path
859 * @param $archiveRel String: the relative path where the existing file is to
860 * be archived, if there is one. Relative to the public zone root.
861 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
862 * that the source file should be deleted if possible
864 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
865 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
866 if ( $status->successCount
== 0 ) {
869 if ( isset( $status->value
[0] ) ) {
870 $status->value
= $status->value
[0];
872 $status->value
= false;
878 * Publish a batch of files
880 * @param $triplets Array: (source, dest, archive) triplets as per publish()
881 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
882 * that the source files should be deleted if possible
883 * @return FileRepoStatus
885 public function publishBatch( $triplets, $flags = 0 ) {
886 $backend = $this->backend
; // convenience
888 // Try creating directories
889 $status = $this->initZones( 'public' );
890 if ( !$status->isOK() ) {
894 $status = $this->newGood( array() );
896 $operations = array();
897 $sourceFSFilesToDelete = array(); // cleanup for disk source files
898 // Validate each triplet and get the store operation...
899 foreach ( $triplets as $i => $triplet ) {
900 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
901 // Resolve source to a storage path if virtual
902 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
903 $srcPath = $this->resolveVirtualUrl( $srcPath );
905 if ( !$this->validateFilename( $dstRel ) ) {
906 throw new MWException( 'Validation error in $dstRel' );
908 if ( !$this->validateFilename( $archiveRel ) ) {
909 throw new MWException( 'Validation error in $archiveRel' );
912 $publicRoot = $this->getZonePath( 'public' );
913 $dstPath = "$publicRoot/$dstRel";
914 $archivePath = "$publicRoot/$archiveRel";
916 $dstDir = dirname( $dstPath );
917 $archiveDir = dirname( $archivePath );
918 // Abort immediately on directory creation errors since they're likely to be repetitive
919 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
920 return $this->newFatal( 'directorycreateerror', $dstDir );
922 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
923 return $this->newFatal( 'directorycreateerror', $archiveDir );
926 // Archive destination file if it exists
927 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
928 // Check if the archive file exists
929 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
930 // unlinks the destination file if it exists. DB-based synchronisation in
931 // publishBatch's caller should prevent races. In Windows there's no
932 // problem because the rename primitive fails if the destination exists.
933 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
934 $operations[] = array( 'op' => 'null' );
937 $operations[] = array(
940 'dst' => $archivePath
943 $status->value
[$i] = 'archived';
945 $status->value
[$i] = 'new';
947 // Copy (or move) the source file to the destination
948 if ( FileBackend
::isStoragePath( $srcPath ) ) {
949 if ( $flags & self
::DELETE_SOURCE
) {
950 $operations[] = array(
956 $operations[] = array(
962 } else { // FS source path
963 $operations[] = array(
968 if ( $flags & self
::DELETE_SOURCE
) {
969 $sourceFSFilesToDelete[] = $srcPath;
974 // Execute the operations for each triplet
975 $opts = array( 'ignoreErrors' => true );
976 $status->merge( $backend->doOperations( $operations, $opts ) );
977 // Cleanup for disk source files...
978 foreach ( $sourceFSFilesToDelete as $file ) {
979 wfSuppressWarnings();
980 unlink( $file ); // FS cleanup
988 * Checks existence of a a file
990 * @param $file Virtual URL (or storage path) of file to check
991 * @param $flags Integer: bitwise combination of the following flags:
992 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
995 public function fileExists( $file, $flags = 0 ) {
996 $result = $this->fileExistsBatch( array( $file ), $flags );
1001 * Checks existence of an array of files.
1003 * @param $files Array: Virtual URLs (or storage paths) of files to check
1004 * @param $flags Integer: bitwise combination of the following flags:
1005 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
1006 * @return Either array of files and existence flags, or false
1008 public function fileExistsBatch( $files, $flags = 0 ) {
1010 foreach ( $files as $key => $file ) {
1011 if ( self
::isVirtualUrl( $file ) ) {
1012 $file = $this->resolveVirtualUrl( $file );
1014 if ( FileBackend
::isStoragePath( $file ) ) {
1015 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1017 if ( $flags & self
::FILES_ONLY
) {
1018 $result[$key] = is_file( $file ); // FS only
1020 $result[$key] = file_exists( $file ); // FS only
1029 * Move a file to the deletion archive.
1030 * If no valid deletion archive exists, this may either delete the file
1031 * or throw an exception, depending on the preference of the repository
1033 * @param $srcRel Mixed: relative path for the file to be deleted
1034 * @param $archiveRel Mixed: relative path for the archive location.
1035 * Relative to a private archive directory.
1036 * @return FileRepoStatus object
1038 public function delete( $srcRel, $archiveRel ) {
1039 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1043 * Move a group of files to the deletion archive.
1045 * If no valid deletion archive is configured, this may either delete the
1046 * file or throw an exception, depending on the preference of the repository.
1048 * The overwrite policy is determined by the repository -- currently LocalRepo
1049 * assumes a naming scheme in the deleted zone based on content hash, as
1050 * opposed to the public zone which is assumed to be unique.
1052 * @param $sourceDestPairs Array of source/destination pairs. Each element
1053 * is a two-element array containing the source file path relative to the
1054 * public root in the first element, and the archive file path relative
1055 * to the deleted zone root in the second element.
1056 * @return FileRepoStatus
1058 public function deleteBatch( $sourceDestPairs ) {
1059 $backend = $this->backend
; // convenience
1061 // Try creating directories
1062 $status = $this->initZones( array( 'public', 'deleted' ) );
1063 if ( !$status->isOK() ) {
1067 $status = $this->newGood();
1069 $operations = array();
1070 // Validate filenames and create archive directories
1071 foreach ( $sourceDestPairs as $pair ) {
1072 list( $srcRel, $archiveRel ) = $pair;
1073 if ( !$this->validateFilename( $srcRel ) ) {
1074 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1076 if ( !$this->validateFilename( $archiveRel ) ) {
1077 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1080 $publicRoot = $this->getZonePath( 'public' );
1081 $srcPath = "{$publicRoot}/$srcRel";
1083 $deletedRoot = $this->getZonePath( 'deleted' );
1084 $archivePath = "{$deletedRoot}/{$archiveRel}";
1085 $archiveDir = dirname( $archivePath ); // does not touch FS
1087 // Create destination directories
1088 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1089 return $this->newFatal( 'directorycreateerror', $archiveDir );
1091 $this->initDeletedDir( $archiveDir );
1093 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1094 $operations[] = array(
1099 $operations[] = array(
1102 'dst' => $archivePath
1107 // Move the files by execute the operations for each pair.
1108 // We're now committed to returning an OK result, which will
1109 // lead to the files being moved in the DB also.
1110 $opts = array( 'ignoreErrors' => true );
1111 $status->merge( $backend->doOperations( $operations, $opts ) );
1117 * Get a relative path for a deletion archive key,
1118 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1122 public function getDeletedHashPath( $key ) {
1124 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1125 $path .= $key[$i] . '/';
1131 * If a path is a virtual URL, resolve it to a storage path.
1132 * Otherwise, just return the path as it is.
1134 * @param $path string
1136 * @throws MWException
1138 protected function resolveToStoragePath( $path ) {
1139 if ( $this->isVirtualUrl( $path ) ) {
1140 return $this->resolveVirtualUrl( $path );
1146 * Get a local FS copy of a file with a given virtual URL/storage path.
1147 * Temporary files may be purged when the file object falls out of scope.
1149 * @param $virtualUrl string
1150 * @return TempFSFile|null Returns null on failure
1152 public function getLocalCopy( $virtualUrl ) {
1153 $path = $this->resolveToStoragePath( $virtualUrl );
1154 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1158 * Get a local FS file with a given virtual URL/storage path.
1159 * The file is either an original or a copy. It should not be changed.
1160 * Temporary files may be purged when the file object falls out of scope.
1162 * @param $virtualUrl string
1163 * @return FSFile|null Returns null on failure.
1165 public function getLocalReference( $virtualUrl ) {
1166 $path = $this->resolveToStoragePath( $virtualUrl );
1167 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1171 * Get properties of a file with a given virtual URL/storage path.
1172 * Properties should ultimately be obtained via FSFile::getProps().
1174 * @param $virtualUrl string
1177 public function getFileProps( $virtualUrl ) {
1178 $path = $this->resolveToStoragePath( $virtualUrl );
1179 return $this->backend
->getFileProps( array( 'src' => $path ) );
1183 * Get the timestamp of a file with a given virtual URL/storage path
1185 * @param $virtualUrl string
1186 * @return string|false
1188 public function getFileTimestamp( $virtualUrl ) {
1189 $path = $this->resolveToStoragePath( $virtualUrl );
1190 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1194 * Get the sha1 of a file with a given virtual URL/storage path
1196 * @param $virtualUrl string
1197 * @return string|false
1199 public function getFileSha1( $virtualUrl ) {
1200 $path = $this->resolveToStoragePath( $virtualUrl );
1201 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1205 return $tmpFile->getSha1Base36();
1209 * Attempt to stream a file with the given virtual URL/storage path
1211 * @param $virtualUrl string
1212 * @param $headers Array Additional HTTP headers to send on success
1213 * @return bool Success
1215 public function streamFile( $virtualUrl, $headers = array() ) {
1216 $path = $this->resolveToStoragePath( $virtualUrl );
1217 $params = array( 'src' => $path, 'headers' => $headers );
1218 return $this->backend
->streamFile( $params )->isOK();
1222 * Call a callback function for every public file in the repository.
1223 * May use either the database or the filesystem.
1225 * @param $callback Array|string
1228 public function enumFiles( $callback ) {
1229 return $this->enumFilesInStorage( $callback );
1233 * Call a callback function for every public file in the repository.
1234 * May use either the database or the filesystem.
1236 * @param $callback Array|string
1239 protected function enumFilesInStorage( $callback ) {
1240 $publicRoot = $this->getZonePath( 'public' );
1241 $numDirs = 1 << ( $this->hashLevels
* 4 );
1242 // Use a priori assumptions about directory structure
1243 // to reduce the tree height of the scanning process.
1244 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1245 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1246 $path = $publicRoot;
1247 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1248 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1250 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1251 foreach ( $iterator as $name ) {
1252 // Each item returned is a public file
1253 call_user_func( $callback, "{$path}/{$name}" );
1259 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1261 * @param $filename string
1264 public function validateFilename( $filename ) {
1265 if ( strval( $filename ) == '' ) {
1268 if ( wfIsWindows() ) {
1269 $filename = strtr( $filename, '\\', '/' );
1272 * Use the same traversal protection as Title::secureAndSplit()
1274 if ( strpos( $filename, '.' ) !== false &&
1275 ( $filename === '.' ||
$filename === '..' ||
1276 strpos( $filename, './' ) === 0 ||
1277 strpos( $filename, '../' ) === 0 ||
1278 strpos( $filename, '/./' ) !== false ||
1279 strpos( $filename, '/../' ) !== false ) )
1288 * Get a callback function to use for cleaning error message parameters
1292 function getErrorCleanupFunction() {
1293 switch ( $this->pathDisclosureProtection
) {
1295 $callback = array( $this, 'passThrough' );
1298 $callback = array( $this, 'simpleClean' );
1300 default: // 'paranoid'
1301 $callback = array( $this, 'paranoidClean' );
1307 * Path disclosure protection function
1309 * @param $param string
1312 function paranoidClean( $param ) {
1317 * Path disclosure protection function
1319 * @param $param string
1322 function simpleClean( $param ) {
1324 if ( !isset( $this->simpleCleanPairs
) ) {
1325 $this->simpleCleanPairs
= array(
1326 $IP => '$IP', // sanity
1329 return strtr( $param, $this->simpleCleanPairs
);
1333 * Path disclosure protection function
1335 * @param $param string
1338 function passThrough( $param ) {
1343 * Create a new fatal error
1345 * @return FileRepoStatus
1347 function newFatal( $message /*, parameters...*/ ) {
1348 $params = func_get_args();
1349 array_unshift( $params, $this );
1350 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1354 * Create a new good result
1356 * @return FileRepoStatus
1358 function newGood( $value = null ) {
1359 return FileRepoStatus
::newGood( $this, $value );
1363 * Delete files in the deleted directory if they are not referenced in the filearchive table
1367 public function cleanupDeletedBatch( $storageKeys ) {}
1370 * Checks if there is a redirect named as $title. If there is, return the
1371 * title object. If not, return false.
1374 * @param $title Title of image
1377 public function checkRedirect( Title
$title ) {
1382 * Invalidates image redirect cache related to that image
1383 * Doesn't do anything for repositories that don't support image redirects.
1386 * @param $title Title of image
1388 public function invalidateImageRedirect( Title
$title ) {}
1391 * Get the human-readable name of the repo
1395 public function getDisplayName() {
1396 // We don't name our own repo, return nothing
1397 if ( $this->isLocal() ) {
1400 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1401 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1405 * Returns true if this the local file repository.
1409 public function isLocal() {
1410 return $this->getName() == 'local';
1414 * Get a key on the primary cache for this repository.
1415 * Returns false if the repository's cache is not accessible at this site.
1416 * The parameters are the parts of the key, as for wfMemcKey().
1420 function getSharedCacheKey( /*...*/ ) {
1425 * Get a key for this repo in the local cache domain. These cache keys are
1426 * not shared with remote instances of the repo.
1427 * The parameters are the parts of the key, as for wfMemcKey().
1431 function getLocalCacheKey( /*...*/ ) {
1432 $args = func_get_args();
1433 array_unshift( $args, 'filerepo', $this->getName() );
1434 return call_user_func_array( 'wfMemcKey', $args );
1438 * Get an UploadStash associated with this repo.
1440 * @return UploadStash
1442 public function getUploadStash() {
1443 return new UploadStash( $this );