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;
21 var $thumbScriptUrl, $transformVia404;
22 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
23 var $fetchDescription, $initialCapital;
24 var $pathDisclosureProtection = 'paranoid';
25 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
28 * Factory functions for creating new files
29 * Override these in the base class
31 var $fileFactory = false, $oldFileFactory = false;
32 var $fileFactoryKey = false, $oldFileFactoryKey = 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.
69 function newFile( $title, $time = false ) {
70 if ( !($title instanceof Title
) ) {
71 $title = Title
::makeTitleSafe( NS_FILE
, $title );
72 if ( !is_object( $title ) ) {
77 if ( $this->oldFileFactory
) {
78 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
83 return call_user_func( $this->fileFactory
, $title, $this );
88 * Find an instance of the named file created at the specified time
89 * Returns false if the file does not exist. Repositories not supporting
90 * version control should return false if the time is specified.
92 * @param $title Mixed: Title object or string
93 * @param $options Associative array of options:
94 * time: requested time for an archived image, or false for the
95 * current version. An image object will be returned which was
96 * created at the specified time.
98 * ignoreRedirect: If true, do not follow file redirects
100 * private: If true, return restricted (deleted) files if the current
101 * user is allowed to view them. Otherwise, such files will not
104 function findFile( $title, $options = array() ) {
105 if ( !is_array( $options ) ) {
109 $time = isset( $options['time'] ) ?
$options['time'] : false;
111 if ( !($title instanceof Title
) ) {
112 $title = Title
::makeTitleSafe( NS_FILE
, $title );
113 if ( !is_object( $title ) ) {
117 # First try the current version of the file to see if it precedes the timestamp
118 $img = $this->newFile( $title );
122 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
125 # Now try an old version of the file
126 if ( $time !== false ) {
127 $img = $this->newFile( $title, $time );
128 if ( $img && $img->exists() ) {
129 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
131 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
138 if ( !empty( $options['ignoreRedirect'] ) ) {
141 $redir = $this->checkRedirect( $title );
142 if( $redir && $redir->getNamespace() == NS_FILE
) {
143 $img = $this->newFile( $redir );
147 if( $img->exists() ) {
148 $img->redirectedFrom( $title->getDBkey() );
156 * Find many files at once.
157 * @param $items An array of titles, or an array of findFile() options with
158 * the "title" option giving the title. Example:
160 * $findItem = array( 'title' => $title, 'private' => true );
161 * $findBatch = array( $findItem );
162 * $repo->findFiles( $findBatch );
164 function findFiles( $items ) {
166 foreach ( $items as $item ) {
167 if ( is_array( $item ) ) {
168 $title = $item['title'];
170 unset( $options['title'] );
175 $file = $this->findFile( $title, $options );
177 $result[$file->getTitle()->getDBkey()] = $file;
184 * Create a new File object from the local repository
185 * @param $sha1 Mixed: SHA-1 key
186 * @param $time Mixed: time at which the image was uploaded.
187 * If this is specified, the returned object will be an
188 * of the repository's old file class instead of a current
189 * file. Repositories not supporting version control should
190 * return false if this parameter is set.
192 function newFileFromKey( $sha1, $time = false ) {
194 if ( $this->oldFileFactoryKey
) {
195 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
200 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
205 * Find an instance of the file with this key, created at the specified time
206 * Returns false if the file does not exist. Repositories not supporting
207 * version control should return false if the time is specified.
209 * @param $sha1 String
210 * @param $options Option array, same as findFile().
212 function findFileFromKey( $sha1, $options = array() ) {
213 if ( !is_array( $options ) ) {
217 $time = isset( $options['time'] ) ?
$options['time'] : false;
220 # First try the current version of the file to see if it precedes the timestamp
221 $img = $this->newFileFromKey( $sha1 );
225 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
228 # Now try an old version of the file
229 if ( $time !== false ) {
230 $img = $this->newFileFromKey( $sha1, $time );
231 if ( $img->exists() ) {
232 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
234 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
243 * Get the URL of thumb.php
245 function getThumbScriptUrl() {
246 return $this->thumbScriptUrl
;
250 * Get the URL corresponding to one of the four basic zones
251 * @param $zone String: one of: public, deleted, temp, thumb
252 * @return String or false
254 function getZoneUrl( $zone ) {
259 * Returns true if the repository can transform files via a 404 handler
261 function canTransformVia404() {
262 return $this->transformVia404
;
266 * Get the name of an image from its title object
268 function getNameFromTitle( $title ) {
269 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
271 $name = $title->getUserCaseDBKey();
272 if ( $this->initialCapital
) {
273 $name = $wgContLang->ucfirst( $name );
276 $name = $title->getDBkey();
281 static function getHashPathForLevel( $name, $levels ) {
282 if ( $levels == 0 ) {
285 $hash = md5( $name );
287 for ( $i = 1; $i <= $levels; $i++
) {
288 $path .= substr( $hash, 0, $i ) . '/';
295 * Get a relative path including trailing slash, e.g. f/fa/
296 * If the repo is not hashed, returns an empty string
298 function getHashPath( $name ) {
299 return self
::getHashPathForLevel( $name, $this->hashLevels
);
303 * Get the name of this repository, as specified by $info['name]' to the constructor
310 * Make an url to this repo
312 * @param $query mixed Query string to append
313 * @param $entry string Entry point; defaults to index
316 function makeUrl( $query = '', $entry = 'index' ) {
317 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
318 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
322 * Get the URL of an image description page. May return false if it is
323 * unknown or not applicable. In general this should only be called by the
324 * File class, since it may return invalid results for certain kinds of
325 * repositories. Use File::getDescriptionUrl() in user code.
327 * In particular, it uses the article paths as specified to the repository
328 * constructor, whereas local repositories use the local Title functions.
330 function getDescriptionUrl( $name ) {
331 $encName = wfUrlencode( $name );
332 if ( !is_null( $this->descBaseUrl
) ) {
333 # "http://example.com/wiki/Image:"
334 return $this->descBaseUrl
. $encName;
336 if ( !is_null( $this->articleUrl
) ) {
337 # "http://example.com/wiki/$1"
339 # We use "Image:" as the canonical namespace for
340 # compatibility across all MediaWiki versions.
341 return str_replace( '$1',
342 "Image:$encName", $this->articleUrl
);
344 if ( !is_null( $this->scriptDirUrl
) ) {
345 # "http://example.com/w"
347 # We use "Image:" as the canonical namespace for
348 # compatibility across all MediaWiki versions,
349 # and just sort of hope index.php is right. ;)
350 return $this->makeUrl( "title=Image:$encName" );
356 * Get the URL of the content-only fragment of the description page. For
357 * MediaWiki this means action=render. This should only be called by the
358 * repository's file class, since it may return invalid results. User code
359 * should use File::getDescriptionText().
360 * @param $name String: name of image to fetch
361 * @param $lang String: language to fetch it in, if any.
363 function getDescriptionRenderUrl( $name, $lang = null ) {
364 $query = 'action=render';
365 if ( !is_null( $lang ) ) {
366 $query .= '&uselang=' . $lang;
368 if ( isset( $this->scriptDirUrl
) ) {
369 return $this->makeUrl(
371 wfUrlencode( 'Image:' . $name ) .
374 $descUrl = $this->getDescriptionUrl( $name );
376 return wfAppendQuery( $descUrl, $query );
384 * Get the URL of the stylesheet to apply to description pages
387 function getDescriptionStylesheetUrl() {
388 if ( $this->scriptDirUrl
) {
389 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
390 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
395 * Store a file to a given destination.
397 * @param $srcPath String: source path or virtual URL
398 * @param $dstZone String: destination zone
399 * @param $dstRel String: destination relative path
400 * @param $flags Integer: bitwise combination of the following flags:
401 * self::DELETE_SOURCE Delete the source file after upload
402 * self::OVERWRITE Overwrite an existing destination file instead of failing
403 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
404 * same contents as the source
405 * @return FileRepoStatus
407 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
408 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
409 if ( $status->successCount
== 0 ) {
416 * Store a batch of files
418 * @param $triplets Array: (src,zone,dest) triplets as per store()
419 * @param $flags Integer: flags as per store
421 abstract function storeBatch( $triplets, $flags = 0 );
424 * Pick a random name in the temp zone and store a file to it.
425 * Returns a FileRepoStatus object with the URL in the value.
427 * @param $originalName String: the base name of the file as specified
428 * by the user. The file extension will be maintained.
429 * @param $srcPath String: the current location of the file.
431 abstract function storeTemp( $originalName, $srcPath );
435 * Append the contents of the source path to the given file.
436 * @param $srcPath String: location of the source file
437 * @param $toAppendPath String: path to append to.
438 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
439 * that the source file should be deleted if possible
440 * @return mixed Status or false
442 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
445 * Remove a temporary file or mark it for garbage collection
446 * @param $virtualUrl String: the virtual URL returned by storeTemp
447 * @return Boolean: true on success, false on failure
450 function freeTemp( $virtualUrl ) {
455 * Copy or move a file either from the local filesystem or from an mwrepo://
456 * virtual URL, into this repository at the specified destination location.
458 * Returns a FileRepoStatus object. On success, the value contains "new" or
459 * "archived", to indicate whether the file was new with that name.
461 * @param $srcPath String: the source path or URL
462 * @param $dstRel String: the destination relative path
463 * @param $archiveRel String: rhe relative path where the existing file is to
464 * be archived, if there is one. Relative to the public zone root.
465 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
466 * that the source file should be deleted if possible
468 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
469 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
470 if ( $status->successCount
== 0 ) {
473 if ( isset( $status->value
[0] ) ) {
474 $status->value
= $status->value
[0];
476 $status->value
= false;
482 * Publish a batch of files
483 * @param $triplets Array: (source,dest,archive) triplets as per publish()
484 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
485 * that the source files should be deleted if possible
487 abstract function publishBatch( $triplets, $flags = 0 );
489 function fileExists( $file, $flags = 0 ) {
490 $result = $this->fileExistsBatch( array( $file ), $flags );
495 * Checks existence of an array of files.
497 * @param $files Array: URLs (or paths) of files to check
498 * @param $flags Integer: bitwise combination of the following flags:
499 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
500 * @return Either array of files and existence flags, or false
502 abstract function fileExistsBatch( $files, $flags = 0 );
505 * Move a group of files to the deletion archive.
507 * If no valid deletion archive is configured, this may either delete the
508 * file or throw an exception, depending on the preference of the repository.
510 * The overwrite policy is determined by the repository -- currently FSRepo
511 * assumes a naming scheme in the deleted zone based on content hash, as
512 * opposed to the public zone which is assumed to be unique.
514 * @param $sourceDestPairs Array of source/destination pairs. Each element
515 * is a two-element array containing the source file path relative to the
516 * public root in the first element, and the archive file path relative
517 * to the deleted zone root in the second element.
518 * @return FileRepoStatus
520 abstract function deleteBatch( $sourceDestPairs );
523 * Move a file to the deletion archive.
524 * If no valid deletion archive exists, this may either delete the file
525 * or throw an exception, depending on the preference of the repository
526 * @param $srcRel Mixed: relative path for the file to be deleted
527 * @param $archiveRel Mixed: relative path for the archive location.
528 * Relative to a private archive directory.
529 * @return FileRepoStatus object
531 function delete( $srcRel, $archiveRel ) {
532 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
536 * Get properties of a file with a given virtual URL
537 * The virtual URL must refer to this repo
538 * Properties should ultimately be obtained via File::getPropsFromPath()
540 abstract function getFileProps( $virtualUrl );
543 * Call a callback function for every file in the repository
544 * May use either the database or the filesystem
547 function enumFiles( $callback ) {
548 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
552 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
554 function validateFilename( $filename ) {
555 if ( strval( $filename ) == '' ) {
558 if ( wfIsWindows() ) {
559 $filename = strtr( $filename, '\\', '/' );
562 * Use the same traversal protection as Title::secureAndSplit()
564 if ( strpos( $filename, '.' ) !== false &&
565 ( $filename === '.' ||
$filename === '..' ||
566 strpos( $filename, './' ) === 0 ||
567 strpos( $filename, '../' ) === 0 ||
568 strpos( $filename, '/./' ) !== false ||
569 strpos( $filename, '/../' ) !== false ) )
578 * Path disclosure protection functions
580 function paranoidClean( $param ) { return '[hidden]'; }
581 function passThrough( $param ) { return $param; }
584 * Get a callback function to use for cleaning error message parameters
586 function getErrorCleanupFunction() {
587 switch ( $this->pathDisclosureProtection
) {
589 $callback = array( $this, 'passThrough' );
591 default: // 'paranoid'
592 $callback = array( $this, 'paranoidClean' );
599 * Create a new fatal error
601 function newFatal( $message /*, parameters...*/ ) {
602 $params = func_get_args();
603 array_unshift( $params, $this );
604 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
608 * Create a new good result
610 function newGood( $value = null ) {
611 return FileRepoStatus
::newGood( $this, $value );
615 * Delete files in the deleted directory if they are not referenced in the filearchive table
618 function cleanupDeletedBatch( $storageKeys ) {}
621 * Checks if there is a redirect named as $title. If there is, return the
622 * title object. If not, return false.
625 * @param $title Title of image
627 function checkRedirect( $title ) {
632 * Invalidates image redirect cache related to that image
633 * Doesn't do anything for repositories that don't support image redirects.
636 * @param $title Title of image
638 function invalidateImageRedirect( $title ) {}
641 * Get an array or iterator of file objects for files that have a given
642 * SHA-1 content hash.
646 function findBySha1( $hash ) {
651 * Get the human-readable name of the repo.
654 public function getDisplayName() {
655 // We don't name our own repo, return nothing
656 if ( $this->isLocal() ) {
659 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
660 $repoName = wfMsg( 'shared-repo-name-' . $this->name
);
661 if ( !wfEmptyMsg( 'shared-repo-name-' . $this->name
, $repoName ) ) {
664 return wfMsg( 'shared-repo' );
668 * Returns true if this the local file repository.
673 return $this->getName() == 'local';
678 * Get a key on the primary cache for this repository.
679 * Returns false if the repository's cache is not accessible at this site.
680 * The parameters are the parts of the key, as for wfMemcKey().
684 function getSharedCacheKey( /*...*/ ) {
689 * Get a key for this repo in the local cache domain. These cache keys are
690 * not shared with remote instances of the repo.
691 * The parameters are the parts of the key, as for wfMemcKey().
693 function getLocalCacheKey( /*...*/ ) {
694 $args = func_get_args();
695 array_unshift( $args, 'filerepo', $this->getName() );
696 return call_user_func_array( 'wfMemcKey', $args );