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', 'descriptionCacheExpiry' ) 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.
131 * @param array $titles, an array of titles
134 function findFiles( $titles, $flags ) {
136 foreach ( $titles as $index => $title ) {
137 $file = $this->findFile( $title, $flags );
139 $result[$file->getTitle()->getDBkey()] = $file;
145 * Create a new File object from the local repository
146 * @param mixed $sha1 SHA-1 key
147 * @param mixed $time Time at which the image was uploaded.
148 * If this is specified, the returned object will be an
149 * instance of the repository's old file class instead of
150 * a current file. Repositories not supporting version
151 * control should return false if this parameter is set.
153 function newFileFromKey( $sha1, $time = false ) {
155 if ( $this->oldFileFactoryKey
) {
156 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
161 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
166 * Find an instance of the file with this key, created at the specified time
167 * Returns false if the file does not exist. Repositories not supporting
168 * version control should return false if the time is specified.
170 * @param string $sha1 string
171 * @param mixed $time 14-character timestamp, or false for the current version
173 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
174 # First try the current version of the file to see if it precedes the timestamp
175 $img = $this->newFileFromKey( $sha1 );
179 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
182 # Now try an old version of the file
183 if ( $time !== false ) {
184 $img = $this->newFileFromKey( $sha1, $time );
185 if ( $img->exists() ) {
186 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
188 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
197 * Get the URL of thumb.php
199 function getThumbScriptUrl() {
200 return $this->thumbScriptUrl
;
204 * Returns true if the repository can transform files via a 404 handler
206 function canTransformVia404() {
207 return $this->transformVia404
;
211 * Get the name of an image from its title object
213 function getNameFromTitle( $title ) {
214 global $wgCapitalLinks;
215 if ( $this->initialCapital
!= $wgCapitalLinks ) {
217 $name = $title->getUserCaseDBKey();
218 if ( $this->initialCapital
) {
219 $name = $wgContLang->ucfirst( $name );
222 $name = $title->getDBkey();
227 static function getHashPathForLevel( $name, $levels ) {
228 if ( $levels == 0 ) {
231 $hash = md5( $name );
233 for ( $i = 1; $i <= $levels; $i++
) {
234 $path .= substr( $hash, 0, $i ) . '/';
241 * Get the name of this repository, as specified by $info['name]' to the constructor
248 * Get the file description page base URL, or false if there isn't one.
251 function getDescBaseUrl() {
252 if ( is_null( $this->descBaseUrl
) ) {
253 if ( !is_null( $this->articleUrl
) ) {
254 $this->descBaseUrl
= str_replace( '$1',
255 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
256 } elseif ( !is_null( $this->scriptDirUrl
) ) {
257 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
258 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
260 $this->descBaseUrl
= false;
263 return $this->descBaseUrl
;
267 * Get the URL of an image description page. May return false if it is
268 * unknown or not applicable. In general this should only be called by the
269 * File class, since it may return invalid results for certain kinds of
270 * repositories. Use File::getDescriptionUrl() in user code.
272 * In particular, it uses the article paths as specified to the repository
273 * constructor, whereas local repositories use the local Title functions.
275 function getDescriptionUrl( $name ) {
276 $base = $this->getDescBaseUrl();
278 return $base . wfUrlencode( $name );
285 * Get the URL of the content-only fragment of the description page. For
286 * MediaWiki this means action=render. This should only be called by the
287 * repository's file class, since it may return invalid results. User code
288 * should use File::getDescriptionText().
290 function getDescriptionRenderUrl( $name ) {
291 if ( isset( $this->scriptDirUrl
) ) {
292 return $this->scriptDirUrl
. '/index.php?title=' .
293 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
296 $descBase = $this->getDescBaseUrl();
298 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
306 * Store a file to a given destination.
308 * @param string $srcPath Source path or virtual URL
309 * @param string $dstZone Destination zone
310 * @param string $dstRel Destination relative path
311 * @param integer $flags Bitwise combination of the following flags:
312 * self::DELETE_SOURCE Delete the source file after upload
313 * self::OVERWRITE Overwrite an existing destination file instead of failing
314 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
315 * same contents as the source
316 * @return FileRepoStatus
318 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
319 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
320 if ( $status->successCount
== 0 ) {
327 * Store a batch of files
329 * @param array $triplets (src,zone,dest) triplets as per store()
330 * @param integer $flags Flags as per store
332 abstract function storeBatch( $triplets, $flags = 0 );
335 * Pick a random name in the temp zone and store a file to it.
336 * Returns a FileRepoStatus object with the URL in the value.
338 * @param string $originalName The base name of the file as specified
339 * by the user. The file extension will be maintained.
340 * @param string $srcPath The current location of the file.
342 abstract function storeTemp( $originalName, $srcPath );
345 * Remove a temporary file or mark it for garbage collection
346 * @param string $virtualUrl The virtual URL returned by storeTemp
347 * @return boolean True on success, false on failure
350 function freeTemp( $virtualUrl ) {
355 * Copy or move a file either from the local filesystem or from an mwrepo://
356 * virtual URL, into this repository at the specified destination location.
358 * Returns a FileRepoStatus object. On success, the value contains "new" or
359 * "archived", to indicate whether the file was new with that name.
361 * @param string $srcPath The source path or URL
362 * @param string $dstRel The destination relative path
363 * @param string $archiveRel The relative path where the existing file is to
364 * be archived, if there is one. Relative to the public zone root.
365 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
366 * that the source file should be deleted if possible
368 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
369 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
370 if ( $status->successCount
== 0 ) {
373 if ( isset( $status->value
[0] ) ) {
374 $status->value
= $status->value
[0];
376 $status->value
= false;
382 * Publish a batch of files
383 * @param array $triplets (source,dest,archive) triplets as per publish()
384 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
385 * that the source files should be deleted if possible
387 abstract function publishBatch( $triplets, $flags = 0 );
390 * Move a group of files to the deletion archive.
392 * If no valid deletion archive is configured, this may either delete the
393 * file or throw an exception, depending on the preference of the repository.
395 * The overwrite policy is determined by the repository -- currently FSRepo
396 * assumes a naming scheme in the deleted zone based on content hash, as
397 * opposed to the public zone which is assumed to be unique.
399 * @param array $sourceDestPairs Array of source/destination pairs. Each element
400 * is a two-element array containing the source file path relative to the
401 * public root in the first element, and the archive file path relative
402 * to the deleted zone root in the second element.
403 * @return FileRepoStatus
405 abstract function deleteBatch( $sourceDestPairs );
408 * Move a file to the deletion archive.
409 * If no valid deletion archive exists, this may either delete the file
410 * or throw an exception, depending on the preference of the repository
411 * @param mixed $srcRel Relative path for the file to be deleted
412 * @param mixed $archiveRel Relative path for the archive location.
413 * Relative to a private archive directory.
414 * @return WikiError object (wikitext-formatted), or true for success
416 function delete( $srcRel, $archiveRel ) {
417 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
421 * Get properties of a file with a given virtual URL
422 * The virtual URL must refer to this repo
423 * Properties should ultimately be obtained via File::getPropsFromPath()
425 abstract function getFileProps( $virtualUrl );
428 * Call a callback function for every file in the repository
429 * May use either the database or the filesystem
432 function enumFiles( $callback ) {
433 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
437 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
439 function validateFilename( $filename ) {
440 if ( strval( $filename ) == '' ) {
443 if ( wfIsWindows() ) {
444 $filename = strtr( $filename, '\\', '/' );
447 * Use the same traversal protection as Title::secureAndSplit()
449 if ( strpos( $filename, '.' ) !== false &&
450 ( $filename === '.' ||
$filename === '..' ||
451 strpos( $filename, './' ) === 0 ||
452 strpos( $filename, '../' ) === 0 ||
453 strpos( $filename, '/./' ) !== false ||
454 strpos( $filename, '/../' ) !== false ) )
463 * Path disclosure protection functions
465 function paranoidClean( $param ) { return '[hidden]'; }
466 function passThrough( $param ) { return $param; }
469 * Get a callback function to use for cleaning error message parameters
471 function getErrorCleanupFunction() {
472 switch ( $this->pathDisclosureProtection
) {
474 $callback = array( $this, 'passThrough' );
476 default: // 'paranoid'
477 $callback = array( $this, 'paranoidClean' );
484 * Create a new fatal error
486 function newFatal( $message /*, parameters...*/ ) {
487 $params = func_get_args();
488 array_unshift( $params, $this );
489 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
493 * Create a new good result
495 function newGood( $value = null ) {
496 return FileRepoStatus
::newGood( $this, $value );
500 * Delete files in the deleted directory if they are not referenced in the filearchive table
503 function cleanupDeletedBatch( $storageKeys ) {}
506 * Checks if there is a redirect named as $title
509 * @param Title $title Title of image
511 function checkRedirect( $title ) {
516 * Invalidates image redirect cache related to that image
519 * @param Title $title Title of image
521 function invalidateImageRedirect( $title ) {
524 function findBySha1( $hash ) {