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;
11 const OVERWRITE_SAME
= 4;
13 var $thumbScriptUrl, $transformVia404;
14 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
15 var $pathDisclosureProtection = 'paranoid';
18 * Factory functions for creating new files
19 * Override these in the base class
21 var $fileFactory = false, $oldFileFactory = false;
23 function __construct( $info ) {
25 $this->name
= $info['name'];
28 $this->initialCapital
= true; // by default
29 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
30 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
32 if ( isset( $info[$var] ) ) {
33 $this->$var = $info[$var];
36 $this->transformVia404
= !empty( $info['transformVia404'] );
40 * Determine if a string is an mwrepo:// URL
42 static function isVirtualUrl( $url ) {
43 return substr( $url, 0, 9 ) == 'mwrepo://';
47 * Create a new File object from the local repository
48 * @param mixed $title Title object or string
49 * @param mixed $time Time at which the image was uploaded.
50 * If this is specified, the returned object will be an
51 * instance of the repository's old file class instead of
52 * a current file. Repositories not supporting version
53 * control should return false if this parameter is set.
55 function newFile( $title, $time = false ) {
56 if ( !($title instanceof Title
) ) {
57 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
58 if ( !is_object( $title ) ) {
63 if ( $this->oldFileFactory
) {
64 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
69 return call_user_func( $this->fileFactory
, $title, $this );
74 * Find an instance of the named file created at the specified time
75 * Returns false if the file does not exist. Repositories not supporting
76 * version control should return false if the time is specified.
78 * @param mixed $title Title object or string
79 * @param mixed $time 14-character timestamp, or false for the current version
81 function findFile( $title, $time = false, $flags = 0 ) {
82 if ( !($title instanceof Title
) ) {
83 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
84 if ( !is_object( $title ) ) {
88 # First try the current version of the file to see if it precedes the timestamp
89 $img = $this->newFile( $title );
93 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
96 # Now try an old version of the file
97 if ( $time !== false ) {
98 $img = $this->newFile( $title, $time );
99 if ( $img->exists() ) {
100 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
102 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
108 $redir = $this->checkRedirect( $title );
109 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
110 $img = $this->newFile( $redir );
114 if( $img->exists() ) {
115 $img->redirectedFrom( $title->getText() );
123 * Get the URL of thumb.php
125 function getThumbScriptUrl() {
126 return $this->thumbScriptUrl
;
130 * Returns true if the repository can transform files via a 404 handler
132 function canTransformVia404() {
133 return $this->transformVia404
;
137 * Get the name of an image from its title object
139 function getNameFromTitle( $title ) {
140 global $wgCapitalLinks;
141 if ( $this->initialCapital
!= $wgCapitalLinks ) {
143 $name = $title->getUserCaseDBKey();
144 if ( $this->initialCapital
) {
145 $name = $wgContLang->ucfirst( $name );
148 $name = $title->getDBkey();
153 static function getHashPathForLevel( $name, $levels ) {
154 if ( $levels == 0 ) {
157 $hash = md5( $name );
159 for ( $i = 1; $i <= $levels; $i++
) {
160 $path .= substr( $hash, 0, $i ) . '/';
167 * Get the name of this repository, as specified by $info['name]' to the constructor
174 * Get the file description page base URL, or false if there isn't one.
177 function getDescBaseUrl() {
178 if ( is_null( $this->descBaseUrl
) ) {
179 if ( !is_null( $this->articleUrl
) ) {
180 $this->descBaseUrl
= str_replace( '$1',
181 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
182 } elseif ( !is_null( $this->scriptDirUrl
) ) {
183 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
184 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
186 $this->descBaseUrl
= false;
189 return $this->descBaseUrl
;
193 * Get the URL of an image description page. May return false if it is
194 * unknown or not applicable. In general this should only be called by the
195 * File class, since it may return invalid results for certain kinds of
196 * repositories. Use File::getDescriptionUrl() in user code.
198 * In particular, it uses the article paths as specified to the repository
199 * constructor, whereas local repositories use the local Title functions.
201 function getDescriptionUrl( $name ) {
202 $base = $this->getDescBaseUrl();
204 return $base . wfUrlencode( $name );
211 * Get the URL of the content-only fragment of the description page. For
212 * MediaWiki this means action=render. This should only be called by the
213 * repository's file class, since it may return invalid results. User code
214 * should use File::getDescriptionText().
216 function getDescriptionRenderUrl( $name ) {
217 if ( isset( $this->scriptDirUrl
) ) {
218 return $this->scriptDirUrl
. '/index.php?title=' .
219 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
222 $descBase = $this->getDescBaseUrl();
224 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
232 * Store a file to a given destination.
234 * @param string $srcPath Source path or virtual URL
235 * @param string $dstZone Destination zone
236 * @param string $dstRel Destination relative path
237 * @param integer $flags Bitwise combination of the following flags:
238 * self::DELETE_SOURCE Delete the source file after upload
239 * self::OVERWRITE Overwrite an existing destination file instead of failing
240 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
241 * same contents as the source
242 * @return FileRepoStatus
244 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
245 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
246 if ( $status->successCount
== 0 ) {
253 * Store a batch of files
255 * @param array $triplets (src,zone,dest) triplets as per store()
256 * @param integer $flags Flags as per store
258 abstract function storeBatch( $triplets, $flags = 0 );
261 * Pick a random name in the temp zone and store a file to it.
262 * Returns a FileRepoStatus object with the URL in the value.
264 * @param string $originalName The base name of the file as specified
265 * by the user. The file extension will be maintained.
266 * @param string $srcPath The current location of the file.
268 abstract function storeTemp( $originalName, $srcPath );
271 * Remove a temporary file or mark it for garbage collection
272 * @param string $virtualUrl The virtual URL returned by storeTemp
273 * @return boolean True on success, false on failure
276 function freeTemp( $virtualUrl ) {
281 * Copy or move a file either from the local filesystem or from an mwrepo://
282 * virtual URL, into this repository at the specified destination location.
284 * Returns a FileRepoStatus object. On success, the value contains "new" or
285 * "archived", to indicate whether the file was new with that name.
287 * @param string $srcPath The source path or URL
288 * @param string $dstRel The destination relative path
289 * @param string $archiveRel The relative path where the existing file is to
290 * be archived, if there is one. Relative to the public zone root.
291 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
292 * that the source file should be deleted if possible
294 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
295 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
296 if ( $status->successCount
== 0 ) {
299 if ( isset( $status->value
[0] ) ) {
300 $status->value
= $status->value
[0];
302 $status->value
= false;
308 * Publish a batch of files
309 * @param array $triplets (source,dest,archive) triplets as per publish()
310 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
311 * that the source files should be deleted if possible
313 abstract function publishBatch( $triplets, $flags = 0 );
316 * Move a group of files to the deletion archive.
318 * If no valid deletion archive is configured, this may either delete the
319 * file or throw an exception, depending on the preference of the repository.
321 * The overwrite policy is determined by the repository -- currently FSRepo
322 * assumes a naming scheme in the deleted zone based on content hash, as
323 * opposed to the public zone which is assumed to be unique.
325 * @param array $sourceDestPairs Array of source/destination pairs. Each element
326 * is a two-element array containing the source file path relative to the
327 * public root in the first element, and the archive file path relative
328 * to the deleted zone root in the second element.
329 * @return FileRepoStatus
331 abstract function deleteBatch( $sourceDestPairs );
334 * Move a file to the deletion archive.
335 * If no valid deletion archive exists, this may either delete the file
336 * or throw an exception, depending on the preference of the repository
337 * @param mixed $srcRel Relative path for the file to be deleted
338 * @param mixed $archiveRel Relative path for the archive location.
339 * Relative to a private archive directory.
340 * @return WikiError object (wikitext-formatted), or true for success
342 function delete( $srcRel, $archiveRel ) {
343 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
347 * Get properties of a file with a given virtual URL
348 * The virtual URL must refer to this repo
349 * Properties should ultimately be obtained via File::getPropsFromPath()
351 abstract function getFileProps( $virtualUrl );
354 * Call a callback function for every file in the repository
355 * May use either the database or the filesystem
358 function enumFiles( $callback ) {
359 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
363 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
365 function validateFilename( $filename ) {
366 if ( strval( $filename ) == '' ) {
369 if ( wfIsWindows() ) {
370 $filename = strtr( $filename, '\\', '/' );
373 * Use the same traversal protection as Title::secureAndSplit()
375 if ( strpos( $filename, '.' ) !== false &&
376 ( $filename === '.' ||
$filename === '..' ||
377 strpos( $filename, './' ) === 0 ||
378 strpos( $filename, '../' ) === 0 ||
379 strpos( $filename, '/./' ) !== false ||
380 strpos( $filename, '/../' ) !== false ) )
389 * Path disclosure protection functions
391 function paranoidClean( $param ) { return '[hidden]'; }
392 function passThrough( $param ) { return $param; }
395 * Get a callback function to use for cleaning error message parameters
397 function getErrorCleanupFunction() {
398 switch ( $this->pathDisclosureProtection
) {
400 $callback = array( $this, 'passThrough' );
402 default: // 'paranoid'
403 $callback = array( $this, 'paranoidClean' );
410 * Create a new fatal error
412 function newFatal( $message /*, parameters...*/ ) {
413 $params = func_get_args();
414 array_unshift( $params, $this );
415 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
419 * Create a new good result
421 function newGood( $value = null ) {
422 return FileRepoStatus
::newGood( $this, $value );
426 * Delete files in the deleted directory if they are not referenced in the filearchive table
429 function cleanupDeletedBatch( $storageKeys ) {}
432 * Checks if there is a redirect named as $title
435 * @param Title $title Title of image
437 function checkRedirect( $title ) {
442 * Invalidates image redirect cache related to that image
445 * @param Title $title Title of image
447 function invalidateImageRedirect( $title ) {