4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
7 abstract class FileRepo
{
8 const DELETE_SOURCE
= 1;
9 const FIND_PRIVATE
= 1;
10 const FIND_IGNORE_REDIRECT
= 2;
12 const OVERWRITE_SAME
= 4;
14 var $thumbScriptUrl, $transformVia404;
15 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
16 var $pathDisclosureProtection = 'paranoid';
19 * Factory functions for creating new files
20 * Override these in the base class
22 var $fileFactory = false, $oldFileFactory = false;
24 function __construct( $info ) {
26 $this->name
= $info['name'];
29 $this->initialCapital
= true; // by default
30 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
31 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
33 if ( isset( $info[$var] ) ) {
34 $this->$var = $info[$var];
37 $this->transformVia404
= !empty( $info['transformVia404'] );
41 * Determine if a string is an mwrepo:// URL
43 static function isVirtualUrl( $url ) {
44 return substr( $url, 0, 9 ) == 'mwrepo://';
48 * Create a new File object from the local repository
49 * @param mixed $title Title object or string
50 * @param mixed $time Time at which the image was uploaded.
51 * If this is specified, the returned object will be an
52 * instance of the repository's old file class instead of
53 * a current file. Repositories not supporting version
54 * control should return false if this parameter is set.
56 function newFile( $title, $time = false ) {
57 if ( !($title instanceof Title
) ) {
58 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
59 if ( !is_object( $title ) ) {
64 if ( $this->oldFileFactory
) {
65 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
70 return call_user_func( $this->fileFactory
, $title, $this );
75 * Find an instance of the named file created at the specified time
76 * Returns false if the file does not exist. Repositories not supporting
77 * version control should return false if the time is specified.
79 * @param mixed $title Title object or string
80 * @param mixed $time 14-character timestamp, or false for the current version
82 function findFile( $title, $time = false, $flags = 0 ) {
83 if ( !($title instanceof Title
) ) {
84 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
85 if ( !is_object( $title ) ) {
89 # First try the current version of the file to see if it precedes the timestamp
90 $img = $this->newFile( $title );
94 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
97 # Now try an old version of the file
98 if ( $time !== false ) {
99 $img = $this->newFile( $title, $time );
100 if ( $img->exists() ) {
101 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
103 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
110 if ( $flags & FileRepo
::FIND_IGNORE_REDIRECT
) return false;
111 $redir = $this->checkRedirect( $title );
112 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
113 $img = $this->newFile( $redir );
117 if( $img->exists() ) {
118 $img->redirectedFrom( $title->getText() );
126 * Get the URL of thumb.php
128 function getThumbScriptUrl() {
129 return $this->thumbScriptUrl
;
133 * Returns true if the repository can transform files via a 404 handler
135 function canTransformVia404() {
136 return $this->transformVia404
;
140 * Get the name of an image from its title object
142 function getNameFromTitle( $title ) {
143 global $wgCapitalLinks;
144 if ( $this->initialCapital
!= $wgCapitalLinks ) {
146 $name = $title->getUserCaseDBKey();
147 if ( $this->initialCapital
) {
148 $name = $wgContLang->ucfirst( $name );
151 $name = $title->getDBkey();
156 static function getHashPathForLevel( $name, $levels ) {
157 if ( $levels == 0 ) {
160 $hash = md5( $name );
162 for ( $i = 1; $i <= $levels; $i++
) {
163 $path .= substr( $hash, 0, $i ) . '/';
170 * Get the name of this repository, as specified by $info['name]' to the constructor
177 * Get the file description page base URL, or false if there isn't one.
180 function getDescBaseUrl() {
181 if ( is_null( $this->descBaseUrl
) ) {
182 if ( !is_null( $this->articleUrl
) ) {
183 $this->descBaseUrl
= str_replace( '$1',
184 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
185 } elseif ( !is_null( $this->scriptDirUrl
) ) {
186 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
187 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
189 $this->descBaseUrl
= false;
192 return $this->descBaseUrl
;
196 * Get the URL of an image description page. May return false if it is
197 * unknown or not applicable. In general this should only be called by the
198 * File class, since it may return invalid results for certain kinds of
199 * repositories. Use File::getDescriptionUrl() in user code.
201 * In particular, it uses the article paths as specified to the repository
202 * constructor, whereas local repositories use the local Title functions.
204 function getDescriptionUrl( $name ) {
205 $base = $this->getDescBaseUrl();
207 return $base . wfUrlencode( $name );
214 * Get the URL of the content-only fragment of the description page. For
215 * MediaWiki this means action=render. This should only be called by the
216 * repository's file class, since it may return invalid results. User code
217 * should use File::getDescriptionText().
219 function getDescriptionRenderUrl( $name ) {
220 if ( isset( $this->scriptDirUrl
) ) {
221 return $this->scriptDirUrl
. '/index.php?title=' .
222 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
225 $descBase = $this->getDescBaseUrl();
227 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
235 * Store a file to a given destination.
237 * @param string $srcPath Source path or virtual URL
238 * @param string $dstZone Destination zone
239 * @param string $dstRel Destination relative path
240 * @param integer $flags Bitwise combination of the following flags:
241 * self::DELETE_SOURCE Delete the source file after upload
242 * self::OVERWRITE Overwrite an existing destination file instead of failing
243 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
244 * same contents as the source
245 * @return FileRepoStatus
247 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
248 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
249 if ( $status->successCount
== 0 ) {
256 * Store a batch of files
258 * @param array $triplets (src,zone,dest) triplets as per store()
259 * @param integer $flags Flags as per store
261 abstract function storeBatch( $triplets, $flags = 0 );
264 * Pick a random name in the temp zone and store a file to it.
265 * Returns a FileRepoStatus object with the URL in the value.
267 * @param string $originalName The base name of the file as specified
268 * by the user. The file extension will be maintained.
269 * @param string $srcPath The current location of the file.
271 abstract function storeTemp( $originalName, $srcPath );
274 * Remove a temporary file or mark it for garbage collection
275 * @param string $virtualUrl The virtual URL returned by storeTemp
276 * @return boolean True on success, false on failure
279 function freeTemp( $virtualUrl ) {
284 * Copy or move a file either from the local filesystem or from an mwrepo://
285 * virtual URL, into this repository at the specified destination location.
287 * Returns a FileRepoStatus object. On success, the value contains "new" or
288 * "archived", to indicate whether the file was new with that name.
290 * @param string $srcPath The source path or URL
291 * @param string $dstRel The destination relative path
292 * @param string $archiveRel The relative path where the existing file is to
293 * be archived, if there is one. Relative to the public zone root.
294 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
295 * that the source file should be deleted if possible
297 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
298 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
299 if ( $status->successCount
== 0 ) {
302 if ( isset( $status->value
[0] ) ) {
303 $status->value
= $status->value
[0];
305 $status->value
= false;
311 * Publish a batch of files
312 * @param array $triplets (source,dest,archive) triplets as per publish()
313 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
314 * that the source files should be deleted if possible
316 abstract function publishBatch( $triplets, $flags = 0 );
319 * Move a group of files to the deletion archive.
321 * If no valid deletion archive is configured, this may either delete the
322 * file or throw an exception, depending on the preference of the repository.
324 * The overwrite policy is determined by the repository -- currently FSRepo
325 * assumes a naming scheme in the deleted zone based on content hash, as
326 * opposed to the public zone which is assumed to be unique.
328 * @param array $sourceDestPairs Array of source/destination pairs. Each element
329 * is a two-element array containing the source file path relative to the
330 * public root in the first element, and the archive file path relative
331 * to the deleted zone root in the second element.
332 * @return FileRepoStatus
334 abstract function deleteBatch( $sourceDestPairs );
337 * Move a file to the deletion archive.
338 * If no valid deletion archive exists, this may either delete the file
339 * or throw an exception, depending on the preference of the repository
340 * @param mixed $srcRel Relative path for the file to be deleted
341 * @param mixed $archiveRel Relative path for the archive location.
342 * Relative to a private archive directory.
343 * @return WikiError object (wikitext-formatted), or true for success
345 function delete( $srcRel, $archiveRel ) {
346 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
350 * Get properties of a file with a given virtual URL
351 * The virtual URL must refer to this repo
352 * Properties should ultimately be obtained via File::getPropsFromPath()
354 abstract function getFileProps( $virtualUrl );
357 * Call a callback function for every file in the repository
358 * May use either the database or the filesystem
361 function enumFiles( $callback ) {
362 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
366 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
368 function validateFilename( $filename ) {
369 if ( strval( $filename ) == '' ) {
372 if ( wfIsWindows() ) {
373 $filename = strtr( $filename, '\\', '/' );
376 * Use the same traversal protection as Title::secureAndSplit()
378 if ( strpos( $filename, '.' ) !== false &&
379 ( $filename === '.' ||
$filename === '..' ||
380 strpos( $filename, './' ) === 0 ||
381 strpos( $filename, '../' ) === 0 ||
382 strpos( $filename, '/./' ) !== false ||
383 strpos( $filename, '/../' ) !== false ) )
392 * Path disclosure protection functions
394 function paranoidClean( $param ) { return '[hidden]'; }
395 function passThrough( $param ) { return $param; }
398 * Get a callback function to use for cleaning error message parameters
400 function getErrorCleanupFunction() {
401 switch ( $this->pathDisclosureProtection
) {
403 $callback = array( $this, 'passThrough' );
405 default: // 'paranoid'
406 $callback = array( $this, 'paranoidClean' );
413 * Create a new fatal error
415 function newFatal( $message /*, parameters...*/ ) {
416 $params = func_get_args();
417 array_unshift( $params, $this );
418 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
422 * Create a new good result
424 function newGood( $value = null ) {
425 return FileRepoStatus
::newGood( $this, $value );
429 * Delete files in the deleted directory if they are not referenced in the filearchive table
432 function cleanupDeletedBatch( $storageKeys ) {}
435 * Checks if there is a redirect named as $title
438 * @param Title $title Title of image
440 function checkRedirect( $title ) {
445 * Invalidates image redirect cache related to that image
448 * @param Title $title Title of image
450 function invalidateImageRedirect( $title ) {