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
) ) {
134 return $img; // always OK
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 * Find an instance of the file with this key, created at the specified time
191 * Returns false if the file does not exist. Repositories not supporting
192 * version control should return false if the time is specified.
194 * @param $sha1 String base 36 SHA-1 hash
195 * @param $options Option array, same as findFile().
197 function findFileFromKey( $sha1, $options = array() ) {
198 $time = isset( $options['time'] ) ?
$options['time'] : false;
200 # First try to find a matching current version of a file...
201 if ( $this->fileFactoryKey
) {
202 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
204 return false; // find-by-sha1 not supported
206 if ( $img && $img->exists() ) {
209 # Now try to find a matching old version of a file...
210 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
211 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
212 if ( $img && $img->exists() ) {
213 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
214 return $img; // always OK
215 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
224 * Get the URL of thumb.php
226 function getThumbScriptUrl() {
227 return $this->thumbScriptUrl
;
231 * Get the URL corresponding to one of the four basic zones
232 * @param $zone String: one of: public, deleted, temp, thumb
233 * @return String or false
235 function getZoneUrl( $zone ) {
240 * Returns true if the repository can transform files via a 404 handler
244 function canTransformVia404() {
245 return $this->transformVia404
;
249 * Get the name of an image from its title object
250 * @param $title Title
252 function getNameFromTitle( Title
$title ) {
253 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
255 $name = $title->getUserCaseDBKey();
256 if ( $this->initialCapital
) {
257 $name = $wgContLang->ucfirst( $name );
260 $name = $title->getDBkey();
270 static function getHashPathForLevel( $name, $levels ) {
271 if ( $levels == 0 ) {
274 $hash = md5( $name );
276 for ( $i = 1; $i <= $levels; $i++
) {
277 $path .= substr( $hash, 0, $i ) . '/';
284 * Get a relative path including trailing slash, e.g. f/fa/
285 * If the repo is not hashed, returns an empty string
287 * @param $name string
291 function getHashPath( $name ) {
292 return self
::getHashPathForLevel( $name, $this->hashLevels
);
296 * Get the name of this repository, as specified by $info['name]' to the constructor
303 * Make an url to this repo
305 * @param $query mixed Query string to append
306 * @param $entry string Entry point; defaults to index
309 function makeUrl( $query = '', $entry = 'index' ) {
310 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
311 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
315 * Get the URL of an image description page. May return false if it is
316 * unknown or not applicable. In general this should only be called by the
317 * File class, since it may return invalid results for certain kinds of
318 * repositories. Use File::getDescriptionUrl() in user code.
320 * In particular, it uses the article paths as specified to the repository
321 * constructor, whereas local repositories use the local Title functions.
323 function getDescriptionUrl( $name ) {
324 $encName = wfUrlencode( $name );
325 if ( !is_null( $this->descBaseUrl
) ) {
326 # "http://example.com/wiki/Image:"
327 return $this->descBaseUrl
. $encName;
329 if ( !is_null( $this->articleUrl
) ) {
330 # "http://example.com/wiki/$1"
332 # We use "Image:" as the canonical namespace for
333 # compatibility across all MediaWiki versions.
334 return str_replace( '$1',
335 "Image:$encName", $this->articleUrl
);
337 if ( !is_null( $this->scriptDirUrl
) ) {
338 # "http://example.com/w"
340 # We use "Image:" as the canonical namespace for
341 # compatibility across all MediaWiki versions,
342 # and just sort of hope index.php is right. ;)
343 return $this->makeUrl( "title=Image:$encName" );
349 * Get the URL of the content-only fragment of the description page. For
350 * MediaWiki this means action=render. This should only be called by the
351 * repository's file class, since it may return invalid results. User code
352 * should use File::getDescriptionText().
353 * @param $name String: name of image to fetch
354 * @param $lang String: language to fetch it in, if any.
356 function getDescriptionRenderUrl( $name, $lang = null ) {
357 $query = 'action=render';
358 if ( !is_null( $lang ) ) {
359 $query .= '&uselang=' . $lang;
361 if ( isset( $this->scriptDirUrl
) ) {
362 return $this->makeUrl(
364 wfUrlencode( 'Image:' . $name ) .
367 $descUrl = $this->getDescriptionUrl( $name );
369 return wfAppendQuery( $descUrl, $query );
377 * Get the URL of the stylesheet to apply to description pages
380 function getDescriptionStylesheetUrl() {
381 if ( $this->scriptDirUrl
) {
382 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
383 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
388 * Store a file to a given destination.
390 * @param $srcPath String: source path or virtual URL
391 * @param $dstZone String: destination zone
392 * @param $dstRel String: destination relative path
393 * @param $flags Integer: bitwise combination of the following flags:
394 * self::DELETE_SOURCE Delete the source file after upload
395 * self::OVERWRITE Overwrite an existing destination file instead of failing
396 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
397 * same contents as the source
398 * @return FileRepoStatus
400 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
401 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
402 if ( $status->successCount
== 0 ) {
409 * Store a batch of files
411 * @param $triplets Array: (src,zone,dest) triplets as per store()
412 * @param $flags Integer: flags as per store
414 abstract function storeBatch( $triplets, $flags = 0 );
417 * Pick a random name in the temp zone and store a file to it.
418 * Returns a FileRepoStatus object with the URL in the value.
420 * @param $originalName String: the base name of the file as specified
421 * by the user. The file extension will be maintained.
422 * @param $srcPath String: the current location of the file.
424 abstract function storeTemp( $originalName, $srcPath );
428 * Append the contents of the source path to the given file, OR queue
429 * the appending operation in anticipation of a later appendFinish() call.
430 * @param $srcPath String: location of the source file
431 * @param $toAppendPath String: path to append to.
432 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
433 * that the source file should be deleted if possible
434 * @return mixed Status or false
436 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
439 * Finish the append operation.
440 * @param $toAppendPath String: path to append to.
441 * @return mixed Status or false
443 abstract function appendFinish( $toAppendPath );
446 * Remove a temporary file or mark it for garbage collection
447 * @param $virtualUrl String: the virtual URL returned by storeTemp
448 * @return Boolean: true on success, false on failure
451 function freeTemp( $virtualUrl ) {
456 * Copy or move a file either from the local filesystem or from an mwrepo://
457 * virtual URL, into this repository at the specified destination location.
459 * Returns a FileRepoStatus object. On success, the value contains "new" or
460 * "archived", to indicate whether the file was new with that name.
462 * @param $srcPath String: the source path or URL
463 * @param $dstRel String: the destination relative path
464 * @param $archiveRel String: rhe relative path where the existing file is to
465 * be archived, if there is one. Relative to the public zone root.
466 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
467 * that the source file should be deleted if possible
469 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
470 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
471 if ( $status->successCount
== 0 ) {
474 if ( isset( $status->value
[0] ) ) {
475 $status->value
= $status->value
[0];
477 $status->value
= false;
483 * Publish a batch of files
484 * @param $triplets Array: (source,dest,archive) triplets as per publish()
485 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
486 * that the source files should be deleted if possible
488 abstract function publishBatch( $triplets, $flags = 0 );
495 function fileExists( $file, $flags = 0 ) {
496 $result = $this->fileExistsBatch( array( $file ), $flags );
501 * Checks existence of an array of files.
503 * @param $files Array: URLs (or paths) of files to check
504 * @param $flags Integer: bitwise combination of the following flags:
505 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
506 * @return Either array of files and existence flags, or false
508 abstract function fileExistsBatch( $files, $flags = 0 );
511 * Move a group of files to the deletion archive.
513 * If no valid deletion archive is configured, this may either delete the
514 * file or throw an exception, depending on the preference of the repository.
516 * The overwrite policy is determined by the repository -- currently FSRepo
517 * assumes a naming scheme in the deleted zone based on content hash, as
518 * opposed to the public zone which is assumed to be unique.
520 * @param $sourceDestPairs Array of source/destination pairs. Each element
521 * is a two-element array containing the source file path relative to the
522 * public root in the first element, and the archive file path relative
523 * to the deleted zone root in the second element.
524 * @return FileRepoStatus
526 abstract function deleteBatch( $sourceDestPairs );
529 * Move a file to the deletion archive.
530 * If no valid deletion archive exists, this may either delete the file
531 * or throw an exception, depending on the preference of the repository
532 * @param $srcRel Mixed: relative path for the file to be deleted
533 * @param $archiveRel Mixed: relative path for the archive location.
534 * Relative to a private archive directory.
535 * @return FileRepoStatus object
537 function delete( $srcRel, $archiveRel ) {
538 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
542 * Get properties of a file with a given virtual URL
543 * The virtual URL must refer to this repo
544 * Properties should ultimately be obtained via File::getPropsFromPath()
546 * @param $virtualUrl string
548 abstract function getFileProps( $virtualUrl );
551 * Call a callback function for every file in the repository
552 * May use either the database or the filesystem
555 function enumFiles( $callback ) {
556 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
560 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
562 * @param $filename string
566 function validateFilename( $filename ) {
567 if ( strval( $filename ) == '' ) {
570 if ( wfIsWindows() ) {
571 $filename = strtr( $filename, '\\', '/' );
574 * Use the same traversal protection as Title::secureAndSplit()
576 if ( strpos( $filename, '.' ) !== false &&
577 ( $filename === '.' ||
$filename === '..' ||
578 strpos( $filename, './' ) === 0 ||
579 strpos( $filename, '../' ) === 0 ||
580 strpos( $filename, '/./' ) !== false ||
581 strpos( $filename, '/../' ) !== false ) )
590 * Path disclosure protection functions
592 function paranoidClean( $param ) { return '[hidden]'; }
598 function passThrough( $param ) { return $param; }
601 * Get a callback function to use for cleaning error message parameters
603 function getErrorCleanupFunction() {
604 switch ( $this->pathDisclosureProtection
) {
606 $callback = array( $this, 'passThrough' );
608 default: // 'paranoid'
609 $callback = array( $this, 'paranoidClean' );
616 * Create a new fatal error
618 function newFatal( $message /*, parameters...*/ ) {
619 $params = func_get_args();
620 array_unshift( $params, $this );
621 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
625 * Create a new good result
627 * @return FileRepoStatus
629 function newGood( $value = null ) {
630 return FileRepoStatus
::newGood( $this, $value );
634 * Delete files in the deleted directory if they are not referenced in the filearchive table
637 function cleanupDeletedBatch( $storageKeys ) {}
640 * Checks if there is a redirect named as $title. If there is, return the
641 * title object. If not, return false.
644 * @param $title Title of image
647 function checkRedirect( Title
$title ) {
652 * Invalidates image redirect cache related to that image
653 * Doesn't do anything for repositories that don't support image redirects.
656 * @param $title Title of image
658 function invalidateImageRedirect( $title ) {}
661 * Get an array or iterator of file objects for files that have a given
662 * SHA-1 content hash.
666 function findBySha1( $hash ) {
671 * Get the human-readable name of the repo.
674 public function getDisplayName() {
675 // We don't name our own repo, return nothing
676 if ( $this->isLocal() ) {
679 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
680 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
684 * Returns true if this the local file repository.
689 return $this->getName() == 'local';
693 * Get a key on the primary cache for this repository.
694 * Returns false if the repository's cache is not accessible at this site.
695 * The parameters are the parts of the key, as for wfMemcKey().
699 function getSharedCacheKey( /*...*/ ) {
704 * Get a key for this repo in the local cache domain. These cache keys are
705 * not shared with remote instances of the repo.
706 * The parameters are the parts of the key, as for wfMemcKey().
708 function getLocalCacheKey( /*...*/ ) {
709 $args = func_get_args();
710 array_unshift( $args, 'filerepo', $this->getName() );
711 return call_user_func_array( 'wfMemcKey', $args );
715 * Get an UploadStash associated with this repo.
717 * @return UploadStash
719 function getUploadStash() {
720 return new UploadStash( $this );