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;
34 function __construct( $info ) {
36 $this->name
= $info['name'];
39 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
40 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
41 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
42 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
45 if ( isset( $info[$var] ) ) {
46 $this->$var = $info[$var];
49 $this->transformVia404
= !empty( $info['transformVia404'] );
53 * Determine if a string is an mwrepo:// URL
55 static function isVirtualUrl( $url ) {
56 return substr( $url, 0, 9 ) == 'mwrepo://';
60 * Create a new File object from the local repository
62 * @param $title Mixed: Title object or string
63 * @param $time Mixed: Time at which the image was uploaded.
64 * If this is specified, the returned object will be an
65 * instance of the repository's old file class instead of a
66 * current file. Repositories not supporting version control
67 * should return false if this parameter is set.
71 function newFile( $title, $time = false ) {
72 if ( !($title instanceof Title
) ) {
73 $title = Title
::makeTitleSafe( NS_FILE
, $title );
74 if ( !is_object( $title ) ) {
79 if ( $this->oldFileFactory
) {
80 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
85 return call_user_func( $this->fileFactory
, $title, $this );
90 * Find an instance of the named file created at the specified time
91 * Returns false if the file does not exist. Repositories not supporting
92 * version control should return false if the time is specified.
94 * @param $title Mixed: Title object or string
95 * @param $options Associative array of options:
96 * time: requested time for an archived image, or false for the
97 * current version. An image object will be returned which was
98 * created at the specified time.
100 * ignoreRedirect: If true, do not follow file redirects
102 * private: If true, return restricted (deleted) files if the current
103 * user is allowed to view them. Otherwise, such files will not
106 function findFile( $title, $options = array() ) {
107 $time = isset( $options['time'] ) ?
$options['time'] : false;
108 if ( !($title instanceof Title
) ) {
109 $title = Title
::makeTitleSafe( NS_FILE
, $title );
110 if ( !is_object( $title ) ) {
114 # First try the current version of the file to see if it precedes the timestamp
115 $img = $this->newFile( $title );
119 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
122 # Now try an old version of the file
123 if ( $time !== false ) {
124 $img = $this->newFile( $title, $time );
125 if ( $img && $img->exists() ) {
126 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
128 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
135 if ( !empty( $options['ignoreRedirect'] ) ) {
138 $redir = $this->checkRedirect( $title );
139 if( $redir && $title->getNamespace() == NS_FILE
) {
140 $img = $this->newFile( $redir );
144 if( $img->exists() ) {
145 $img->redirectedFrom( $title->getDBkey() );
153 * Find many files at once.
154 * @param $items An array of titles, or an array of findFile() options with
155 * the "title" option giving the title. Example:
157 * $findItem = array( 'title' => $title, 'private' => true );
158 * $findBatch = array( $findItem );
159 * $repo->findFiles( $findBatch );
161 function findFiles( $items ) {
163 foreach ( $items as $item ) {
164 if ( is_array( $item ) ) {
165 $title = $item['title'];
167 unset( $options['title'] );
172 $file = $this->findFile( $title, $options );
174 $result[$file->getTitle()->getDBkey()] = $file;
181 * Get the URL of thumb.php
183 function getThumbScriptUrl() {
184 return $this->thumbScriptUrl
;
188 * Get the URL corresponding to one of the four basic zones
189 * @param $zone String: one of: public, deleted, temp, thumb
190 * @return String or false
192 function getZoneUrl( $zone ) {
197 * Returns true if the repository can transform files via a 404 handler
199 function canTransformVia404() {
200 return $this->transformVia404
;
204 * Get the name of an image from its title object
205 * @param $title Title
207 function getNameFromTitle( $title ) {
208 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
210 $name = $title->getUserCaseDBKey();
211 if ( $this->initialCapital
) {
212 $name = $wgContLang->ucfirst( $name );
215 $name = $title->getDBkey();
220 static function getHashPathForLevel( $name, $levels ) {
221 if ( $levels == 0 ) {
224 $hash = md5( $name );
226 for ( $i = 1; $i <= $levels; $i++
) {
227 $path .= substr( $hash, 0, $i ) . '/';
234 * Get a relative path including trailing slash, e.g. f/fa/
235 * If the repo is not hashed, returns an empty string
237 function getHashPath( $name ) {
238 return self
::getHashPathForLevel( $name, $this->hashLevels
);
242 * Get the name of this repository, as specified by $info['name]' to the constructor
249 * Make an url to this repo
251 * @param $query mixed Query string to append
252 * @param $entry string Entry point; defaults to index
255 function makeUrl( $query = '', $entry = 'index' ) {
256 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
257 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
261 * Get the URL of an image description page. May return false if it is
262 * unknown or not applicable. In general this should only be called by the
263 * File class, since it may return invalid results for certain kinds of
264 * repositories. Use File::getDescriptionUrl() in user code.
266 * In particular, it uses the article paths as specified to the repository
267 * constructor, whereas local repositories use the local Title functions.
269 function getDescriptionUrl( $name ) {
270 $encName = wfUrlencode( $name );
271 if ( !is_null( $this->descBaseUrl
) ) {
272 # "http://example.com/wiki/Image:"
273 return $this->descBaseUrl
. $encName;
275 if ( !is_null( $this->articleUrl
) ) {
276 # "http://example.com/wiki/$1"
278 # We use "Image:" as the canonical namespace for
279 # compatibility across all MediaWiki versions.
280 return str_replace( '$1',
281 "Image:$encName", $this->articleUrl
);
283 if ( !is_null( $this->scriptDirUrl
) ) {
284 # "http://example.com/w"
286 # We use "Image:" as the canonical namespace for
287 # compatibility across all MediaWiki versions,
288 # and just sort of hope index.php is right. ;)
289 return $this->makeUrl( "title=Image:$encName" );
295 * Get the URL of the content-only fragment of the description page. For
296 * MediaWiki this means action=render. This should only be called by the
297 * repository's file class, since it may return invalid results. User code
298 * should use File::getDescriptionText().
299 * @param $name String: name of image to fetch
300 * @param $lang String: language to fetch it in, if any.
302 function getDescriptionRenderUrl( $name, $lang = null ) {
303 $query = 'action=render';
304 if ( !is_null( $lang ) ) {
305 $query .= '&uselang=' . $lang;
307 if ( isset( $this->scriptDirUrl
) ) {
308 return $this->makeUrl(
310 wfUrlencode( 'Image:' . $name ) .
313 $descUrl = $this->getDescriptionUrl( $name );
315 return wfAppendQuery( $descUrl, $query );
323 * Get the URL of the stylesheet to apply to description pages
326 function getDescriptionStylesheetUrl() {
327 if ( $this->scriptDirUrl
) {
328 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
329 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
334 * Store a file to a given destination.
336 * @param $srcPath String: source path or virtual URL
337 * @param $dstZone String: destination zone
338 * @param $dstRel String: destination relative path
339 * @param $flags Integer: bitwise combination of the following flags:
340 * self::DELETE_SOURCE Delete the source file after upload
341 * self::OVERWRITE Overwrite an existing destination file instead of failing
342 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
343 * same contents as the source
344 * @return FileRepoStatus
346 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
347 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
348 if ( $status->successCount
== 0 ) {
355 * Store a batch of files
357 * @param $triplets Array: (src,zone,dest) triplets as per store()
358 * @param $flags Integer: flags as per store
360 abstract function storeBatch( $triplets, $flags = 0 );
363 * Pick a random name in the temp zone and store a file to it.
364 * Returns a FileRepoStatus object with the URL in the value.
366 * @param $originalName String: the base name of the file as specified
367 * by the user. The file extension will be maintained.
368 * @param $srcPath String: the current location of the file.
370 abstract function storeTemp( $originalName, $srcPath );
374 * Append the contents of the source path to the given file.
375 * @param $srcPath String: location of the source file
376 * @param $toAppendPath String: path to append to.
377 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
378 * that the source file should be deleted if possible
379 * @return mixed Status or false
381 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
384 * Remove a temporary file or mark it for garbage collection
385 * @param $virtualUrl String: the virtual URL returned by storeTemp
386 * @return Boolean: true on success, false on failure
389 function freeTemp( $virtualUrl ) {
394 * Copy or move a file either from the local filesystem or from an mwrepo://
395 * virtual URL, into this repository at the specified destination location.
397 * Returns a FileRepoStatus object. On success, the value contains "new" or
398 * "archived", to indicate whether the file was new with that name.
400 * @param $srcPath String: the source path or URL
401 * @param $dstRel String: the destination relative path
402 * @param $archiveRel String: rhe relative path where the existing file is to
403 * be archived, if there is one. Relative to the public zone root.
404 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
405 * that the source file should be deleted if possible
407 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
408 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
409 if ( $status->successCount
== 0 ) {
412 if ( isset( $status->value
[0] ) ) {
413 $status->value
= $status->value
[0];
415 $status->value
= false;
421 * Publish a batch of files
422 * @param $triplets Array: (source,dest,archive) triplets as per publish()
423 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
424 * that the source files should be deleted if possible
426 abstract function publishBatch( $triplets, $flags = 0 );
428 function fileExists( $file, $flags = 0 ) {
429 $result = $this->fileExistsBatch( array( $file ), $flags );
434 * Checks existence of an array of files.
436 * @param $files Array: URLs (or paths) of files to check
437 * @param $flags Integer: bitwise combination of the following flags:
438 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
439 * @return Either array of files and existence flags, or false
441 abstract function fileExistsBatch( $files, $flags = 0 );
444 * Move a group of files to the deletion archive.
446 * If no valid deletion archive is configured, this may either delete the
447 * file or throw an exception, depending on the preference of the repository.
449 * The overwrite policy is determined by the repository -- currently FSRepo
450 * assumes a naming scheme in the deleted zone based on content hash, as
451 * opposed to the public zone which is assumed to be unique.
453 * @param $sourceDestPairs Array of source/destination pairs. Each element
454 * is a two-element array containing the source file path relative to the
455 * public root in the first element, and the archive file path relative
456 * to the deleted zone root in the second element.
457 * @return FileRepoStatus
459 abstract function deleteBatch( $sourceDestPairs );
462 * Move a file to the deletion archive.
463 * If no valid deletion archive exists, this may either delete the file
464 * or throw an exception, depending on the preference of the repository
465 * @param $srcRel Mixed: relative path for the file to be deleted
466 * @param $archiveRel Mixed: relative path for the archive location.
467 * Relative to a private archive directory.
468 * @return FileRepoStatus object
470 function delete( $srcRel, $archiveRel ) {
471 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
475 * Get properties of a file with a given virtual URL
476 * The virtual URL must refer to this repo
477 * Properties should ultimately be obtained via File::getPropsFromPath()
479 abstract function getFileProps( $virtualUrl );
482 * Call a callback function for every file in the repository
483 * May use either the database or the filesystem
486 function enumFiles( $callback ) {
487 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
491 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
493 function validateFilename( $filename ) {
494 if ( strval( $filename ) == '' ) {
497 if ( wfIsWindows() ) {
498 $filename = strtr( $filename, '\\', '/' );
501 * Use the same traversal protection as Title::secureAndSplit()
503 if ( strpos( $filename, '.' ) !== false &&
504 ( $filename === '.' ||
$filename === '..' ||
505 strpos( $filename, './' ) === 0 ||
506 strpos( $filename, '../' ) === 0 ||
507 strpos( $filename, '/./' ) !== false ||
508 strpos( $filename, '/../' ) !== false ) )
517 * Path disclosure protection functions
519 function paranoidClean( $param ) { return '[hidden]'; }
520 function passThrough( $param ) { return $param; }
523 * Get a callback function to use for cleaning error message parameters
525 function getErrorCleanupFunction() {
526 switch ( $this->pathDisclosureProtection
) {
528 $callback = array( $this, 'passThrough' );
530 default: // 'paranoid'
531 $callback = array( $this, 'paranoidClean' );
538 * Create a new fatal error
540 function newFatal( $message /*, parameters...*/ ) {
541 $params = func_get_args();
542 array_unshift( $params, $this );
543 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
547 * Create a new good result
549 function newGood( $value = null ) {
550 return FileRepoStatus
::newGood( $this, $value );
554 * Delete files in the deleted directory if they are not referenced in the filearchive table
557 function cleanupDeletedBatch( $storageKeys ) {}
560 * Checks if there is a redirect named as $title. If there is, return the
561 * title object. If not, return false.
564 * @param $title Title of image
567 function checkRedirect( $title ) {
572 * Invalidates image redirect cache related to that image
573 * Doesn't do anything for repositories that don't support image redirects.
576 * @param $title Title of image
578 function invalidateImageRedirect( $title ) {}
581 * Get an array or iterator of file objects for files that have a given
582 * SHA-1 content hash.
586 function findBySha1( $hash ) {
591 * Get the human-readable name of the repo.
594 public function getDisplayName() {
595 // We don't name our own repo, return nothing
596 if ( $this->isLocal() ) {
599 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
600 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
604 * Returns true if this the local file repository.
609 return $this->getName() == 'local';
614 * Get a key on the primary cache for this repository.
615 * Returns false if the repository's cache is not accessible at this site.
616 * The parameters are the parts of the key, as for wfMemcKey().
620 function getSharedCacheKey( /*...*/ ) {
625 * Get a key for this repo in the local cache domain. These cache keys are
626 * not shared with remote instances of the repo.
627 * The parameters are the parts of the key, as for wfMemcKey().
629 function getLocalCacheKey( /*...*/ ) {
630 $args = func_get_args();
631 array_unshift( $args, 'filerepo', $this->getName() );
632 return call_user_func_array( 'wfMemcKey', $args );
636 * Get an UploadStash associated with this repo.
638 * @return UploadStash
640 function getUploadStash() {
641 return new UploadStash( $this );