4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
8 abstract class FileRepo
{
10 const DELETE_SOURCE
= 1;
12 const OVERWRITE_SAME
= 4;
14 var $thumbScriptUrl, $transformVia404;
15 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
16 var $pathDisclosureProtection = 'paranoid';
17 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
20 * Factory functions for creating new files
21 * Override these in the base class
23 var $fileFactory = false, $oldFileFactory = false;
24 var $fileFactoryKey = false, $oldFileFactoryKey = false;
26 function __construct( $info ) {
28 $this->name
= $info['name'];
31 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
32 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
33 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
34 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl' ) as $var )
36 if ( isset( $info[$var] ) ) {
37 $this->$var = $info[$var];
40 $this->transformVia404
= !empty( $info['transformVia404'] );
44 * Determine if a string is an mwrepo:// URL
46 static function isVirtualUrl( $url ) {
47 return substr( $url, 0, 9 ) == 'mwrepo://';
51 * Create a new File object from the local repository
53 * @param $title Mixed: Title object or string
54 * @param $time Mixed: Time at which the image was uploaded.
55 * If this is specified, the returned object will be an
56 * instance of the repository's old file class instead of a
57 * current file. Repositories not supporting version control
58 * should return false if this parameter is set.
60 function newFile( $title, $time = false ) {
61 if ( !($title instanceof Title
) ) {
62 $title = Title
::makeTitleSafe( NS_FILE
, $title );
63 if ( !is_object( $title ) ) {
68 if ( $this->oldFileFactory
) {
69 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
74 return call_user_func( $this->fileFactory
, $title, $this );
79 * Find an instance of the named file created at the specified time
80 * Returns false if the file does not exist. Repositories not supporting
81 * version control should return false if the time is specified.
83 * @param $title Mixed: Title object or string
84 * @param $options Associative array of options:
85 * time: requested time for an archived image, or false for the
86 * current version. An image object will be returned which was
87 * created at the specified time.
89 * ignoreRedirect: If true, do not follow file redirects
91 * private: If true, return restricted (deleted) files if the current
92 * user is allowed to view them. Otherwise, such files will not
95 function findFile( $title, $options = array() ) {
96 if ( !is_array( $options ) ) {
100 $time = isset( $options['time'] ) ?
$options['time'] : false;
102 if ( !($title instanceof Title
) ) {
103 $title = Title
::makeTitleSafe( NS_FILE
, $title );
104 if ( !is_object( $title ) ) {
108 # First try the current version of the file to see if it precedes the timestamp
109 $img = $this->newFile( $title );
113 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
116 # Now try an old version of the file
117 if ( $time !== false ) {
118 $img = $this->newFile( $title, $time );
119 if ( $img && $img->exists() ) {
120 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
122 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
129 if ( !empty( $options['ignoreRedirect'] ) ) {
132 $redir = $this->checkRedirect( $title );
133 if( $redir && $redir->getNamespace() == NS_FILE
) {
134 $img = $this->newFile( $redir );
138 if( $img->exists() ) {
139 $img->redirectedFrom( $title->getDBkey() );
147 * Find many files at once.
148 * @param $items An array of titles, or an array of findFile() options with
149 * the "title" option giving the title. Example:
151 * $findItem = array( 'title' => $title, 'private' => true );
152 * $findBatch = array( $findItem );
153 * $repo->findFiles( $findBatch );
155 function findFiles( $items ) {
157 foreach ( $items as $index => $item ) {
158 if ( is_array( $item ) ) {
159 $title = $item['title'];
161 unset( $options['title'] );
166 $file = $this->findFile( $title, $options );
168 $result[$file->getTitle()->getDBkey()] = $file;
174 * Create a new File object from the local repository
175 * @param $sha1 Mixed: SHA-1 key
176 * @param $time Mixed: time at which the image was uploaded.
177 * If this is specified, the returned object will be an
178 * of the repository's old file class instead of a current
179 * file. Repositories not supporting version control should
180 * return false if this parameter is set.
182 function newFileFromKey( $sha1, $time = false ) {
184 if ( $this->oldFileFactoryKey
) {
185 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
190 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
195 * Find an instance of the file with this key, created at the specified time
196 * Returns false if the file does not exist. Repositories not supporting
197 * version control should return false if the time is specified.
199 * @param $sha1 String
200 * @param $options Option array, same as findFile().
202 function findFileFromKey( $sha1, $options = array() ) {
203 if ( !is_array( $options ) ) {
207 $time = isset( $options['time'] ) ?
$options['time'] : false;
210 # First try the current version of the file to see if it precedes the timestamp
211 $img = $this->newFileFromKey( $sha1 );
215 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
218 # Now try an old version of the file
219 if ( $time !== false ) {
220 $img = $this->newFileFromKey( $sha1, $time );
221 if ( $img->exists() ) {
222 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
224 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
233 * Get the URL of thumb.php
235 function getThumbScriptUrl() {
236 return $this->thumbScriptUrl
;
240 * Get the URL corresponding to one of the four basic zones
241 * @param $zone String: one of: public, deleted, temp, thumb
242 * @return String or false
244 function getZoneUrl( $zone ) {
249 * Returns true if the repository can transform files via a 404 handler
251 function canTransformVia404() {
252 return $this->transformVia404
;
256 * Get the name of an image from its title object
258 function getNameFromTitle( $title ) {
259 global $wgCapitalLinks;
260 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
262 $name = $title->getUserCaseDBKey();
263 if ( $this->initialCapital
) {
264 $name = $wgContLang->ucfirst( $name );
267 $name = $title->getDBkey();
272 static function getHashPathForLevel( $name, $levels ) {
273 if ( $levels == 0 ) {
276 $hash = md5( $name );
278 for ( $i = 1; $i <= $levels; $i++
) {
279 $path .= substr( $hash, 0, $i ) . '/';
286 * Get a relative path including trailing slash, e.g. f/fa/
287 * If the repo is not hashed, returns an empty string
289 function getHashPath( $name ) {
290 return self
::getHashPathForLevel( $name, $this->hashLevels
);
294 * Get the name of this repository, as specified by $info['name]' to the constructor
301 * Get the URL of an image description page. May return false if it is
302 * unknown or not applicable. In general this should only be called by the
303 * File class, since it may return invalid results for certain kinds of
304 * repositories. Use File::getDescriptionUrl() in user code.
306 * In particular, it uses the article paths as specified to the repository
307 * constructor, whereas local repositories use the local Title functions.
309 function getDescriptionUrl( $name ) {
310 $encName = wfUrlencode( $name );
311 if ( !is_null( $this->descBaseUrl
) ) {
312 # "http://example.com/wiki/Image:"
313 return $this->descBaseUrl
. $encName;
315 if ( !is_null( $this->articleUrl
) ) {
316 # "http://example.com/wiki/$1"
318 # We use "Image:" as the canonical namespace for
319 # compatibility across all MediaWiki versions.
320 return str_replace( '$1',
321 "Image:$encName", $this->articleUrl
);
323 if ( !is_null( $this->scriptDirUrl
) ) {
324 # "http://example.com/w"
326 # We use "Image:" as the canonical namespace for
327 # compatibility across all MediaWiki versions,
328 # and just sort of hope index.php is right. ;)
329 return $this->scriptDirUrl
.
330 "/index.php?title=Image:$encName";
336 * Get the URL of the content-only fragment of the description page. For
337 * MediaWiki this means action=render. This should only be called by the
338 * repository's file class, since it may return invalid results. User code
339 * should use File::getDescriptionText().
340 * @param $name String: name of image to fetch
341 * @param $lang String: language to fetch it in, if any.
343 function getDescriptionRenderUrl( $name, $lang = null ) {
344 $query = 'action=render';
345 if ( !is_null( $lang ) ) {
346 $query .= '&uselang=' . $lang;
348 if ( isset( $this->scriptDirUrl
) ) {
349 return $this->scriptDirUrl
. '/index.php?title=' .
350 wfUrlencode( 'Image:' . $name ) .
353 $descUrl = $this->getDescriptionUrl( $name );
355 return wfAppendQuery( $descUrl, $query );
363 * Store a file to a given destination.
365 * @param $srcPath String: source path or virtual URL
366 * @param $dstZone String: destination zone
367 * @param $dstRel String: destination relative path
368 * @param $flags Integer: bitwise combination of the following flags:
369 * self::DELETE_SOURCE Delete the source file after upload
370 * self::OVERWRITE Overwrite an existing destination file instead of failing
371 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
372 * same contents as the source
373 * @return FileRepoStatus
375 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
376 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
377 if ( $status->successCount
== 0 ) {
384 * Store a batch of files
386 * @param $triplets Array: (src,zone,dest) triplets as per store()
387 * @param $flags Integer: flags as per store
389 abstract function storeBatch( $triplets, $flags = 0 );
392 * Pick a random name in the temp zone and store a file to it.
393 * Returns a FileRepoStatus object with the URL in the value.
395 * @param $originalName String: the base name of the file as specified
396 * by the user. The file extension will be maintained.
397 * @param $srcPath String: the current location of the file.
399 abstract function storeTemp( $originalName, $srcPath );
403 * Append the contents of the source path to the given file.
404 * @param $srcPath String: location of the source file
405 * @param $toAppendPath String: path to append to.
406 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
407 * that the source file should be deleted if possible
408 * @return mixed Status or false
410 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
413 * Remove a temporary file or mark it for garbage collection
414 * @param $virtualUrl String: the virtual URL returned by storeTemp
415 * @return Boolean: true on success, false on failure
418 function freeTemp( $virtualUrl ) {
423 * Copy or move a file either from the local filesystem or from an mwrepo://
424 * virtual URL, into this repository at the specified destination location.
426 * Returns a FileRepoStatus object. On success, the value contains "new" or
427 * "archived", to indicate whether the file was new with that name.
429 * @param $srcPath String: the source path or URL
430 * @param $dstRel String: the destination relative path
431 * @param $archiveRel String: rhe relative path where the existing file is to
432 * be archived, if there is one. Relative to the public zone root.
433 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
434 * that the source file should be deleted if possible
436 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
437 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
438 if ( $status->successCount
== 0 ) {
441 if ( isset( $status->value
[0] ) ) {
442 $status->value
= $status->value
[0];
444 $status->value
= false;
450 * Publish a batch of files
451 * @param $triplets Array: (source,dest,archive) triplets as per publish()
452 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
453 * that the source files should be deleted if possible
455 abstract function publishBatch( $triplets, $flags = 0 );
457 function fileExists( $file, $flags = 0 ) {
458 $result = $this->fileExistsBatch( array( $file ), $flags );
463 * Checks existence of an array of files.
465 * @param $files Array: URLs (or paths) of files to check
466 * @param $flags Integer: bitwise combination of the following flags:
467 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
468 * @return Either array of files and existence flags, or false
470 abstract function fileExistsBatch( $files, $flags = 0 );
473 * Move a group of files to the deletion archive.
475 * If no valid deletion archive is configured, this may either delete the
476 * file or throw an exception, depending on the preference of the repository.
478 * The overwrite policy is determined by the repository -- currently FSRepo
479 * assumes a naming scheme in the deleted zone based on content hash, as
480 * opposed to the public zone which is assumed to be unique.
482 * @param $sourceDestPairs Array of source/destination pairs. Each element
483 * is a two-element array containing the source file path relative to the
484 * public root in the first element, and the archive file path relative
485 * to the deleted zone root in the second element.
486 * @return FileRepoStatus
488 abstract function deleteBatch( $sourceDestPairs );
491 * Move a file to the deletion archive.
492 * If no valid deletion archive exists, this may either delete the file
493 * or throw an exception, depending on the preference of the repository
494 * @param $srcRel Mixed: relative path for the file to be deleted
495 * @param $archiveRel Mixed: relative path for the archive location.
496 * Relative to a private archive directory.
497 * @return FileRepoStatus object
499 function delete( $srcRel, $archiveRel ) {
500 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
504 * Get properties of a file with a given virtual URL
505 * The virtual URL must refer to this repo
506 * Properties should ultimately be obtained via File::getPropsFromPath()
508 abstract function getFileProps( $virtualUrl );
511 * Call a callback function for every file in the repository
512 * May use either the database or the filesystem
515 function enumFiles( $callback ) {
516 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
520 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
522 function validateFilename( $filename ) {
523 if ( strval( $filename ) == '' ) {
526 if ( wfIsWindows() ) {
527 $filename = strtr( $filename, '\\', '/' );
530 * Use the same traversal protection as Title::secureAndSplit()
532 if ( strpos( $filename, '.' ) !== false &&
533 ( $filename === '.' ||
$filename === '..' ||
534 strpos( $filename, './' ) === 0 ||
535 strpos( $filename, '../' ) === 0 ||
536 strpos( $filename, '/./' ) !== false ||
537 strpos( $filename, '/../' ) !== false ) )
546 * Path disclosure protection functions
548 function paranoidClean( $param ) { return '[hidden]'; }
549 function passThrough( $param ) { return $param; }
552 * Get a callback function to use for cleaning error message parameters
554 function getErrorCleanupFunction() {
555 switch ( $this->pathDisclosureProtection
) {
557 $callback = array( $this, 'passThrough' );
559 default: // 'paranoid'
560 $callback = array( $this, 'paranoidClean' );
567 * Create a new fatal error
569 function newFatal( $message /*, parameters...*/ ) {
570 $params = func_get_args();
571 array_unshift( $params, $this );
572 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
576 * Create a new good result
578 function newGood( $value = null ) {
579 return FileRepoStatus
::newGood( $this, $value );
583 * Delete files in the deleted directory if they are not referenced in the filearchive table
586 function cleanupDeletedBatch( $storageKeys ) {}
589 * Checks if there is a redirect named as $title. If there is, return the
590 * title object. If not, return false.
593 * @param $title Title of image
595 function checkRedirect( $title ) {
600 * Invalidates image redirect cache related to that image
601 * Doesn't do anything for repositories that don't support image redirects.
604 * @param $title Title of image
606 function invalidateImageRedirect( $title ) {}
609 * Get an array or iterator of file objects for files that have a given
610 * SHA-1 content hash.
614 function findBySha1( $hash ) {
619 * Get the human-readable name of the repo.
622 public function getDisplayName() {
623 // We don't name our own repo, return nothing
624 if ( $this->isLocal() ) {
627 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
628 $repoName = wfMsg( 'shared-repo-name-' . $this->name
);
629 if ( !wfEmptyMsg( 'shared-repo-name-' . $this->name
, $repoName ) ) {
632 return wfMsg( 'shared-repo' );
636 * Returns true if this the local file repository.
641 return $this->getName() == 'local';
646 * Get a key on the primary cache for this repository.
647 * Returns false if the repository's cache is not accessible at this site.
648 * The parameters are the parts of the key, as for wfMemcKey().
652 function getSharedCacheKey( /*...*/ ) {
657 * Get a key for this repo in the local cache domain. These cache keys are
658 * not shared with remote instances of the repo.
659 * The parameters are the parts of the key, as for wfMemcKey().
661 function getLocalCacheKey( /*...*/ ) {
662 $args = func_get_args();
663 array_unshift( $args, 'filerepo', $this->getName() );
664 return call_user_func_array( 'wfMemcKey', $args );