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
52 * @param mixed $title Title object or string
53 * @param mixed $time Time at which the image was uploaded.
54 * If this is specified, the returned object will be an
55 * instance of the repository's old file class instead of
56 * a current file. Repositories not supporting version
57 * control should return false if this parameter is set.
59 function newFile( $title, $time = false ) {
60 if ( !($title instanceof Title
) ) {
61 $title = Title
::makeTitleSafe( NS_FILE
, $title );
62 if ( !is_object( $title ) ) {
67 if ( $this->oldFileFactory
) {
68 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
73 return call_user_func( $this->fileFactory
, $title, $this );
78 * Find an instance of the named file created at the specified time
79 * Returns false if the file does not exist. Repositories not supporting
80 * version control should return false if the time is specified.
82 * @param mixed $title Title object or string
83 * @param $options Associative array of options:
84 * time: requested time for an archived image, or false for the
85 * current version. An image object will be returned which was
86 * created at the specified time.
88 * ignoreRedirect: If true, do not follow file redirects
90 * private: If true, return restricted (deleted) files if the current
91 * user is allowed to view them. Otherwise, such files will not
94 function findFile( $title, $options = array() ) {
95 if ( !is_array( $options ) ) {
99 $time = isset( $options['time'] ) ?
$options['time'] : false;
101 if ( !($title instanceof Title
) ) {
102 $title = Title
::makeTitleSafe( NS_FILE
, $title );
103 if ( !is_object( $title ) ) {
107 # First try the current version of the file to see if it precedes the timestamp
108 $img = $this->newFile( $title );
112 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
115 # Now try an old version of the file
116 if ( $time !== false ) {
117 $img = $this->newFile( $title, $time );
118 if ( $img && $img->exists() ) {
119 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
121 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
128 if ( !empty( $options['ignoreRedirect'] ) ) {
131 $redir = $this->checkRedirect( $title );
132 if( $redir && $redir->getNamespace() == NS_FILE
) {
133 $img = $this->newFile( $redir );
137 if( $img->exists() ) {
138 $img->redirectedFrom( $title->getDBkey() );
146 * Find many files at once.
147 * @param array $items, an array of titles, or an array of findFile() options with
148 * the "title" option giving the title. Example:
150 * $findItem = array( 'title' => $title, 'private' => true );
151 * $findBatch = array( $findItem );
152 * $repo->findFiles( $findBatch );
154 function findFiles( $items ) {
156 foreach ( $items as $index => $item ) {
157 if ( is_array( $item ) ) {
158 $title = $item['title'];
160 unset( $options['title'] );
165 $file = $this->findFile( $title, $options );
167 $result[$file->getTitle()->getDBkey()] = $file;
173 * Create a new File object from the local repository
174 * @param mixed $sha1 SHA-1 key
175 * @param mixed $time Time at which the image was uploaded.
176 * If this is specified, the returned object will be an
177 * instance of the repository's old file class instead of
178 * a current file. Repositories not supporting version
179 * control should return false if this parameter is set.
181 function newFileFromKey( $sha1, $time = false ) {
183 if ( $this->oldFileFactoryKey
) {
184 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
189 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
194 * Find an instance of the file with this key, created at the specified time
195 * Returns false if the file does not exist. Repositories not supporting
196 * version control should return false if the time is specified.
198 * @param string $sha1 string
199 * @param array $options Option array, same as findFile().
201 function findFileFromKey( $sha1, $options = array() ) {
202 if ( !is_array( $options ) ) {
206 $time = isset( $options['time'] ) ?
$options['time'] : false;
209 # First try the current version of the file to see if it precedes the timestamp
210 $img = $this->newFileFromKey( $sha1 );
214 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
217 # Now try an old version of the file
218 if ( $time !== false ) {
219 $img = $this->newFileFromKey( $sha1, $time );
220 if ( $img->exists() ) {
221 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
223 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
232 * Get the URL of thumb.php
234 function getThumbScriptUrl() {
235 return $this->thumbScriptUrl
;
239 * Get the URL corresponding to one of the four basic zones
240 * @param String $zone One of: public, deleted, temp, thumb
241 * @return String or false
243 function getZoneUrl( $zone ) {
248 * Returns true if the repository can transform files via a 404 handler
250 function canTransformVia404() {
251 return $this->transformVia404
;
255 * Get the name of an image from its title object
257 function getNameFromTitle( $title ) {
258 global $wgCapitalLinks;
259 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
261 $name = $title->getUserCaseDBKey();
262 if ( $this->initialCapital
) {
263 $name = $wgContLang->ucfirst( $name );
266 $name = $title->getDBkey();
271 static function getHashPathForLevel( $name, $levels ) {
272 if ( $levels == 0 ) {
275 $hash = md5( $name );
277 for ( $i = 1; $i <= $levels; $i++
) {
278 $path .= substr( $hash, 0, $i ) . '/';
285 * Get a relative path including trailing slash, e.g. f/fa/
286 * If the repo is not hashed, returns an empty string
288 function getHashPath( $name ) {
289 return self
::getHashPathForLevel( $name, $this->hashLevels
);
293 * Get the name of this repository, as specified by $info['name]' to the constructor
300 * Get the URL of an image description page. May return false if it is
301 * unknown or not applicable. In general this should only be called by the
302 * File class, since it may return invalid results for certain kinds of
303 * repositories. Use File::getDescriptionUrl() in user code.
305 * In particular, it uses the article paths as specified to the repository
306 * constructor, whereas local repositories use the local Title functions.
308 function getDescriptionUrl( $name ) {
309 $encName = wfUrlencode( $name );
310 if ( !is_null( $this->descBaseUrl
) ) {
311 # "http://example.com/wiki/Image:"
312 return $this->descBaseUrl
. $encName;
314 if ( !is_null( $this->articleUrl
) ) {
315 # "http://example.com/wiki/$1"
317 # We use "Image:" as the canonical namespace for
318 # compatibility across all MediaWiki versions.
319 return str_replace( '$1',
320 "Image:$encName", $this->articleUrl
);
322 if ( !is_null( $this->scriptDirUrl
) ) {
323 # "http://example.com/w"
325 # We use "Image:" as the canonical namespace for
326 # compatibility across all MediaWiki versions,
327 # and just sort of hope index.php is right. ;)
328 return $this->scriptDirUrl
.
329 "/index.php?title=Image:$encName";
335 * Get the URL of the content-only fragment of the description page. For
336 * MediaWiki this means action=render. This should only be called by the
337 * repository's file class, since it may return invalid results. User code
338 * should use File::getDescriptionText().
339 * @param string $name Name of image to fetch
340 * @param string $lang Language to fetch it in, if any.
342 function getDescriptionRenderUrl( $name, $lang = null ) {
343 $query = 'action=render';
344 if ( !is_null( $lang ) ) {
345 $query .= '&uselang=' . $lang;
347 if ( isset( $this->scriptDirUrl
) ) {
348 return $this->scriptDirUrl
. '/index.php?title=' .
349 wfUrlencode( 'Image:' . $name ) .
352 $descUrl = $this->getDescriptionUrl( $name );
354 return wfAppendQuery( $descUrl, $query );
362 * Store a file to a given destination.
364 * @param string $srcPath Source path or virtual URL
365 * @param string $dstZone Destination zone
366 * @param string $dstRel Destination relative path
367 * @param integer $flags Bitwise combination of the following flags:
368 * self::DELETE_SOURCE Delete the source file after upload
369 * self::OVERWRITE Overwrite an existing destination file instead of failing
370 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
371 * same contents as the source
372 * @return FileRepoStatus
374 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
375 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
376 if ( $status->successCount
== 0 ) {
383 * Store a batch of files
385 * @param array $triplets (src,zone,dest) triplets as per store()
386 * @param integer $flags Flags as per store
388 abstract function storeBatch( $triplets, $flags = 0 );
391 * Pick a random name in the temp zone and store a file to it.
392 * Returns a FileRepoStatus object with the URL in the value.
394 * @param string $originalName The base name of the file as specified
395 * by the user. The file extension will be maintained.
396 * @param string $srcPath The current location of the file.
398 abstract function storeTemp( $originalName, $srcPath );
402 * Append the contents of the source path to the given file.
403 * @param $srcPath string location of the source file
404 * @param $toAppendPath string path to append to.
405 * @param $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
406 * that the source file should be deleted if possible
407 * @return mixed Status or false
409 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
412 * Remove a temporary file or mark it for garbage collection
413 * @param string $virtualUrl The virtual URL returned by storeTemp
414 * @return boolean True on success, false on failure
417 function freeTemp( $virtualUrl ) {
422 * Copy or move a file either from the local filesystem or from an mwrepo://
423 * virtual URL, into this repository at the specified destination location.
425 * Returns a FileRepoStatus object. On success, the value contains "new" or
426 * "archived", to indicate whether the file was new with that name.
428 * @param string $srcPath The source path or URL
429 * @param string $dstRel The destination relative path
430 * @param string $archiveRel The relative path where the existing file is to
431 * be archived, if there is one. Relative to the public zone root.
432 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
433 * that the source file should be deleted if possible
435 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
436 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
437 if ( $status->successCount
== 0 ) {
440 if ( isset( $status->value
[0] ) ) {
441 $status->value
= $status->value
[0];
443 $status->value
= false;
449 * Publish a batch of files
450 * @param array $triplets (source,dest,archive) triplets as per publish()
451 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
452 * that the source files should be deleted if possible
454 abstract function publishBatch( $triplets, $flags = 0 );
456 function fileExists( $file, $flags = 0 ) {
457 $result = $this->fileExistsBatch( array( $file ), $flags );
462 * Checks existence of an array of files.
464 * @param array $files URLs (or paths) of files to check
465 * @param integer $flags Bitwise combination of the following flags:
466 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
467 * @return Either array of files and existence flags, or false
469 abstract function fileExistsBatch( $files, $flags = 0 );
472 * Move a group of files to the deletion archive.
474 * If no valid deletion archive is configured, this may either delete the
475 * file or throw an exception, depending on the preference of the repository.
477 * The overwrite policy is determined by the repository -- currently FSRepo
478 * assumes a naming scheme in the deleted zone based on content hash, as
479 * opposed to the public zone which is assumed to be unique.
481 * @param array $sourceDestPairs Array of source/destination pairs. Each element
482 * is a two-element array containing the source file path relative to the
483 * public root in the first element, and the archive file path relative
484 * to the deleted zone root in the second element.
485 * @return FileRepoStatus
487 abstract function deleteBatch( $sourceDestPairs );
490 * Move a file to the deletion archive.
491 * If no valid deletion archive exists, this may either delete the file
492 * or throw an exception, depending on the preference of the repository
493 * @param mixed $srcRel Relative path for the file to be deleted
494 * @param mixed $archiveRel Relative path for the archive location.
495 * Relative to a private archive directory.
496 * @return WikiError object (wikitext-formatted), or true for success
498 function delete( $srcRel, $archiveRel ) {
499 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
503 * Get properties of a file with a given virtual URL
504 * The virtual URL must refer to this repo
505 * Properties should ultimately be obtained via File::getPropsFromPath()
507 abstract function getFileProps( $virtualUrl );
510 * Call a callback function for every file in the repository
511 * May use either the database or the filesystem
514 function enumFiles( $callback ) {
515 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
519 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
521 function validateFilename( $filename ) {
522 if ( strval( $filename ) == '' ) {
525 if ( wfIsWindows() ) {
526 $filename = strtr( $filename, '\\', '/' );
529 * Use the same traversal protection as Title::secureAndSplit()
531 if ( strpos( $filename, '.' ) !== false &&
532 ( $filename === '.' ||
$filename === '..' ||
533 strpos( $filename, './' ) === 0 ||
534 strpos( $filename, '../' ) === 0 ||
535 strpos( $filename, '/./' ) !== false ||
536 strpos( $filename, '/../' ) !== false ) )
545 * Path disclosure protection functions
547 function paranoidClean( $param ) { return '[hidden]'; }
548 function passThrough( $param ) { return $param; }
551 * Get a callback function to use for cleaning error message parameters
553 function getErrorCleanupFunction() {
554 switch ( $this->pathDisclosureProtection
) {
556 $callback = array( $this, 'passThrough' );
558 default: // 'paranoid'
559 $callback = array( $this, 'paranoidClean' );
566 * Create a new fatal error
568 function newFatal( $message /*, parameters...*/ ) {
569 $params = func_get_args();
570 array_unshift( $params, $this );
571 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
575 * Create a new good result
577 function newGood( $value = null ) {
578 return FileRepoStatus
::newGood( $this, $value );
582 * Delete files in the deleted directory if they are not referenced in the filearchive table
585 function cleanupDeletedBatch( $storageKeys ) {}
588 * Checks if there is a redirect named as $title. If there is, return the
589 * title object. If not, return false.
592 * @param Title $title Title of image
594 function checkRedirect( $title ) {
599 * Invalidates image redirect cache related to that image
600 * Doesn't do anything for repositories that don't support image redirects.
603 * @param Title $title Title of image
605 function invalidateImageRedirect( $title ) {}
608 * Get an array or iterator of file objects for files that have a given
609 * SHA-1 content hash.
613 function findBySha1( $hash ) {
618 * Get the human-readable name of the repo.
621 public function getDisplayName() {
622 // We don't name our own repo, return nothing
623 if ( $this->name
== 'local' ) {
626 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
627 $repoName = wfMsg( 'shared-repo-name-' . $this->name
);
628 if ( !wfEmptyMsg( 'shared-repo-name-' . $this->name
, $repoName ) ) {
631 return wfMsg( 'shared-repo' );
635 * Get a key on the primary cache for this repository.
636 * Returns false if the repository's cache is not accessible at this site.
637 * The parameters are the parts of the key, as for wfMemcKey().
641 function getSharedCacheKey( /*...*/ ) {
646 * Get a key for this repo in the local cache domain. These cache keys are
647 * not shared with remote instances of the repo.
648 * The parameters are the parts of the key, as for wfMemcKey().
650 function getLocalCacheKey( /*...*/ ) {
651 $args = func_get_args();
652 array_unshift( $args, 'filerepo', $this->getName() );
653 return call_user_func_array( 'wfMemcKey', $args );