3 * Base code for file repositories.
10 * Base class for file repositories.
11 * Do not instantiate, use a derived class.
15 abstract class FileRepo
{
17 const DELETE_SOURCE
= 1;
19 const OVERWRITE_SAME
= 4;
20 const SKIP_VALIDATION
= 8;
22 var $thumbScriptUrl, $transformVia404;
23 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
24 var $fetchDescription, $initialCapital;
25 var $pathDisclosureProtection = 'paranoid';
26 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
29 * Factory functions for creating new files
30 * Override these in the base class
32 var $fileFactory = false, $oldFileFactory = false;
33 var $fileFactoryKey = false, $oldFileFactoryKey = false;
35 function __construct( $info ) {
37 $this->name
= $info['name'];
40 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
41 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
42 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
43 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
46 if ( isset( $info[$var] ) ) {
47 $this->$var = $info[$var];
50 $this->transformVia404
= !empty( $info['transformVia404'] );
54 * Determine if a string is an mwrepo:// URL
60 static function isVirtualUrl( $url ) {
61 return substr( $url, 0, 9 ) == 'mwrepo://';
65 * Create a new File object from the local repository
67 * @param $title Mixed: Title object or string
68 * @param $time Mixed: Time at which the image was uploaded.
69 * If this is specified, the returned object will be an
70 * instance of the repository's old file class instead of a
71 * current file. Repositories not supporting version control
72 * should return false if this parameter is set.
76 function newFile( $title, $time = false ) {
77 if ( !($title instanceof Title
) ) {
78 $title = Title
::makeTitleSafe( NS_FILE
, $title );
79 if ( !is_object( $title ) ) {
84 if ( $this->oldFileFactory
) {
85 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
90 return call_user_func( $this->fileFactory
, $title, $this );
95 * Find an instance of the named file created at the specified time
96 * Returns false if the file does not exist. Repositories not supporting
97 * version control should return false if the time is specified.
99 * @param $title Mixed: Title object or string
100 * @param $options array Associative array of options:
101 * time: requested time for an archived image, or false for the
102 * current version. An image object will be returned which was
103 * created at the specified time.
105 * ignoreRedirect: If true, do not follow file redirects
107 * private: If true, return restricted (deleted) files if the current
108 * user is allowed to view them. Otherwise, such files will not
113 function findFile( $title, $options = array() ) {
114 $time = isset( $options['time'] ) ?
$options['time'] : false;
115 if ( !($title instanceof Title
) ) {
116 $title = Title
::makeTitleSafe( NS_FILE
, $title );
117 if ( !is_object( $title ) ) {
121 # First try the current version of the file to see if it precedes the timestamp
122 $img = $this->newFile( $title );
126 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
129 # Now try an old version of the file
130 if ( $time !== false ) {
131 $img = $this->newFile( $title, $time );
132 if ( $img && $img->exists() ) {
133 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
135 } elseif ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
142 if ( !empty( $options['ignoreRedirect'] ) ) {
145 $redir = $this->checkRedirect( $title );
146 if( $redir && $title->getNamespace() == NS_FILE
) {
147 $img = $this->newFile( $redir );
151 if( $img->exists() ) {
152 $img->redirectedFrom( $title->getDBkey() );
160 * Find many files at once.
161 * @param $items An array of titles, or an array of findFile() options with
162 * the "title" option giving the title. Example:
164 * $findItem = array( 'title' => $title, 'private' => true );
165 * $findBatch = array( $findItem );
166 * $repo->findFiles( $findBatch );
170 function findFiles( $items ) {
172 foreach ( $items as $item ) {
173 if ( is_array( $item ) ) {
174 $title = $item['title'];
176 unset( $options['title'] );
181 $file = $this->findFile( $title, $options );
183 $result[$file->getTitle()->getDBkey()] = $file;
190 * Create a new File object from the local repository
191 * @param $sha1 Mixed: base 36 SHA-1 hash
192 * @param $time Mixed: time at which the image was uploaded.
193 * If this is specified, the returned object will be an
194 * of the repository's old file class instead of a current
195 * file. Repositories not supporting version control should
196 * return false if this parameter is set.
200 function newFileFromKey( $sha1, $time = false ) {
202 if ( $this->oldFileFactoryKey
) {
203 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
206 if ( $this->fileFactoryKey
) {
207 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
214 * Find an instance of the file with this key, created at the specified time
215 * Returns false if the file does not exist. Repositories not supporting
216 * version control should return false if the time is specified.
218 * @param $sha1 String base 36 SHA-1 hash
219 * @param $options Option array, same as findFile().
221 function findFileFromKey( $sha1, $options = array() ) {
222 $time = isset( $options['time'] ) ?
$options['time'] : false;
224 # First try the current version of the file to see if it precedes the timestamp
225 $img = $this->newFileFromKey( $sha1 );
229 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
232 # Now try an old version of the file
233 if ( $time !== false ) {
234 $img = $this->newFileFromKey( $sha1, $time );
235 if ( $img && $img->exists() ) {
236 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
238 } elseif ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
247 * Get the URL of thumb.php
249 function getThumbScriptUrl() {
250 return $this->thumbScriptUrl
;
254 * Get the URL corresponding to one of the four basic zones
255 * @param $zone String: one of: public, deleted, temp, thumb
256 * @return String or false
258 function getZoneUrl( $zone ) {
263 * Returns true if the repository can transform files via a 404 handler
267 function canTransformVia404() {
268 return $this->transformVia404
;
272 * Get the name of an image from its title object
273 * @param $title Title
275 function getNameFromTitle( $title ) {
276 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
278 $name = $title->getUserCaseDBKey();
279 if ( $this->initialCapital
) {
280 $name = $wgContLang->ucfirst( $name );
283 $name = $title->getDBkey();
293 static function getHashPathForLevel( $name, $levels ) {
294 if ( $levels == 0 ) {
297 $hash = md5( $name );
299 for ( $i = 1; $i <= $levels; $i++
) {
300 $path .= substr( $hash, 0, $i ) . '/';
307 * Get a relative path including trailing slash, e.g. f/fa/
308 * If the repo is not hashed, returns an empty string
310 * @param $name string
314 function getHashPath( $name ) {
315 return self
::getHashPathForLevel( $name, $this->hashLevels
);
319 * Get the name of this repository, as specified by $info['name]' to the constructor
326 * Make an url to this repo
328 * @param $query mixed Query string to append
329 * @param $entry string Entry point; defaults to index
332 function makeUrl( $query = '', $entry = 'index' ) {
333 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
334 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
338 * Get the URL of an image description page. May return false if it is
339 * unknown or not applicable. In general this should only be called by the
340 * File class, since it may return invalid results for certain kinds of
341 * repositories. Use File::getDescriptionUrl() in user code.
343 * In particular, it uses the article paths as specified to the repository
344 * constructor, whereas local repositories use the local Title functions.
346 function getDescriptionUrl( $name ) {
347 $encName = wfUrlencode( $name );
348 if ( !is_null( $this->descBaseUrl
) ) {
349 # "http://example.com/wiki/Image:"
350 return $this->descBaseUrl
. $encName;
352 if ( !is_null( $this->articleUrl
) ) {
353 # "http://example.com/wiki/$1"
355 # We use "Image:" as the canonical namespace for
356 # compatibility across all MediaWiki versions.
357 return str_replace( '$1',
358 "Image:$encName", $this->articleUrl
);
360 if ( !is_null( $this->scriptDirUrl
) ) {
361 # "http://example.com/w"
363 # We use "Image:" as the canonical namespace for
364 # compatibility across all MediaWiki versions,
365 # and just sort of hope index.php is right. ;)
366 return $this->makeUrl( "title=Image:$encName" );
372 * Get the URL of the content-only fragment of the description page. For
373 * MediaWiki this means action=render. This should only be called by the
374 * repository's file class, since it may return invalid results. User code
375 * should use File::getDescriptionText().
376 * @param $name String: name of image to fetch
377 * @param $lang String: language to fetch it in, if any.
379 function getDescriptionRenderUrl( $name, $lang = null ) {
380 $query = 'action=render';
381 if ( !is_null( $lang ) ) {
382 $query .= '&uselang=' . $lang;
384 if ( isset( $this->scriptDirUrl
) ) {
385 return $this->makeUrl(
387 wfUrlencode( 'Image:' . $name ) .
390 $descUrl = $this->getDescriptionUrl( $name );
392 return wfAppendQuery( $descUrl, $query );
400 * Get the URL of the stylesheet to apply to description pages
403 function getDescriptionStylesheetUrl() {
404 if ( $this->scriptDirUrl
) {
405 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
406 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
411 * Store a file to a given destination.
413 * @param $srcPath String: source path or virtual URL
414 * @param $dstZone String: destination zone
415 * @param $dstRel String: destination relative path
416 * @param $flags Integer: bitwise combination of the following flags:
417 * self::DELETE_SOURCE Delete the source file after upload
418 * self::OVERWRITE Overwrite an existing destination file instead of failing
419 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
420 * same contents as the source
421 * @return FileRepoStatus
423 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
424 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
425 if ( $status->successCount
== 0 ) {
432 * Store a batch of files
434 * @param $triplets Array: (src,zone,dest) triplets as per store()
435 * @param $flags Integer: flags as per store
437 abstract function storeBatch( $triplets, $flags = 0 );
440 * Pick a random name in the temp zone and store a file to it.
441 * Returns a FileRepoStatus object with the URL in the value.
443 * @param $originalName String: the base name of the file as specified
444 * by the user. The file extension will be maintained.
445 * @param $srcPath String: the current location of the file.
447 abstract function storeTemp( $originalName, $srcPath );
451 * Append the contents of the source path to the given file, OR queue
452 * the appending operation in anticipation of a later appendFinish() call.
453 * @param $srcPath String: location of the source file
454 * @param $toAppendPath String: path to append to.
455 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
456 * that the source file should be deleted if possible
457 * @return mixed Status or false
459 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
462 * Finish the append operation.
463 * @param $toAppendPath String: path to append to.
464 * @return mixed Status or false
466 abstract function appendFinish( $toAppendPath );
469 * Remove a temporary file or mark it for garbage collection
470 * @param $virtualUrl String: the virtual URL returned by storeTemp
471 * @return Boolean: true on success, false on failure
474 function freeTemp( $virtualUrl ) {
479 * Copy or move a file either from the local filesystem or from an mwrepo://
480 * virtual URL, into this repository at the specified destination location.
482 * Returns a FileRepoStatus object. On success, the value contains "new" or
483 * "archived", to indicate whether the file was new with that name.
485 * @param $srcPath String: the source path or URL
486 * @param $dstRel String: the destination relative path
487 * @param $archiveRel String: rhe relative path where the existing file is to
488 * be archived, if there is one. Relative to the public zone root.
489 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
490 * that the source file should be deleted if possible
492 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
493 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
494 if ( $status->successCount
== 0 ) {
497 if ( isset( $status->value
[0] ) ) {
498 $status->value
= $status->value
[0];
500 $status->value
= false;
506 * Publish a batch of files
507 * @param $triplets Array: (source,dest,archive) triplets as per publish()
508 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
509 * that the source files should be deleted if possible
511 abstract function publishBatch( $triplets, $flags = 0 );
518 function fileExists( $file, $flags = 0 ) {
519 $result = $this->fileExistsBatch( array( $file ), $flags );
524 * Checks existence of an array of files.
526 * @param $files Array: URLs (or paths) of files to check
527 * @param $flags Integer: bitwise combination of the following flags:
528 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
529 * @return Either array of files and existence flags, or false
531 abstract function fileExistsBatch( $files, $flags = 0 );
534 * Move a group of files to the deletion archive.
536 * If no valid deletion archive is configured, this may either delete the
537 * file or throw an exception, depending on the preference of the repository.
539 * The overwrite policy is determined by the repository -- currently FSRepo
540 * assumes a naming scheme in the deleted zone based on content hash, as
541 * opposed to the public zone which is assumed to be unique.
543 * @param $sourceDestPairs Array of source/destination pairs. Each element
544 * is a two-element array containing the source file path relative to the
545 * public root in the first element, and the archive file path relative
546 * to the deleted zone root in the second element.
547 * @return FileRepoStatus
549 abstract function deleteBatch( $sourceDestPairs );
552 * Move a file to the deletion archive.
553 * If no valid deletion archive exists, this may either delete the file
554 * or throw an exception, depending on the preference of the repository
555 * @param $srcRel Mixed: relative path for the file to be deleted
556 * @param $archiveRel Mixed: relative path for the archive location.
557 * Relative to a private archive directory.
558 * @return FileRepoStatus object
560 function delete( $srcRel, $archiveRel ) {
561 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
565 * Get properties of a file with a given virtual URL
566 * The virtual URL must refer to this repo
567 * Properties should ultimately be obtained via File::getPropsFromPath()
569 * @param $virtualUrl string
571 abstract function getFileProps( $virtualUrl );
574 * Call a callback function for every file in the repository
575 * May use either the database or the filesystem
578 function enumFiles( $callback ) {
579 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
583 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
585 * @param $filename string
589 function validateFilename( $filename ) {
590 if ( strval( $filename ) == '' ) {
593 if ( wfIsWindows() ) {
594 $filename = strtr( $filename, '\\', '/' );
597 * Use the same traversal protection as Title::secureAndSplit()
599 if ( strpos( $filename, '.' ) !== false &&
600 ( $filename === '.' ||
$filename === '..' ||
601 strpos( $filename, './' ) === 0 ||
602 strpos( $filename, '../' ) === 0 ||
603 strpos( $filename, '/./' ) !== false ||
604 strpos( $filename, '/../' ) !== false ) )
613 * Path disclosure protection functions
615 function paranoidClean( $param ) { return '[hidden]'; }
621 function passThrough( $param ) { return $param; }
624 * Get a callback function to use for cleaning error message parameters
626 function getErrorCleanupFunction() {
627 switch ( $this->pathDisclosureProtection
) {
629 $callback = array( $this, 'passThrough' );
631 default: // 'paranoid'
632 $callback = array( $this, 'paranoidClean' );
639 * Create a new fatal error
641 function newFatal( $message /*, parameters...*/ ) {
642 $params = func_get_args();
643 array_unshift( $params, $this );
644 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
648 * Create a new good result
650 * @return FileRepoStatus
652 function newGood( $value = null ) {
653 return FileRepoStatus
::newGood( $this, $value );
657 * Delete files in the deleted directory if they are not referenced in the filearchive table
660 function cleanupDeletedBatch( $storageKeys ) {}
663 * Checks if there is a redirect named as $title. If there is, return the
664 * title object. If not, return false.
667 * @param $title Title of image
670 function checkRedirect( $title ) {
675 * Invalidates image redirect cache related to that image
676 * Doesn't do anything for repositories that don't support image redirects.
679 * @param $title Title of image
681 function invalidateImageRedirect( $title ) {}
684 * Get an array or iterator of file objects for files that have a given
685 * SHA-1 content hash.
689 function findBySha1( $hash ) {
694 * Get the human-readable name of the repo.
697 public function getDisplayName() {
698 // We don't name our own repo, return nothing
699 if ( $this->isLocal() ) {
702 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
703 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
707 * Returns true if this the local file repository.
712 return $this->getName() == 'local';
716 * Get a key on the primary cache for this repository.
717 * Returns false if the repository's cache is not accessible at this site.
718 * The parameters are the parts of the key, as for wfMemcKey().
722 function getSharedCacheKey( /*...*/ ) {
727 * Get a key for this repo in the local cache domain. These cache keys are
728 * not shared with remote instances of the repo.
729 * The parameters are the parts of the key, as for wfMemcKey().
731 function getLocalCacheKey( /*...*/ ) {
732 $args = func_get_args();
733 array_unshift( $args, 'filerepo', $this->getName() );
734 return call_user_func_array( 'wfMemcKey', $args );
738 * Get an UploadStash associated with this repo.
740 * @return UploadStash
742 function getUploadStash() {
743 return new UploadStash( $this );