4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
8 abstract class FileRepo
{
9 const DELETE_SOURCE
= 1;
10 const FIND_PRIVATE
= 1;
11 const FIND_IGNORE_REDIRECT
= 2;
13 const OVERWRITE_SAME
= 4;
15 var $thumbScriptUrl, $transformVia404;
16 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
17 var $pathDisclosureProtection = 'paranoid';
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
= true; // by default
32 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
33 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
35 if ( isset( $info[$var] ) ) {
36 $this->$var = $info[$var];
39 $this->transformVia404
= !empty( $info['transformVia404'] );
43 * Determine if a string is an mwrepo:// URL
45 static function isVirtualUrl( $url ) {
46 return substr( $url, 0, 9 ) == 'mwrepo://';
50 * Create a new File object from the local repository
51 * @param mixed $title Title object or string
52 * @param mixed $time Time at which the image was uploaded.
53 * If this is specified, the returned object will be an
54 * instance of the repository's old file class instead of
55 * a current file. Repositories not supporting version
56 * control should return false if this parameter is set.
58 function newFile( $title, $time = false ) {
59 if ( !($title instanceof Title
) ) {
60 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
61 if ( !is_object( $title ) ) {
66 if ( $this->oldFileFactory
) {
67 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
72 return call_user_func( $this->fileFactory
, $title, $this );
77 * Find an instance of the named file created at the specified time
78 * Returns false if the file does not exist. Repositories not supporting
79 * version control should return false if the time is specified.
81 * @param mixed $title Title object or string
82 * @param mixed $time 14-character timestamp, or false for the current version
84 function findFile( $title, $time = false, $flags = 0 ) {
85 if ( !($title instanceof Title
) ) {
86 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
87 if ( !is_object( $title ) ) {
91 # First try the current version of the file to see if it precedes the timestamp
92 $img = $this->newFile( $title );
96 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
99 # Now try an old version of the file
100 if ( $time !== false ) {
101 $img = $this->newFile( $title, $time );
102 if ( $img->exists() ) {
103 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
105 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
112 if ( $flags & FileRepo
::FIND_IGNORE_REDIRECT
) {
115 $redir = $this->checkRedirect( $title );
116 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
117 $img = $this->newFile( $redir );
121 if( $img->exists() ) {
122 $img->redirectedFrom( $title->getDBkey() );
130 * Find many files at once. Removes the corresponding titles
131 * of files that are found from $titles.
132 * @param array $titles, an array of titles
135 function findFiles( &$titles, $flags ) {
137 foreach ( $titles as $index => $title ) {
138 $file = $this->findFile( $title );
140 $result[$file->getTitle()->getDBkey()] = $file;
141 unset( $titles[$index] );
148 * Create a new File object from the local repository
149 * @param mixed $sha1 SHA-1 key
150 * @param mixed $time Time at which the image was uploaded.
151 * If this is specified, the returned object will be an
152 * instance of the repository's old file class instead of
153 * a current file. Repositories not supporting version
154 * control should return false if this parameter is set.
156 function newFileFromKey( $sha1, $time = false ) {
158 if ( $this->oldFileFactoryKey
) {
159 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
164 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
169 * Find an instance of the file with this key, created at the specified time
170 * Returns false if the file does not exist. Repositories not supporting
171 * version control should return false if the time is specified.
173 * @param string $sha1 string
174 * @param mixed $time 14-character timestamp, or false for the current version
176 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
177 # First try the current version of the file to see if it precedes the timestamp
178 $img = $this->newFileFromKey( $sha1 );
182 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
185 # Now try an old version of the file
186 if ( $time !== false ) {
187 $img = $this->newFileFromKey( $sha1, $time );
188 if ( $img->exists() ) {
189 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
191 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
200 * Get the URL of thumb.php
202 function getThumbScriptUrl() {
203 return $this->thumbScriptUrl
;
207 * Returns true if the repository can transform files via a 404 handler
209 function canTransformVia404() {
210 return $this->transformVia404
;
214 * Get the name of an image from its title object
216 function getNameFromTitle( $title ) {
217 global $wgCapitalLinks;
218 if ( $this->initialCapital
!= $wgCapitalLinks ) {
220 $name = $title->getUserCaseDBKey();
221 if ( $this->initialCapital
) {
222 $name = $wgContLang->ucfirst( $name );
225 $name = $title->getDBkey();
230 static function getHashPathForLevel( $name, $levels ) {
231 if ( $levels == 0 ) {
234 $hash = md5( $name );
236 for ( $i = 1; $i <= $levels; $i++
) {
237 $path .= substr( $hash, 0, $i ) . '/';
244 * Get the name of this repository, as specified by $info['name]' to the constructor
251 * Get the file description page base URL, or false if there isn't one.
254 function getDescBaseUrl() {
255 if ( is_null( $this->descBaseUrl
) ) {
256 if ( !is_null( $this->articleUrl
) ) {
257 $this->descBaseUrl
= str_replace( '$1',
258 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
259 } elseif ( !is_null( $this->scriptDirUrl
) ) {
260 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
261 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
263 $this->descBaseUrl
= false;
266 return $this->descBaseUrl
;
270 * Get the URL of an image description page. May return false if it is
271 * unknown or not applicable. In general this should only be called by the
272 * File class, since it may return invalid results for certain kinds of
273 * repositories. Use File::getDescriptionUrl() in user code.
275 * In particular, it uses the article paths as specified to the repository
276 * constructor, whereas local repositories use the local Title functions.
278 function getDescriptionUrl( $name ) {
279 $base = $this->getDescBaseUrl();
281 return $base . wfUrlencode( $name );
288 * Get the URL of the content-only fragment of the description page. For
289 * MediaWiki this means action=render. This should only be called by the
290 * repository's file class, since it may return invalid results. User code
291 * should use File::getDescriptionText().
293 function getDescriptionRenderUrl( $name ) {
294 if ( isset( $this->scriptDirUrl
) ) {
295 return $this->scriptDirUrl
. '/index.php?title=' .
296 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
299 $descBase = $this->getDescBaseUrl();
301 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
309 * Store a file to a given destination.
311 * @param string $srcPath Source path or virtual URL
312 * @param string $dstZone Destination zone
313 * @param string $dstRel Destination relative path
314 * @param integer $flags Bitwise combination of the following flags:
315 * self::DELETE_SOURCE Delete the source file after upload
316 * self::OVERWRITE Overwrite an existing destination file instead of failing
317 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
318 * same contents as the source
319 * @return FileRepoStatus
321 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
322 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
323 if ( $status->successCount
== 0 ) {
330 * Store a batch of files
332 * @param array $triplets (src,zone,dest) triplets as per store()
333 * @param integer $flags Flags as per store
335 abstract function storeBatch( $triplets, $flags = 0 );
338 * Pick a random name in the temp zone and store a file to it.
339 * Returns a FileRepoStatus object with the URL in the value.
341 * @param string $originalName The base name of the file as specified
342 * by the user. The file extension will be maintained.
343 * @param string $srcPath The current location of the file.
345 abstract function storeTemp( $originalName, $srcPath );
348 * Remove a temporary file or mark it for garbage collection
349 * @param string $virtualUrl The virtual URL returned by storeTemp
350 * @return boolean True on success, false on failure
353 function freeTemp( $virtualUrl ) {
358 * Copy or move a file either from the local filesystem or from an mwrepo://
359 * virtual URL, into this repository at the specified destination location.
361 * Returns a FileRepoStatus object. On success, the value contains "new" or
362 * "archived", to indicate whether the file was new with that name.
364 * @param string $srcPath The source path or URL
365 * @param string $dstRel The destination relative path
366 * @param string $archiveRel The relative path where the existing file is to
367 * be archived, if there is one. Relative to the public zone root.
368 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
369 * that the source file should be deleted if possible
371 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
372 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
373 if ( $status->successCount
== 0 ) {
376 if ( isset( $status->value
[0] ) ) {
377 $status->value
= $status->value
[0];
379 $status->value
= false;
385 * Publish a batch of files
386 * @param array $triplets (source,dest,archive) triplets as per publish()
387 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
388 * that the source files should be deleted if possible
390 abstract function publishBatch( $triplets, $flags = 0 );
393 * Move a group of files to the deletion archive.
395 * If no valid deletion archive is configured, this may either delete the
396 * file or throw an exception, depending on the preference of the repository.
398 * The overwrite policy is determined by the repository -- currently FSRepo
399 * assumes a naming scheme in the deleted zone based on content hash, as
400 * opposed to the public zone which is assumed to be unique.
402 * @param array $sourceDestPairs Array of source/destination pairs. Each element
403 * is a two-element array containing the source file path relative to the
404 * public root in the first element, and the archive file path relative
405 * to the deleted zone root in the second element.
406 * @return FileRepoStatus
408 abstract function deleteBatch( $sourceDestPairs );
411 * Move a file to the deletion archive.
412 * If no valid deletion archive exists, this may either delete the file
413 * or throw an exception, depending on the preference of the repository
414 * @param mixed $srcRel Relative path for the file to be deleted
415 * @param mixed $archiveRel Relative path for the archive location.
416 * Relative to a private archive directory.
417 * @return WikiError object (wikitext-formatted), or true for success
419 function delete( $srcRel, $archiveRel ) {
420 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
424 * Get properties of a file with a given virtual URL
425 * The virtual URL must refer to this repo
426 * Properties should ultimately be obtained via File::getPropsFromPath()
428 abstract function getFileProps( $virtualUrl );
431 * Call a callback function for every file in the repository
432 * May use either the database or the filesystem
435 function enumFiles( $callback ) {
436 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
440 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
442 function validateFilename( $filename ) {
443 if ( strval( $filename ) == '' ) {
446 if ( wfIsWindows() ) {
447 $filename = strtr( $filename, '\\', '/' );
450 * Use the same traversal protection as Title::secureAndSplit()
452 if ( strpos( $filename, '.' ) !== false &&
453 ( $filename === '.' ||
$filename === '..' ||
454 strpos( $filename, './' ) === 0 ||
455 strpos( $filename, '../' ) === 0 ||
456 strpos( $filename, '/./' ) !== false ||
457 strpos( $filename, '/../' ) !== false ) )
466 * Path disclosure protection functions
468 function paranoidClean( $param ) { return '[hidden]'; }
469 function passThrough( $param ) { return $param; }
472 * Get a callback function to use for cleaning error message parameters
474 function getErrorCleanupFunction() {
475 switch ( $this->pathDisclosureProtection
) {
477 $callback = array( $this, 'passThrough' );
479 default: // 'paranoid'
480 $callback = array( $this, 'paranoidClean' );
487 * Create a new fatal error
489 function newFatal( $message /*, parameters...*/ ) {
490 $params = func_get_args();
491 array_unshift( $params, $this );
492 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
496 * Create a new good result
498 function newGood( $value = null ) {
499 return FileRepoStatus
::newGood( $this, $value );
503 * Delete files in the deleted directory if they are not referenced in the filearchive table
506 function cleanupDeletedBatch( $storageKeys ) {}
509 * Checks if there is a redirect named as $title
512 * @param Title $title Title of image
514 function checkRedirect( $title ) {
519 * Invalidates image redirect cache related to that image
522 * @param Title $title Title of image
524 function invalidateImageRedirect( $title ) {
527 function findBySha1( $hash ) {