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
56 static function isVirtualUrl( $url ) {
57 return substr( $url, 0, 9 ) == 'mwrepo://';
61 * Create a new File object from the local repository
63 * @param $title Mixed: Title object or string
64 * @param $time Mixed: Time at which the image was uploaded.
65 * If this is specified, the returned object will be an
66 * instance of the repository's old file class instead of a
67 * current file. Repositories not supporting version control
68 * should return false if this parameter is set.
72 function newFile( $title, $time = false ) {
73 if ( !($title instanceof Title
) ) {
74 $title = Title
::makeTitleSafe( NS_FILE
, $title );
75 if ( !is_object( $title ) ) {
80 if ( $this->oldFileFactory
) {
81 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
86 return call_user_func( $this->fileFactory
, $title, $this );
91 * Find an instance of the named file created at the specified time
92 * Returns false if the file does not exist. Repositories not supporting
93 * version control should return false if the time is specified.
95 * @param $title Mixed: Title object or string
96 * @param $options Associative array of options:
97 * time: requested time for an archived image, or false for the
98 * current version. An image object will be returned which was
99 * created at the specified time.
101 * ignoreRedirect: If true, do not follow file redirects
103 * private: If true, return restricted (deleted) files if the current
104 * user is allowed to view them. Otherwise, such files will not
107 function findFile( $title, $options = array() ) {
108 if ( !is_array( $options ) ) {
112 $time = isset( $options['time'] ) ?
$options['time'] : false;
114 if ( !($title instanceof Title
) ) {
115 $title = Title
::makeTitleSafe( NS_FILE
, $title );
116 if ( !is_object( $title ) ) {
120 # First try the current version of the file to see if it precedes the timestamp
121 $img = $this->newFile( $title );
125 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
128 # Now try an old version of the file
129 if ( $time !== false ) {
130 $img = $this->newFile( $title, $time );
131 if ( $img && $img->exists() ) {
132 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
134 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
141 if ( !empty( $options['ignoreRedirect'] ) ) {
144 $redir = $this->checkRedirect( $title );
145 if( $redir && $title->getNamespace() == NS_FILE
) {
146 $img = $this->newFile( $redir );
150 if( $img->exists() ) {
151 $img->redirectedFrom( $title->getDBkey() );
159 * Find many files at once.
160 * @param $items An array of titles, or an array of findFile() options with
161 * the "title" option giving the title. Example:
163 * $findItem = array( 'title' => $title, 'private' => true );
164 * $findBatch = array( $findItem );
165 * $repo->findFiles( $findBatch );
167 function findFiles( $items ) {
169 foreach ( $items as $item ) {
170 if ( is_array( $item ) ) {
171 $title = $item['title'];
173 unset( $options['title'] );
178 $file = $this->findFile( $title, $options );
180 $result[$file->getTitle()->getDBkey()] = $file;
187 * Create a new File object from the local repository
188 * @param $sha1 Mixed: SHA-1 key
189 * @param $time Mixed: time at which the image was uploaded.
190 * If this is specified, the returned object will be an
191 * of the repository's old file class instead of a current
192 * file. Repositories not supporting version control should
193 * return false if this parameter is set.
197 function newFileFromKey( $sha1, $time = false ) {
199 if ( $this->oldFileFactoryKey
) {
200 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
205 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
210 * Find an instance of the file with this key, created at the specified time
211 * Returns false if the file does not exist. Repositories not supporting
212 * version control should return false if the time is specified.
214 * @param $sha1 String
215 * @param $options Option array, same as findFile().
217 function findFileFromKey( $sha1, $options = array() ) {
218 if ( !is_array( $options ) ) {
222 $time = isset( $options['time'] ) ?
$options['time'] : false;
225 # First try the current version of the file to see if it precedes the timestamp
226 $img = $this->newFileFromKey( $sha1 );
230 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
233 # Now try an old version of the file
234 if ( $time !== false ) {
235 $img = $this->newFileFromKey( $sha1, $time );
236 if ( $img->exists() ) {
237 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
239 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
248 * Get the URL of thumb.php
250 function getThumbScriptUrl() {
251 return $this->thumbScriptUrl
;
255 * Get the URL corresponding to one of the four basic zones
256 * @param $zone String: one of: public, deleted, temp, thumb
257 * @return String or false
259 function getZoneUrl( $zone ) {
264 * Returns true if the repository can transform files via a 404 handler
266 function canTransformVia404() {
267 return $this->transformVia404
;
271 * Get the name of an image from its title object
272 * @param $title Title
274 function getNameFromTitle( $title ) {
275 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
277 $name = $title->getUserCaseDBKey();
278 if ( $this->initialCapital
) {
279 $name = $wgContLang->ucfirst( $name );
282 $name = $title->getDBkey();
287 static function getHashPathForLevel( $name, $levels ) {
288 if ( $levels == 0 ) {
291 $hash = md5( $name );
293 for ( $i = 1; $i <= $levels; $i++
) {
294 $path .= substr( $hash, 0, $i ) . '/';
301 * Get a relative path including trailing slash, e.g. f/fa/
302 * If the repo is not hashed, returns an empty string
304 function getHashPath( $name ) {
305 return self
::getHashPathForLevel( $name, $this->hashLevels
);
309 * Get the name of this repository, as specified by $info['name]' to the constructor
316 * Make an url to this repo
318 * @param $query mixed Query string to append
319 * @param $entry string Entry point; defaults to index
322 function makeUrl( $query = '', $entry = 'index' ) {
323 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
324 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
328 * Get the URL of an image description page. May return false if it is
329 * unknown or not applicable. In general this should only be called by the
330 * File class, since it may return invalid results for certain kinds of
331 * repositories. Use File::getDescriptionUrl() in user code.
333 * In particular, it uses the article paths as specified to the repository
334 * constructor, whereas local repositories use the local Title functions.
336 function getDescriptionUrl( $name ) {
337 $encName = wfUrlencode( $name );
338 if ( !is_null( $this->descBaseUrl
) ) {
339 # "http://example.com/wiki/Image:"
340 return $this->descBaseUrl
. $encName;
342 if ( !is_null( $this->articleUrl
) ) {
343 # "http://example.com/wiki/$1"
345 # We use "Image:" as the canonical namespace for
346 # compatibility across all MediaWiki versions.
347 return str_replace( '$1',
348 "Image:$encName", $this->articleUrl
);
350 if ( !is_null( $this->scriptDirUrl
) ) {
351 # "http://example.com/w"
353 # We use "Image:" as the canonical namespace for
354 # compatibility across all MediaWiki versions,
355 # and just sort of hope index.php is right. ;)
356 return $this->makeUrl( "title=Image:$encName" );
362 * Get the URL of the content-only fragment of the description page. For
363 * MediaWiki this means action=render. This should only be called by the
364 * repository's file class, since it may return invalid results. User code
365 * should use File::getDescriptionText().
366 * @param $name String: name of image to fetch
367 * @param $lang String: language to fetch it in, if any.
369 function getDescriptionRenderUrl( $name, $lang = null ) {
370 $query = 'action=render';
371 if ( !is_null( $lang ) ) {
372 $query .= '&uselang=' . $lang;
374 if ( isset( $this->scriptDirUrl
) ) {
375 return $this->makeUrl(
377 wfUrlencode( 'Image:' . $name ) .
380 $descUrl = $this->getDescriptionUrl( $name );
382 return wfAppendQuery( $descUrl, $query );
390 * Get the URL of the stylesheet to apply to description pages
393 function getDescriptionStylesheetUrl() {
394 if ( $this->scriptDirUrl
) {
395 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
396 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
401 * Store a file to a given destination.
403 * @param $srcPath String: source path or virtual URL
404 * @param $dstZone String: destination zone
405 * @param $dstRel String: destination relative path
406 * @param $flags Integer: bitwise combination of the following flags:
407 * self::DELETE_SOURCE Delete the source file after upload
408 * self::OVERWRITE Overwrite an existing destination file instead of failing
409 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
410 * same contents as the source
411 * @return FileRepoStatus
413 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
414 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
415 if ( $status->successCount
== 0 ) {
422 * Store a batch of files
424 * @param $triplets Array: (src,zone,dest) triplets as per store()
425 * @param $flags Integer: flags as per store
427 abstract function storeBatch( $triplets, $flags = 0 );
430 * Pick a random name in the temp zone and store a file to it.
431 * Returns a FileRepoStatus object with the URL in the value.
433 * @param $originalName String: the base name of the file as specified
434 * by the user. The file extension will be maintained.
435 * @param $srcPath String: the current location of the file.
437 abstract function storeTemp( $originalName, $srcPath );
441 * Append the contents of the source path to the given file.
442 * @param $srcPath String: location of the source file
443 * @param $toAppendPath String: path to append to.
444 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
445 * that the source file should be deleted if possible
446 * @return mixed Status or false
448 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
451 * Remove a temporary file or mark it for garbage collection
452 * @param $virtualUrl String: the virtual URL returned by storeTemp
453 * @return Boolean: true on success, false on failure
456 function freeTemp( $virtualUrl ) {
461 * Copy or move a file either from the local filesystem or from an mwrepo://
462 * virtual URL, into this repository at the specified destination location.
464 * Returns a FileRepoStatus object. On success, the value contains "new" or
465 * "archived", to indicate whether the file was new with that name.
467 * @param $srcPath String: the source path or URL
468 * @param $dstRel String: the destination relative path
469 * @param $archiveRel String: rhe relative path where the existing file is to
470 * be archived, if there is one. Relative to the public zone root.
471 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
472 * that the source file should be deleted if possible
474 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
475 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
476 if ( $status->successCount
== 0 ) {
479 if ( isset( $status->value
[0] ) ) {
480 $status->value
= $status->value
[0];
482 $status->value
= false;
488 * Publish a batch of files
489 * @param $triplets Array: (source,dest,archive) triplets as per publish()
490 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
491 * that the source files should be deleted if possible
493 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 abstract function getFileProps( $virtualUrl );
549 * Call a callback function for every file in the repository
550 * May use either the database or the filesystem
553 function enumFiles( $callback ) {
554 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
558 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
560 function validateFilename( $filename ) {
561 if ( strval( $filename ) == '' ) {
564 if ( wfIsWindows() ) {
565 $filename = strtr( $filename, '\\', '/' );
568 * Use the same traversal protection as Title::secureAndSplit()
570 if ( strpos( $filename, '.' ) !== false &&
571 ( $filename === '.' ||
$filename === '..' ||
572 strpos( $filename, './' ) === 0 ||
573 strpos( $filename, '../' ) === 0 ||
574 strpos( $filename, '/./' ) !== false ||
575 strpos( $filename, '/../' ) !== false ) )
584 * Path disclosure protection functions
586 function paranoidClean( $param ) { return '[hidden]'; }
587 function passThrough( $param ) { return $param; }
590 * Get a callback function to use for cleaning error message parameters
592 function getErrorCleanupFunction() {
593 switch ( $this->pathDisclosureProtection
) {
595 $callback = array( $this, 'passThrough' );
597 default: // 'paranoid'
598 $callback = array( $this, 'paranoidClean' );
605 * Create a new fatal error
607 function newFatal( $message /*, parameters...*/ ) {
608 $params = func_get_args();
609 array_unshift( $params, $this );
610 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
614 * Create a new good result
616 function newGood( $value = null ) {
617 return FileRepoStatus
::newGood( $this, $value );
621 * Delete files in the deleted directory if they are not referenced in the filearchive table
624 function cleanupDeletedBatch( $storageKeys ) {}
627 * Checks if there is a redirect named as $title. If there is, return the
628 * title object. If not, return false.
631 * @param $title Title of image
634 function checkRedirect( $title ) {
639 * Invalidates image redirect cache related to that image
640 * Doesn't do anything for repositories that don't support image redirects.
643 * @param $title Title of image
645 function invalidateImageRedirect( $title ) {}
648 * Get an array or iterator of file objects for files that have a given
649 * SHA-1 content hash.
653 function findBySha1( $hash ) {
658 * Get the human-readable name of the repo.
661 public function getDisplayName() {
662 // We don't name our own repo, return nothing
663 if ( $this->isLocal() ) {
666 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
667 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
671 * Returns true if this the local file repository.
676 return $this->getName() == 'local';
681 * Get a key on the primary cache for this repository.
682 * Returns false if the repository's cache is not accessible at this site.
683 * The parameters are the parts of the key, as for wfMemcKey().
687 function getSharedCacheKey( /*...*/ ) {
692 * Get a key for this repo in the local cache domain. These cache keys are
693 * not shared with remote instances of the repo.
694 * The parameters are the parts of the key, as for wfMemcKey().
696 function getLocalCacheKey( /*...*/ ) {
697 $args = func_get_args();
698 array_unshift( $args, 'filerepo', $this->getName() );
699 return call_user_func_array( 'wfMemcKey', $args );
703 * Get an UploadStash associated with this repo.
705 function getUploadStash() {
706 return new UploadStash( $this );