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',
34 'descriptionCacheExpiry', 'apiThumbCacheExpiry', 'apiThumbCacheDir' ) 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_IMAGE
, $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 mixed $time 14-character timestamp, or false for the current version
85 function findFile( $title, $time = false, $flags = 0 ) {
86 if ( !($title instanceof Title
) ) {
87 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
88 if ( !is_object( $title ) ) {
92 # First try the current version of the file to see if it precedes the timestamp
93 $img = $this->newFile( $title );
97 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
100 # Now try an old version of the file
101 if ( $time !== false ) {
102 $img = $this->newFile( $title, $time );
103 if ( $img->exists() ) {
104 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
106 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
113 if ( $flags & FileRepo
::FIND_IGNORE_REDIRECT
) {
116 $redir = $this->checkRedirect( $title );
117 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
118 $img = $this->newFile( $redir );
122 if( $img->exists() ) {
123 $img->redirectedFrom( $title->getDBkey() );
131 * Find many files at once.
132 * @param array $titles, an array of titles
135 function findFiles( $titles, $flags ) {
137 foreach ( $titles as $index => $title ) {
138 $file = $this->findFile( $title, $flags );
140 $result[$file->getTitle()->getDBkey()] = $file;
146 * Create a new File object from the local repository
147 * @param mixed $sha1 SHA-1 key
148 * @param mixed $time Time at which the image was uploaded.
149 * If this is specified, the returned object will be an
150 * instance of the repository's old file class instead of
151 * a current file. Repositories not supporting version
152 * control should return false if this parameter is set.
154 function newFileFromKey( $sha1, $time = false ) {
156 if ( $this->oldFileFactoryKey
) {
157 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
162 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
167 * Find an instance of the file with this key, created at the specified time
168 * Returns false if the file does not exist. Repositories not supporting
169 * version control should return false if the time is specified.
171 * @param string $sha1 string
172 * @param mixed $time 14-character timestamp, or false for the current version
174 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
175 # First try the current version of the file to see if it precedes the timestamp
176 $img = $this->newFileFromKey( $sha1 );
180 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
183 # Now try an old version of the file
184 if ( $time !== false ) {
185 $img = $this->newFileFromKey( $sha1, $time );
186 if ( $img->exists() ) {
187 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
189 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
198 * Get the URL of thumb.php
200 function getThumbScriptUrl() {
201 return $this->thumbScriptUrl
;
205 * Returns true if the repository can transform files via a 404 handler
207 function canTransformVia404() {
208 return $this->transformVia404
;
212 * Get the name of an image from its title object
214 function getNameFromTitle( $title ) {
215 global $wgCapitalLinks;
216 if ( $this->initialCapital
!= $wgCapitalLinks ) {
218 $name = $title->getUserCaseDBKey();
219 if ( $this->initialCapital
) {
220 $name = $wgContLang->ucfirst( $name );
223 $name = $title->getDBkey();
228 static function getHashPathForLevel( $name, $levels ) {
229 if ( $levels == 0 ) {
232 $hash = md5( $name );
234 for ( $i = 1; $i <= $levels; $i++
) {
235 $path .= substr( $hash, 0, $i ) . '/';
242 * Get the name of this repository, as specified by $info['name]' to the constructor
249 * Get the file description page base URL, or false if there isn't one.
252 function getDescBaseUrl() {
253 if ( is_null( $this->descBaseUrl
) ) {
254 if ( !is_null( $this->articleUrl
) ) {
255 $this->descBaseUrl
= str_replace( '$1',
256 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
257 } elseif ( !is_null( $this->scriptDirUrl
) ) {
258 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
259 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
261 $this->descBaseUrl
= false;
264 return $this->descBaseUrl
;
268 * Get the URL of an image description page. May return false if it is
269 * unknown or not applicable. In general this should only be called by the
270 * File class, since it may return invalid results for certain kinds of
271 * repositories. Use File::getDescriptionUrl() in user code.
273 * In particular, it uses the article paths as specified to the repository
274 * constructor, whereas local repositories use the local Title functions.
276 function getDescriptionUrl( $name ) {
277 $base = $this->getDescBaseUrl();
279 return $base . wfUrlencode( $name );
286 * Get the URL of the content-only fragment of the description page. For
287 * MediaWiki this means action=render. This should only be called by the
288 * repository's file class, since it may return invalid results. User code
289 * should use File::getDescriptionText().
291 function getDescriptionRenderUrl( $name ) {
292 if ( isset( $this->scriptDirUrl
) ) {
293 return $this->scriptDirUrl
. '/index.php?title=' .
294 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
297 $descBase = $this->getDescBaseUrl();
299 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
307 * Store a file to a given destination.
309 * @param string $srcPath Source path or virtual URL
310 * @param string $dstZone Destination zone
311 * @param string $dstRel Destination relative path
312 * @param integer $flags Bitwise combination of the following flags:
313 * self::DELETE_SOURCE Delete the source file after upload
314 * self::OVERWRITE Overwrite an existing destination file instead of failing
315 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
316 * same contents as the source
317 * @return FileRepoStatus
319 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
320 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
321 if ( $status->successCount
== 0 ) {
328 * Store a batch of files
330 * @param array $triplets (src,zone,dest) triplets as per store()
331 * @param integer $flags Flags as per store
333 abstract function storeBatch( $triplets, $flags = 0 );
336 * Pick a random name in the temp zone and store a file to it.
337 * Returns a FileRepoStatus object with the URL in the value.
339 * @param string $originalName The base name of the file as specified
340 * by the user. The file extension will be maintained.
341 * @param string $srcPath The current location of the file.
343 abstract function storeTemp( $originalName, $srcPath );
346 * Remove a temporary file or mark it for garbage collection
347 * @param string $virtualUrl The virtual URL returned by storeTemp
348 * @return boolean True on success, false on failure
351 function freeTemp( $virtualUrl ) {
356 * Copy or move a file either from the local filesystem or from an mwrepo://
357 * virtual URL, into this repository at the specified destination location.
359 * Returns a FileRepoStatus object. On success, the value contains "new" or
360 * "archived", to indicate whether the file was new with that name.
362 * @param string $srcPath The source path or URL
363 * @param string $dstRel The destination relative path
364 * @param string $archiveRel The relative path where the existing file is to
365 * be archived, if there is one. Relative to the public zone root.
366 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
367 * that the source file should be deleted if possible
369 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
370 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
371 if ( $status->successCount
== 0 ) {
374 if ( isset( $status->value
[0] ) ) {
375 $status->value
= $status->value
[0];
377 $status->value
= false;
383 * Publish a batch of files
384 * @param array $triplets (source,dest,archive) triplets as per publish()
385 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
386 * that the source files should be deleted if possible
388 abstract function publishBatch( $triplets, $flags = 0 );
391 * Move a group of files to the deletion archive.
393 * If no valid deletion archive is configured, this may either delete the
394 * file or throw an exception, depending on the preference of the repository.
396 * The overwrite policy is determined by the repository -- currently FSRepo
397 * assumes a naming scheme in the deleted zone based on content hash, as
398 * opposed to the public zone which is assumed to be unique.
400 * @param array $sourceDestPairs Array of source/destination pairs. Each element
401 * is a two-element array containing the source file path relative to the
402 * public root in the first element, and the archive file path relative
403 * to the deleted zone root in the second element.
404 * @return FileRepoStatus
406 abstract function deleteBatch( $sourceDestPairs );
409 * Move a file to the deletion archive.
410 * If no valid deletion archive exists, this may either delete the file
411 * or throw an exception, depending on the preference of the repository
412 * @param mixed $srcRel Relative path for the file to be deleted
413 * @param mixed $archiveRel Relative path for the archive location.
414 * Relative to a private archive directory.
415 * @return WikiError object (wikitext-formatted), or true for success
417 function delete( $srcRel, $archiveRel ) {
418 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
422 * Get properties of a file with a given virtual URL
423 * The virtual URL must refer to this repo
424 * Properties should ultimately be obtained via File::getPropsFromPath()
426 abstract function getFileProps( $virtualUrl );
429 * Call a callback function for every file in the repository
430 * May use either the database or the filesystem
433 function enumFiles( $callback ) {
434 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
438 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
440 function validateFilename( $filename ) {
441 if ( strval( $filename ) == '' ) {
444 if ( wfIsWindows() ) {
445 $filename = strtr( $filename, '\\', '/' );
448 * Use the same traversal protection as Title::secureAndSplit()
450 if ( strpos( $filename, '.' ) !== false &&
451 ( $filename === '.' ||
$filename === '..' ||
452 strpos( $filename, './' ) === 0 ||
453 strpos( $filename, '../' ) === 0 ||
454 strpos( $filename, '/./' ) !== false ||
455 strpos( $filename, '/../' ) !== false ) )
464 * Path disclosure protection functions
466 function paranoidClean( $param ) { return '[hidden]'; }
467 function passThrough( $param ) { return $param; }
470 * Get a callback function to use for cleaning error message parameters
472 function getErrorCleanupFunction() {
473 switch ( $this->pathDisclosureProtection
) {
475 $callback = array( $this, 'passThrough' );
477 default: // 'paranoid'
478 $callback = array( $this, 'paranoidClean' );
485 * Create a new fatal error
487 function newFatal( $message /*, parameters...*/ ) {
488 $params = func_get_args();
489 array_unshift( $params, $this );
490 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
494 * Create a new good result
496 function newGood( $value = null ) {
497 return FileRepoStatus
::newGood( $this, $value );
501 * Delete files in the deleted directory if they are not referenced in the filearchive table
504 function cleanupDeletedBatch( $storageKeys ) {}
507 * Checks if there is a redirect named as $title
510 * @param Title $title Title of image
512 function checkRedirect( $title ) {
517 * Invalidates image redirect cache related to that image
520 * @param Title $title Title of image
522 function invalidateImageRedirect( $title ) {
525 function findBySha1( $hash ) {