7fe8e81316dabee6a26d87bce79bce5c0a2ad08a
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;
33 var $fileFactoryKey = false, $oldFileFactoryKey = false;
35 function __construct( $info ) {
37 $this->name
= $info['name'];
40 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
41 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
42 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
43 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
46 if ( isset( $info[$var] ) ) {
47 $this->$var = $info[$var];
50 $this->transformVia404
= !empty( $info['transformVia404'] );
54 * Determine if a string is an mwrepo:// URL
56 static function isVirtualUrl( $url ) {
57 return substr( $url, 0, 9 ) == 'mwrepo://';
61 * Create a new File object from the local repository
63 * @param $title Mixed: Title object or string
64 * @param $time Mixed: Time at which the image was uploaded.
65 * If this is specified, the returned object will be an
66 * instance of the repository's old file class instead of a
67 * current file. Repositories not supporting version control
68 * should return false if this parameter is set.
72 function newFile( $title, $time = false ) {
73 if ( !($title instanceof Title
) ) {
74 $title = Title
::makeTitleSafe( NS_FILE
, $title );
75 if ( !is_object( $title ) ) {
80 if ( $this->oldFileFactory
) {
81 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
86 return call_user_func( $this->fileFactory
, $title, $this );
91 * Find an instance of the named file created at the specified time
92 * Returns false if the file does not exist. Repositories not supporting
93 * version control should return false if the time is specified.
95 * @param $title Mixed: Title object or string
96 * @param $options Associative array of options:
97 * time: requested time for an archived image, or false for the
98 * current version. An image object will be returned which was
99 * created at the specified time.
101 * ignoreRedirect: If true, do not follow file redirects
103 * private: If true, return restricted (deleted) files if the current
104 * user is allowed to view them. Otherwise, such files will not
107 function findFile( $title, $options = array() ) {
108 $time = isset( $options['time'] ) ?
$options['time'] : false;
109 if ( !($title instanceof Title
) ) {
110 $title = Title
::makeTitleSafe( NS_FILE
, $title );
111 if ( !is_object( $title ) ) {
115 # First try the current version of the file to see if it precedes the timestamp
116 $img = $this->newFile( $title );
120 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
123 # Now try an old version of the file
124 if ( $time !== false ) {
125 $img = $this->newFile( $title, $time );
126 if ( $img && $img->exists() ) {
127 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
129 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
136 if ( !empty( $options['ignoreRedirect'] ) ) {
139 $redir = $this->checkRedirect( $title );
140 if( $redir && $title->getNamespace() == NS_FILE
) {
141 $img = $this->newFile( $redir );
145 if( $img->exists() ) {
146 $img->redirectedFrom( $title->getDBkey() );
154 * Find many files at once.
155 * @param $items An array of titles, or an array of findFile() options with
156 * the "title" option giving the title. Example:
158 * $findItem = array( 'title' => $title, 'private' => true );
159 * $findBatch = array( $findItem );
160 * $repo->findFiles( $findBatch );
162 function findFiles( $items ) {
164 foreach ( $items as $item ) {
165 if ( is_array( $item ) ) {
166 $title = $item['title'];
168 unset( $options['title'] );
173 $file = $this->findFile( $title, $options );
175 $result[$file->getTitle()->getDBkey()] = $file;
182 * Create a new File object from the local repository
183 * @param $sha1 Mixed: base 36 SHA-1 hash
184 * @param $time Mixed: time at which the image was uploaded.
185 * If this is specified, the returned object will be an
186 * of the repository's old file class instead of a current
187 * file. Repositories not supporting version control should
188 * 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 );
198 if ( $this->fileFactoryKey
) {
199 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
206 * Find an instance of the file with this key, created at the specified time
207 * Returns false if the file does not exist. Repositories not supporting
208 * version control should return false if the time is specified.
210 * @param $sha1 String base 36 SHA-1 hash
211 * @param $options Option array, same as findFile().
213 function findFileFromKey( $sha1, $options = array() ) {
214 $time = isset( $options['time'] ) ?
$options['time'] : false;
216 # First try the current version of the file to see if it precedes the timestamp
217 $img = $this->newFileFromKey( $sha1 );
221 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
224 # Now try an old version of the file
225 if ( $time !== false ) {
226 $img = $this->newFileFromKey( $sha1, $time );
227 if ( $img && $img->exists() ) {
228 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
230 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
239 * Get the URL of thumb.php
241 function getThumbScriptUrl() {
242 return $this->thumbScriptUrl
;
246 * Get the URL corresponding to one of the four basic zones
247 * @param $zone String: one of: public, deleted, temp, thumb
248 * @return String or false
250 function getZoneUrl( $zone ) {
255 * Returns true if the repository can transform files via a 404 handler
257 function canTransformVia404() {
258 return $this->transformVia404
;
262 * Get the name of an image from its title object
263 * @param $title Title
265 function getNameFromTitle( $title ) {
266 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
268 $name = $title->getUserCaseDBKey();
269 if ( $this->initialCapital
) {
270 $name = $wgContLang->ucfirst( $name );
273 $name = $title->getDBkey();
278 static function getHashPathForLevel( $name, $levels ) {
279 if ( $levels == 0 ) {
282 $hash = md5( $name );
284 for ( $i = 1; $i <= $levels; $i++
) {
285 $path .= substr( $hash, 0, $i ) . '/';
292 * Get a relative path including trailing slash, e.g. f/fa/
293 * If the repo is not hashed, returns an empty string
295 function getHashPath( $name ) {
296 return self
::getHashPathForLevel( $name, $this->hashLevels
);
300 * Get the name of this repository, as specified by $info['name]' to the constructor
307 * Make an url to this repo
309 * @param $query mixed Query string to append
310 * @param $entry string Entry point; defaults to index
313 function makeUrl( $query = '', $entry = 'index' ) {
314 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
315 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
319 * Get the URL of an image description page. May return false if it is
320 * unknown or not applicable. In general this should only be called by the
321 * File class, since it may return invalid results for certain kinds of
322 * repositories. Use File::getDescriptionUrl() in user code.
324 * In particular, it uses the article paths as specified to the repository
325 * constructor, whereas local repositories use the local Title functions.
327 function getDescriptionUrl( $name ) {
328 $encName = wfUrlencode( $name );
329 if ( !is_null( $this->descBaseUrl
) ) {
330 # "http://example.com/wiki/Image:"
331 return $this->descBaseUrl
. $encName;
333 if ( !is_null( $this->articleUrl
) ) {
334 # "http://example.com/wiki/$1"
336 # We use "Image:" as the canonical namespace for
337 # compatibility across all MediaWiki versions.
338 return str_replace( '$1',
339 "Image:$encName", $this->articleUrl
);
341 if ( !is_null( $this->scriptDirUrl
) ) {
342 # "http://example.com/w"
344 # We use "Image:" as the canonical namespace for
345 # compatibility across all MediaWiki versions,
346 # and just sort of hope index.php is right. ;)
347 return $this->makeUrl( "title=Image:$encName" );
353 * Get the URL of the content-only fragment of the description page. For
354 * MediaWiki this means action=render. This should only be called by the
355 * repository's file class, since it may return invalid results. User code
356 * should use File::getDescriptionText().
357 * @param $name String: name of image to fetch
358 * @param $lang String: language to fetch it in, if any.
360 function getDescriptionRenderUrl( $name, $lang = null ) {
361 $query = 'action=render';
362 if ( !is_null( $lang ) ) {
363 $query .= '&uselang=' . $lang;
365 if ( isset( $this->scriptDirUrl
) ) {
366 return $this->makeUrl(
368 wfUrlencode( 'Image:' . $name ) .
371 $descUrl = $this->getDescriptionUrl( $name );
373 return wfAppendQuery( $descUrl, $query );
381 * Get the URL of the stylesheet to apply to description pages
384 function getDescriptionStylesheetUrl() {
385 if ( $this->scriptDirUrl
) {
386 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
387 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
392 * Store a file to a given destination.
394 * @param $srcPath String: source path or virtual URL
395 * @param $dstZone String: destination zone
396 * @param $dstRel String: destination relative path
397 * @param $flags Integer: bitwise combination of the following flags:
398 * self::DELETE_SOURCE Delete the source file after upload
399 * self::OVERWRITE Overwrite an existing destination file instead of failing
400 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
401 * same contents as the source
402 * @return FileRepoStatus
404 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
405 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
406 if ( $status->successCount
== 0 ) {
413 * Store a batch of files
415 * @param $triplets Array: (src,zone,dest) triplets as per store()
416 * @param $flags Integer: flags as per store
418 abstract function storeBatch( $triplets, $flags = 0 );
421 * Pick a random name in the temp zone and store a file to it.
422 * Returns a FileRepoStatus object with the URL in the value.
424 * @param $originalName String: the base name of the file as specified
425 * by the user. The file extension will be maintained.
426 * @param $srcPath String: the current location of the file.
428 abstract function storeTemp( $originalName, $srcPath );
432 * Append the contents of the source path to the given file, OR queue
433 * the appending operation in anticipation of a later appendFinish() call.
434 * @param $srcPath String: location of the source file
435 * @param $toAppendPath String: path to append to.
436 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
437 * that the source file should be deleted if possible
438 * @return mixed Status or false
440 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
443 * Finish the append operation.
444 * @param $toAppendPath String: path to append to.
445 * @return mixed Status or false
447 abstract function appendFinish( $toAppendPath );
450 * Remove a temporary file or mark it for garbage collection
451 * @param $virtualUrl String: the virtual URL returned by storeTemp
452 * @return Boolean: true on success, false on failure
455 function freeTemp( $virtualUrl ) {
460 * Copy or move a file either from the local filesystem or from an mwrepo://
461 * virtual URL, into this repository at the specified destination location.
463 * Returns a FileRepoStatus object. On success, the value contains "new" or
464 * "archived", to indicate whether the file was new with that name.
466 * @param $srcPath String: the source path or URL
467 * @param $dstRel String: the destination relative path
468 * @param $archiveRel String: rhe relative path where the existing file is to
469 * be archived, if there is one. Relative to the public zone root.
470 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
471 * that the source file should be deleted if possible
473 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
474 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
475 if ( $status->successCount
== 0 ) {
478 if ( isset( $status->value
[0] ) ) {
479 $status->value
= $status->value
[0];
481 $status->value
= false;
487 * Publish a batch of files
488 * @param $triplets Array: (source,dest,archive) triplets as per publish()
489 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
490 * that the source files should be deleted if possible
492 abstract function publishBatch( $triplets, $flags = 0 );
494 function fileExists( $file, $flags = 0 ) {
495 $result = $this->fileExistsBatch( array( $file ), $flags );
500 * Checks existence of an array of files.
502 * @param $files Array: URLs (or paths) of files to check
503 * @param $flags Integer: bitwise combination of the following flags:
504 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
505 * @return Either array of files and existence flags, or false
507 abstract function fileExistsBatch( $files, $flags = 0 );
510 * Move a group of files to the deletion archive.
512 * If no valid deletion archive is configured, this may either delete the
513 * file or throw an exception, depending on the preference of the repository.
515 * The overwrite policy is determined by the repository -- currently FSRepo
516 * assumes a naming scheme in the deleted zone based on content hash, as
517 * opposed to the public zone which is assumed to be unique.
519 * @param $sourceDestPairs Array of source/destination pairs. Each element
520 * is a two-element array containing the source file path relative to the
521 * public root in the first element, and the archive file path relative
522 * to the deleted zone root in the second element.
523 * @return FileRepoStatus
525 abstract function deleteBatch( $sourceDestPairs );
528 * Move a file to the deletion archive.
529 * If no valid deletion archive exists, this may either delete the file
530 * or throw an exception, depending on the preference of the repository
531 * @param $srcRel Mixed: relative path for the file to be deleted
532 * @param $archiveRel Mixed: relative path for the archive location.
533 * Relative to a private archive directory.
534 * @return FileRepoStatus object
536 function delete( $srcRel, $archiveRel ) {
537 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
541 * Get properties of a file with a given virtual URL
542 * The virtual URL must refer to this repo
543 * Properties should ultimately be obtained via File::getPropsFromPath()
545 abstract function getFileProps( $virtualUrl );
548 * Call a callback function for every file in the repository
549 * May use either the database or the filesystem
552 function enumFiles( $callback ) {
553 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
557 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
559 function validateFilename( $filename ) {
560 if ( strval( $filename ) == '' ) {
563 if ( wfIsWindows() ) {
564 $filename = strtr( $filename, '\\', '/' );
567 * Use the same traversal protection as Title::secureAndSplit()
569 if ( strpos( $filename, '.' ) !== false &&
570 ( $filename === '.' ||
$filename === '..' ||
571 strpos( $filename, './' ) === 0 ||
572 strpos( $filename, '../' ) === 0 ||
573 strpos( $filename, '/./' ) !== false ||
574 strpos( $filename, '/../' ) !== false ) )
583 * Path disclosure protection functions
585 function paranoidClean( $param ) { return '[hidden]'; }
586 function passThrough( $param ) { return $param; }
589 * Get a callback function to use for cleaning error message parameters
591 function getErrorCleanupFunction() {
592 switch ( $this->pathDisclosureProtection
) {
594 $callback = array( $this, 'passThrough' );
596 default: // 'paranoid'
597 $callback = array( $this, 'paranoidClean' );
604 * Create a new fatal error
606 function newFatal( $message /*, parameters...*/ ) {
607 $params = func_get_args();
608 array_unshift( $params, $this );
609 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
613 * Create a new good result
615 function newGood( $value = null ) {
616 return FileRepoStatus
::newGood( $this, $value );
620 * Delete files in the deleted directory if they are not referenced in the filearchive table
623 function cleanupDeletedBatch( $storageKeys ) {}
626 * Checks if there is a redirect named as $title. If there is, return the
627 * title object. If not, return false.
630 * @param $title Title of image
633 function checkRedirect( $title ) {
638 * Invalidates image redirect cache related to that image
639 * Doesn't do anything for repositories that don't support image redirects.
642 * @param $title Title of image
644 function invalidateImageRedirect( $title ) {}
647 * Get an array or iterator of file objects for files that have a given
648 * SHA-1 content hash.
652 function findBySha1( $hash ) {
657 * Get the human-readable name of the repo.
660 public function getDisplayName() {
661 // We don't name our own repo, return nothing
662 if ( $this->isLocal() ) {
665 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
666 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
670 * Returns true if this the local file repository.
675 return $this->getName() == 'local';
680 * Get a key on the primary cache for this repository.
681 * Returns false if the repository's cache is not accessible at this site.
682 * The parameters are the parts of the key, as for wfMemcKey().
686 function getSharedCacheKey( /*...*/ ) {
691 * Get a key for this repo in the local cache domain. These cache keys are
692 * not shared with remote instances of the repo.
693 * The parameters are the parts of the key, as for wfMemcKey().
695 function getLocalCacheKey( /*...*/ ) {
696 $args = func_get_args();
697 array_unshift( $args, 'filerepo', $this->getName() );
698 return call_user_func_array( 'wfMemcKey', $args );
702 * Get an UploadStash associated with this repo.
704 * @return UploadStash
706 function getUploadStash() {
707 return new UploadStash( $this );