bf06aefee83d232bf1ccce6131f902aaf3d1af89
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;
23 var $fileFactoryKey = false, $oldFileFactoryKey = false;
25 function __construct( $info ) {
27 $this->name
= $info['name'];
30 $this->initialCapital
= true; // by default
31 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
32 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
34 if ( isset( $info[$var] ) ) {
35 $this->$var = $info[$var];
38 $this->transformVia404
= !empty( $info['transformVia404'] );
42 * Determine if a string is an mwrepo:// URL
44 static function isVirtualUrl( $url ) {
45 return substr( $url, 0, 9 ) == 'mwrepo://';
49 * Create a new File object from the local repository
50 * @param mixed $title Title object or string
51 * @param mixed $time Time at which the image was uploaded.
52 * If this is specified, the returned object will be an
53 * instance of the repository's old file class instead of
54 * a current file. Repositories not supporting version
55 * control should return false if this parameter is set.
57 function newFile( $title, $time = false ) {
58 if ( !($title instanceof Title
) ) {
59 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
60 if ( !is_object( $title ) ) {
65 if ( $this->oldFileFactory
) {
66 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
71 return call_user_func( $this->fileFactory
, $title, $this );
76 * Find an instance of the named file created at the specified time
77 * Returns false if the file does not exist. Repositories not supporting
78 * version control should return false if the time is specified.
80 * @param mixed $title Title object or string
81 * @param mixed $time 14-character timestamp, or false for the current version
83 function findFile( $title, $time = false, $flags = 0 ) {
84 if ( !($title instanceof Title
) ) {
85 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
86 if ( !is_object( $title ) ) {
90 # First try the current version of the file to see if it precedes the timestamp
91 $img = $this->newFile( $title );
95 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
98 # Now try an old version of the file
99 if ( $time !== false ) {
100 $img = $this->newFile( $title, $time );
101 if ( $img->exists() ) {
102 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
104 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
111 if ( $flags & FileRepo
::FIND_IGNORE_REDIRECT
) {
114 $redir = $this->checkRedirect( $title );
115 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
116 $img = $this->newFile( $redir );
120 if( $img->exists() ) {
121 $img->redirectedFrom( $title->getDBkey() );
129 * Find many files at once
131 function findFiles( &$titles, $time = false, $flags ) {
133 foreach ( $titles as $index => $title ) {
134 $file = $this->findFile( $title );
136 $result[$file->getTitle()->getDBkey()] = $file;
137 unset( $titles[$index] );
144 * Create a new File object from the local repository
145 * @param mixed $sha1 SHA-1 key
146 * @param mixed $time Time at which the image was uploaded.
147 * If this is specified, the returned object will be an
148 * instance of the repository's old file class instead of
149 * a current file. Repositories not supporting version
150 * control should return false if this parameter is set.
152 function newFileFromKey( $sha1, $time = false ) {
154 if ( $this->oldFileFactoryKey
) {
155 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
160 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
165 * Find an instance of the file with this key, created at the specified time
166 * Returns false if the file does not exist. Repositories not supporting
167 * version control should return false if the time is specified.
169 * @param string $sha1 string
170 * @param mixed $time 14-character timestamp, or false for the current version
172 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
173 # First try the current version of the file to see if it precedes the timestamp
174 $img = $this->newFileFromKey( $sha1 );
178 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
181 # Now try an old version of the file
182 if ( $time !== false ) {
183 $img = $this->newFileFromKey( $sha1, $time );
184 if ( $img->exists() ) {
185 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
187 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
196 * Get the URL of thumb.php
198 function getThumbScriptUrl() {
199 return $this->thumbScriptUrl
;
203 * Returns true if the repository can transform files via a 404 handler
205 function canTransformVia404() {
206 return $this->transformVia404
;
210 * Get the name of an image from its title object
212 function getNameFromTitle( $title ) {
213 global $wgCapitalLinks;
214 if ( $this->initialCapital
!= $wgCapitalLinks ) {
216 $name = $title->getUserCaseDBKey();
217 if ( $this->initialCapital
) {
218 $name = $wgContLang->ucfirst( $name );
221 $name = $title->getDBkey();
226 static function getHashPathForLevel( $name, $levels ) {
227 if ( $levels == 0 ) {
230 $hash = md5( $name );
232 for ( $i = 1; $i <= $levels; $i++
) {
233 $path .= substr( $hash, 0, $i ) . '/';
240 * Get the name of this repository, as specified by $info['name]' to the constructor
247 * Get the file description page base URL, or false if there isn't one.
250 function getDescBaseUrl() {
251 if ( is_null( $this->descBaseUrl
) ) {
252 if ( !is_null( $this->articleUrl
) ) {
253 $this->descBaseUrl
= str_replace( '$1',
254 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
255 } elseif ( !is_null( $this->scriptDirUrl
) ) {
256 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
257 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
259 $this->descBaseUrl
= false;
262 return $this->descBaseUrl
;
266 * Get the URL of an image description page. May return false if it is
267 * unknown or not applicable. In general this should only be called by the
268 * File class, since it may return invalid results for certain kinds of
269 * repositories. Use File::getDescriptionUrl() in user code.
271 * In particular, it uses the article paths as specified to the repository
272 * constructor, whereas local repositories use the local Title functions.
274 function getDescriptionUrl( $name ) {
275 $base = $this->getDescBaseUrl();
277 return $base . wfUrlencode( $name );
284 * Get the URL of the content-only fragment of the description page. For
285 * MediaWiki this means action=render. This should only be called by the
286 * repository's file class, since it may return invalid results. User code
287 * should use File::getDescriptionText().
289 function getDescriptionRenderUrl( $name ) {
290 if ( isset( $this->scriptDirUrl
) ) {
291 return $this->scriptDirUrl
. '/index.php?title=' .
292 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
295 $descBase = $this->getDescBaseUrl();
297 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
305 * Store a file to a given destination.
307 * @param string $srcPath Source path or virtual URL
308 * @param string $dstZone Destination zone
309 * @param string $dstRel Destination relative path
310 * @param integer $flags Bitwise combination of the following flags:
311 * self::DELETE_SOURCE Delete the source file after upload
312 * self::OVERWRITE Overwrite an existing destination file instead of failing
313 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
314 * same contents as the source
315 * @return FileRepoStatus
317 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
318 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
319 if ( $status->successCount
== 0 ) {
326 * Store a batch of files
328 * @param array $triplets (src,zone,dest) triplets as per store()
329 * @param integer $flags Flags as per store
331 abstract function storeBatch( $triplets, $flags = 0 );
334 * Pick a random name in the temp zone and store a file to it.
335 * Returns a FileRepoStatus object with the URL in the value.
337 * @param string $originalName The base name of the file as specified
338 * by the user. The file extension will be maintained.
339 * @param string $srcPath The current location of the file.
341 abstract function storeTemp( $originalName, $srcPath );
344 * Remove a temporary file or mark it for garbage collection
345 * @param string $virtualUrl The virtual URL returned by storeTemp
346 * @return boolean True on success, false on failure
349 function freeTemp( $virtualUrl ) {
354 * Copy or move a file either from the local filesystem or from an mwrepo://
355 * virtual URL, into this repository at the specified destination location.
357 * Returns a FileRepoStatus object. On success, the value contains "new" or
358 * "archived", to indicate whether the file was new with that name.
360 * @param string $srcPath The source path or URL
361 * @param string $dstRel The destination relative path
362 * @param string $archiveRel The relative path where the existing file is to
363 * be archived, if there is one. Relative to the public zone root.
364 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
365 * that the source file should be deleted if possible
367 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
368 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
369 if ( $status->successCount
== 0 ) {
372 if ( isset( $status->value
[0] ) ) {
373 $status->value
= $status->value
[0];
375 $status->value
= false;
381 * Publish a batch of files
382 * @param array $triplets (source,dest,archive) triplets as per publish()
383 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
384 * that the source files should be deleted if possible
386 abstract function publishBatch( $triplets, $flags = 0 );
389 * Move a group of files to the deletion archive.
391 * If no valid deletion archive is configured, this may either delete the
392 * file or throw an exception, depending on the preference of the repository.
394 * The overwrite policy is determined by the repository -- currently FSRepo
395 * assumes a naming scheme in the deleted zone based on content hash, as
396 * opposed to the public zone which is assumed to be unique.
398 * @param array $sourceDestPairs Array of source/destination pairs. Each element
399 * is a two-element array containing the source file path relative to the
400 * public root in the first element, and the archive file path relative
401 * to the deleted zone root in the second element.
402 * @return FileRepoStatus
404 abstract function deleteBatch( $sourceDestPairs );
407 * Move a file to the deletion archive.
408 * If no valid deletion archive exists, this may either delete the file
409 * or throw an exception, depending on the preference of the repository
410 * @param mixed $srcRel Relative path for the file to be deleted
411 * @param mixed $archiveRel Relative path for the archive location.
412 * Relative to a private archive directory.
413 * @return WikiError object (wikitext-formatted), or true for success
415 function delete( $srcRel, $archiveRel ) {
416 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
420 * Get properties of a file with a given virtual URL
421 * The virtual URL must refer to this repo
422 * Properties should ultimately be obtained via File::getPropsFromPath()
424 abstract function getFileProps( $virtualUrl );
427 * Call a callback function for every file in the repository
428 * May use either the database or the filesystem
431 function enumFiles( $callback ) {
432 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
436 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
438 function validateFilename( $filename ) {
439 if ( strval( $filename ) == '' ) {
442 if ( wfIsWindows() ) {
443 $filename = strtr( $filename, '\\', '/' );
446 * Use the same traversal protection as Title::secureAndSplit()
448 if ( strpos( $filename, '.' ) !== false &&
449 ( $filename === '.' ||
$filename === '..' ||
450 strpos( $filename, './' ) === 0 ||
451 strpos( $filename, '../' ) === 0 ||
452 strpos( $filename, '/./' ) !== false ||
453 strpos( $filename, '/../' ) !== false ) )
462 * Path disclosure protection functions
464 function paranoidClean( $param ) { return '[hidden]'; }
465 function passThrough( $param ) { return $param; }
468 * Get a callback function to use for cleaning error message parameters
470 function getErrorCleanupFunction() {
471 switch ( $this->pathDisclosureProtection
) {
473 $callback = array( $this, 'passThrough' );
475 default: // 'paranoid'
476 $callback = array( $this, 'paranoidClean' );
483 * Create a new fatal error
485 function newFatal( $message /*, parameters...*/ ) {
486 $params = func_get_args();
487 array_unshift( $params, $this );
488 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
492 * Create a new good result
494 function newGood( $value = null ) {
495 return FileRepoStatus
::newGood( $this, $value );
499 * Delete files in the deleted directory if they are not referenced in the filearchive table
502 function cleanupDeletedBatch( $storageKeys ) {}
505 * Checks if there is a redirect named as $title
508 * @param Title $title Title of image
510 function checkRedirect( $title ) {
515 * Invalidates image redirect cache related to that image
518 * @param Title $title Title of image
520 function invalidateImageRedirect( $title ) {
523 function findBySha1( $hash ) {