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, $scriptExtension, $articleUrl;
16 var $fetchDescription, $initialCapital;
17 var $pathDisclosureProtection = 'paranoid';
18 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
21 * Factory functions for creating new files
22 * Override these in the base class
24 var $fileFactory = false, $oldFileFactory = false;
25 var $fileFactoryKey = false, $oldFileFactoryKey = false;
27 function __construct( $info ) {
29 $this->name
= $info['name'];
32 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
33 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
34 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
35 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
38 if ( isset( $info[$var] ) ) {
39 $this->$var = $info[$var];
42 $this->transformVia404
= !empty( $info['transformVia404'] );
46 * Determine if a string is an mwrepo:// URL
48 static function isVirtualUrl( $url ) {
49 return substr( $url, 0, 9 ) == 'mwrepo://';
53 * Create a new File object from the local repository
55 * @param $title Mixed: Title object or string
56 * @param $time Mixed: Time at which the image was uploaded.
57 * If this is specified, the returned object will be an
58 * instance of the repository's old file class instead of a
59 * current file. Repositories not supporting version control
60 * should return false if this parameter is set.
62 function newFile( $title, $time = false ) {
63 if ( !($title instanceof Title
) ) {
64 $title = Title
::makeTitleSafe( NS_FILE
, $title );
65 if ( !is_object( $title ) ) {
70 if ( $this->oldFileFactory
) {
71 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
76 return call_user_func( $this->fileFactory
, $title, $this );
81 * Find an instance of the named file created at the specified time
82 * Returns false if the file does not exist. Repositories not supporting
83 * version control should return false if the time is specified.
85 * @param $title Mixed: Title object or string
86 * @param $options Associative array of options:
87 * time: requested time for an archived image, or false for the
88 * current version. An image object will be returned which was
89 * created at the specified time.
91 * ignoreRedirect: If true, do not follow file redirects
93 * private: If true, return restricted (deleted) files if the current
94 * user is allowed to view them. Otherwise, such files will not
97 function findFile( $title, $options = array() ) {
98 if ( !is_array( $options ) ) {
102 $time = isset( $options['time'] ) ?
$options['time'] : false;
104 if ( !($title instanceof Title
) ) {
105 $title = Title
::makeTitleSafe( NS_FILE
, $title );
106 if ( !is_object( $title ) ) {
110 # First try the current version of the file to see if it precedes the timestamp
111 $img = $this->newFile( $title );
115 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
118 # Now try an old version of the file
119 if ( $time !== false ) {
120 $img = $this->newFile( $title, $time );
121 if ( $img && $img->exists() ) {
122 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
124 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
131 if ( !empty( $options['ignoreRedirect'] ) ) {
134 $redir = $this->checkRedirect( $title );
135 if( $redir && $redir->getNamespace() == NS_FILE
) {
136 $img = $this->newFile( $redir );
140 if( $img->exists() ) {
141 $img->redirectedFrom( $title->getDBkey() );
149 * Find many files at once.
150 * @param $items An array of titles, or an array of findFile() options with
151 * the "title" option giving the title. Example:
153 * $findItem = array( 'title' => $title, 'private' => true );
154 * $findBatch = array( $findItem );
155 * $repo->findFiles( $findBatch );
157 function findFiles( $items ) {
159 foreach ( $items as $index => $item ) {
160 if ( is_array( $item ) ) {
161 $title = $item['title'];
163 unset( $options['title'] );
168 $file = $this->findFile( $title, $options );
170 $result[$file->getTitle()->getDBkey()] = $file;
176 * Create a new File object from the local repository
177 * @param $sha1 Mixed: SHA-1 key
178 * @param $time Mixed: time at which the image was uploaded.
179 * If this is specified, the returned object will be an
180 * of the repository's old file class instead of a current
181 * file. Repositories not supporting version control should
182 * return false if this parameter is set.
184 function newFileFromKey( $sha1, $time = false ) {
186 if ( $this->oldFileFactoryKey
) {
187 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
192 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
197 * Find an instance of the file with this key, created at the specified time
198 * Returns false if the file does not exist. Repositories not supporting
199 * version control should return false if the time is specified.
201 * @param $sha1 String
202 * @param $options Option array, same as findFile().
204 function findFileFromKey( $sha1, $options = array() ) {
205 if ( !is_array( $options ) ) {
209 $time = isset( $options['time'] ) ?
$options['time'] : false;
212 # First try the current version of the file to see if it precedes the timestamp
213 $img = $this->newFileFromKey( $sha1 );
217 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
220 # Now try an old version of the file
221 if ( $time !== false ) {
222 $img = $this->newFileFromKey( $sha1, $time );
223 if ( $img->exists() ) {
224 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
226 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
235 * Get the URL of thumb.php
237 function getThumbScriptUrl() {
238 return $this->thumbScriptUrl
;
242 * Get the URL corresponding to one of the four basic zones
243 * @param $zone String: one of: public, deleted, temp, thumb
244 * @return String or false
246 function getZoneUrl( $zone ) {
251 * Returns true if the repository can transform files via a 404 handler
253 function canTransformVia404() {
254 return $this->transformVia404
;
258 * Get the name of an image from its title object
260 function getNameFromTitle( $title ) {
261 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
263 $name = $title->getUserCaseDBKey();
264 if ( $this->initialCapital
) {
265 $name = $wgContLang->ucfirst( $name );
268 $name = $title->getDBkey();
273 static function getHashPathForLevel( $name, $levels ) {
274 if ( $levels == 0 ) {
277 $hash = md5( $name );
279 for ( $i = 1; $i <= $levels; $i++
) {
280 $path .= substr( $hash, 0, $i ) . '/';
287 * Get a relative path including trailing slash, e.g. f/fa/
288 * If the repo is not hashed, returns an empty string
290 function getHashPath( $name ) {
291 return self
::getHashPathForLevel( $name, $this->hashLevels
);
295 * Get the name of this repository, as specified by $info['name]' to the constructor
302 * Make an url to this repo
304 * @param $query mixed Query string to append
305 * @param $entry string Entry point; defaults to index
308 function makeUrl( $query = '', $entry = 'index' ) {
309 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
310 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}?", $query );
314 * Get the URL of an image description page. May return false if it is
315 * unknown or not applicable. In general this should only be called by the
316 * File class, since it may return invalid results for certain kinds of
317 * repositories. Use File::getDescriptionUrl() in user code.
319 * In particular, it uses the article paths as specified to the repository
320 * constructor, whereas local repositories use the local Title functions.
322 function getDescriptionUrl( $name ) {
323 $encName = wfUrlencode( $name );
324 if ( !is_null( $this->descBaseUrl
) ) {
325 # "http://example.com/wiki/Image:"
326 return $this->descBaseUrl
. $encName;
328 if ( !is_null( $this->articleUrl
) ) {
329 # "http://example.com/wiki/$1"
331 # We use "Image:" as the canonical namespace for
332 # compatibility across all MediaWiki versions.
333 return str_replace( '$1',
334 "Image:$encName", $this->articleUrl
);
336 if ( !is_null( $this->scriptDirUrl
) ) {
337 # "http://example.com/w"
339 # We use "Image:" as the canonical namespace for
340 # compatibility across all MediaWiki versions,
341 # and just sort of hope index.php is right. ;)
342 return $this->makeUrl( "title=Image:$encName" );
348 * Get the URL of the content-only fragment of the description page. For
349 * MediaWiki this means action=render. This should only be called by the
350 * repository's file class, since it may return invalid results. User code
351 * should use File::getDescriptionText().
352 * @param $name String: name of image to fetch
353 * @param $lang String: language to fetch it in, if any.
355 function getDescriptionRenderUrl( $name, $lang = null ) {
356 $query = 'action=render';
357 if ( !is_null( $lang ) ) {
358 $query .= '&uselang=' . $lang;
360 if ( isset( $this->scriptDirUrl
) ) {
361 return $this->makeUrl(
363 wfUrlencode( 'Image:' . $name ) .
366 $descUrl = $this->getDescriptionUrl( $name );
368 return wfAppendQuery( $descUrl, $query );
376 * Get the URL of the stylesheet to apply to description pages
379 function getDescriptionStylesheetUrl() {
380 if ( $this->scriptDirUrl
) {
381 return self
::makeUrl( 'title=MediaWiki:Filepage.css&' .
382 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
387 * Store a file to a given destination.
389 * @param $srcPath String: source path or virtual URL
390 * @param $dstZone String: destination zone
391 * @param $dstRel String: destination relative path
392 * @param $flags Integer: bitwise combination of the following flags:
393 * self::DELETE_SOURCE Delete the source file after upload
394 * self::OVERWRITE Overwrite an existing destination file instead of failing
395 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
396 * same contents as the source
397 * @return FileRepoStatus
399 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
400 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
401 if ( $status->successCount
== 0 ) {
408 * Store a batch of files
410 * @param $triplets Array: (src,zone,dest) triplets as per store()
411 * @param $flags Integer: flags as per store
413 abstract function storeBatch( $triplets, $flags = 0 );
416 * Pick a random name in the temp zone and store a file to it.
417 * Returns a FileRepoStatus object with the URL in the value.
419 * @param $originalName String: the base name of the file as specified
420 * by the user. The file extension will be maintained.
421 * @param $srcPath String: the current location of the file.
423 abstract function storeTemp( $originalName, $srcPath );
427 * Append the contents of the source path to the given file.
428 * @param $srcPath String: location of the source file
429 * @param $toAppendPath String: path to append to.
430 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
431 * that the source file should be deleted if possible
432 * @return mixed Status or false
434 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
437 * Remove a temporary file or mark it for garbage collection
438 * @param $virtualUrl String: the virtual URL returned by storeTemp
439 * @return Boolean: true on success, false on failure
442 function freeTemp( $virtualUrl ) {
447 * Copy or move a file either from the local filesystem or from an mwrepo://
448 * virtual URL, into this repository at the specified destination location.
450 * Returns a FileRepoStatus object. On success, the value contains "new" or
451 * "archived", to indicate whether the file was new with that name.
453 * @param $srcPath String: the source path or URL
454 * @param $dstRel String: the destination relative path
455 * @param $archiveRel String: rhe relative path where the existing file is to
456 * be archived, if there is one. Relative to the public zone root.
457 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
458 * that the source file should be deleted if possible
460 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
461 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
462 if ( $status->successCount
== 0 ) {
465 if ( isset( $status->value
[0] ) ) {
466 $status->value
= $status->value
[0];
468 $status->value
= false;
474 * Publish a batch of files
475 * @param $triplets Array: (source,dest,archive) triplets as per publish()
476 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
477 * that the source files should be deleted if possible
479 abstract function publishBatch( $triplets, $flags = 0 );
481 function fileExists( $file, $flags = 0 ) {
482 $result = $this->fileExistsBatch( array( $file ), $flags );
487 * Checks existence of an array of files.
489 * @param $files Array: URLs (or paths) of files to check
490 * @param $flags Integer: bitwise combination of the following flags:
491 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
492 * @return Either array of files and existence flags, or false
494 abstract function fileExistsBatch( $files, $flags = 0 );
497 * Move a group of files to the deletion archive.
499 * If no valid deletion archive is configured, this may either delete the
500 * file or throw an exception, depending on the preference of the repository.
502 * The overwrite policy is determined by the repository -- currently FSRepo
503 * assumes a naming scheme in the deleted zone based on content hash, as
504 * opposed to the public zone which is assumed to be unique.
506 * @param $sourceDestPairs Array of source/destination pairs. Each element
507 * is a two-element array containing the source file path relative to the
508 * public root in the first element, and the archive file path relative
509 * to the deleted zone root in the second element.
510 * @return FileRepoStatus
512 abstract function deleteBatch( $sourceDestPairs );
515 * Move a file to the deletion archive.
516 * If no valid deletion archive exists, this may either delete the file
517 * or throw an exception, depending on the preference of the repository
518 * @param $srcRel Mixed: relative path for the file to be deleted
519 * @param $archiveRel Mixed: relative path for the archive location.
520 * Relative to a private archive directory.
521 * @return FileRepoStatus object
523 function delete( $srcRel, $archiveRel ) {
524 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
528 * Get properties of a file with a given virtual URL
529 * The virtual URL must refer to this repo
530 * Properties should ultimately be obtained via File::getPropsFromPath()
532 abstract function getFileProps( $virtualUrl );
535 * Call a callback function for every file in the repository
536 * May use either the database or the filesystem
539 function enumFiles( $callback ) {
540 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
544 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
546 function validateFilename( $filename ) {
547 if ( strval( $filename ) == '' ) {
550 if ( wfIsWindows() ) {
551 $filename = strtr( $filename, '\\', '/' );
554 * Use the same traversal protection as Title::secureAndSplit()
556 if ( strpos( $filename, '.' ) !== false &&
557 ( $filename === '.' ||
$filename === '..' ||
558 strpos( $filename, './' ) === 0 ||
559 strpos( $filename, '../' ) === 0 ||
560 strpos( $filename, '/./' ) !== false ||
561 strpos( $filename, '/../' ) !== false ) )
570 * Path disclosure protection functions
572 function paranoidClean( $param ) { return '[hidden]'; }
573 function passThrough( $param ) { return $param; }
576 * Get a callback function to use for cleaning error message parameters
578 function getErrorCleanupFunction() {
579 switch ( $this->pathDisclosureProtection
) {
581 $callback = array( $this, 'passThrough' );
583 default: // 'paranoid'
584 $callback = array( $this, 'paranoidClean' );
591 * Create a new fatal error
593 function newFatal( $message /*, parameters...*/ ) {
594 $params = func_get_args();
595 array_unshift( $params, $this );
596 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
600 * Create a new good result
602 function newGood( $value = null ) {
603 return FileRepoStatus
::newGood( $this, $value );
607 * Delete files in the deleted directory if they are not referenced in the filearchive table
610 function cleanupDeletedBatch( $storageKeys ) {}
613 * Checks if there is a redirect named as $title. If there is, return the
614 * title object. If not, return false.
617 * @param $title Title of image
619 function checkRedirect( $title ) {
624 * Invalidates image redirect cache related to that image
625 * Doesn't do anything for repositories that don't support image redirects.
628 * @param $title Title of image
630 function invalidateImageRedirect( $title ) {}
633 * Get an array or iterator of file objects for files that have a given
634 * SHA-1 content hash.
638 function findBySha1( $hash ) {
643 * Get the human-readable name of the repo.
646 public function getDisplayName() {
647 // We don't name our own repo, return nothing
648 if ( $this->isLocal() ) {
651 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
652 $repoName = wfMsg( 'shared-repo-name-' . $this->name
);
653 if ( !wfEmptyMsg( 'shared-repo-name-' . $this->name
, $repoName ) ) {
656 return wfMsg( 'shared-repo' );
660 * Returns true if this the local file repository.
665 return $this->getName() == 'local';
670 * Get a key on the primary cache for this repository.
671 * Returns false if the repository's cache is not accessible at this site.
672 * The parameters are the parts of the key, as for wfMemcKey().
676 function getSharedCacheKey( /*...*/ ) {
681 * Get a key for this repo in the local cache domain. These cache keys are
682 * not shared with remote instances of the repo.
683 * The parameters are the parts of the key, as for wfMemcKey().
685 function getLocalCacheKey( /*...*/ ) {
686 $args = func_get_args();
687 array_unshift( $args, 'filerepo', $this->getName() );
688 return call_user_func_array( 'wfMemcKey', $args );