4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
7 abstract class FileRepo
{
8 const DELETE_SOURCE
= 1;
10 const OVERWRITE_SAME
= 4;
12 var $thumbScriptUrl, $transformVia404;
13 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
14 var $pathDisclosureProtection = 'paranoid';
17 * Factory functions for creating new files
18 * Override these in the base class
20 var $fileFactory = false, $oldFileFactory = false;
22 function __construct( $info ) {
24 $this->name
= $info['name'];
27 $this->initialCapital
= true; // by default
28 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
29 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
31 if ( isset( $info[$var] ) ) {
32 $this->$var = $info[$var];
35 $this->transformVia404
= !empty( $info['transformVia404'] );
39 * Determine if a string is an mwrepo:// URL
41 static function isVirtualUrl( $url ) {
42 return substr( $url, 0, 9 ) == 'mwrepo://';
46 * Create a new File object from the local repository
47 * @param mixed $title Title object or string
48 * @param mixed $time Time at which the image is supposed to have existed.
49 * If this is specified, the returned object will be an
50 * instance of the repository's old file class instead of
51 * a current file. Repositories not supporting version
52 * control should return false if this parameter is set.
54 function newFile( $title, $time = false ) {
55 if ( !($title instanceof Title
) ) {
56 $title = Title
::makeTitleSafe( NS_IMAGE
, $title );
57 if ( !is_object( $title ) ) {
62 if ( $this->oldFileFactory
) {
63 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
68 return call_user_func( $this->fileFactory
, $title, $this );
73 * Find an instance of the named file that existed at the specified time
74 * Returns false if the file did not exist. Repositories not supporting
75 * version control should return false if the time is specified.
77 * @param mixed $time 14-character timestamp, or false for the current version
79 function findFile( $title, $time = false ) {
80 # First try the current version of the file to see if it precedes the timestamp
81 $img = $this->newFile( $title );
85 if ( $img->exists() && ( !$time ||
$img->getTimestamp() <= $time ) ) {
88 # Now try an old version of the file
89 $img = $this->newFile( $title, $time );
90 if ( $img->exists() ) {
95 $redir = $this->checkRedirect( $title );
96 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
97 $img = $this->newFile( $redir );
101 if( $img->exists() ) {
102 $img->redirectedFrom( $title->getText() );
109 * Get the URL of thumb.php
111 function getThumbScriptUrl() {
112 return $this->thumbScriptUrl
;
116 * Returns true if the repository can transform files via a 404 handler
118 function canTransformVia404() {
119 return $this->transformVia404
;
123 * Get the name of an image from its title object
125 function getNameFromTitle( $title ) {
126 global $wgCapitalLinks;
127 if ( $this->initialCapital
!= $wgCapitalLinks ) {
129 $name = $title->getUserCaseDBKey();
130 if ( $this->initialCapital
) {
131 $name = $wgContLang->ucfirst( $name );
134 $name = $title->getDBkey();
139 static function getHashPathForLevel( $name, $levels ) {
140 if ( $levels == 0 ) {
143 $hash = md5( $name );
145 for ( $i = 1; $i <= $levels; $i++
) {
146 $path .= substr( $hash, 0, $i ) . '/';
153 * Get the name of this repository, as specified by $info['name]' to the constructor
160 * Get the file description page base URL, or false if there isn't one.
163 function getDescBaseUrl() {
164 if ( is_null( $this->descBaseUrl
) ) {
165 if ( !is_null( $this->articleUrl
) ) {
166 $this->descBaseUrl
= str_replace( '$1',
167 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
168 } elseif ( !is_null( $this->scriptDirUrl
) ) {
169 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
170 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE
) ) . ':';
172 $this->descBaseUrl
= false;
175 return $this->descBaseUrl
;
179 * Get the URL of an image description page. May return false if it is
180 * unknown or not applicable. In general this should only be called by the
181 * File class, since it may return invalid results for certain kinds of
182 * repositories. Use File::getDescriptionUrl() in user code.
184 * In particular, it uses the article paths as specified to the repository
185 * constructor, whereas local repositories use the local Title functions.
187 function getDescriptionUrl( $name ) {
188 $base = $this->getDescBaseUrl();
190 return $base . wfUrlencode( $name );
197 * Get the URL of the content-only fragment of the description page. For
198 * MediaWiki this means action=render. This should only be called by the
199 * repository's file class, since it may return invalid results. User code
200 * should use File::getDescriptionText().
202 function getDescriptionRenderUrl( $name ) {
203 if ( isset( $this->scriptDirUrl
) ) {
204 return $this->scriptDirUrl
. '/index.php?title=' .
205 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
208 $descBase = $this->getDescBaseUrl();
210 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
218 * Store a file to a given destination.
220 * @param string $srcPath Source path or virtual URL
221 * @param string $dstZone Destination zone
222 * @param string $dstRel Destination relative path
223 * @param integer $flags Bitwise combination of the following flags:
224 * self::DELETE_SOURCE Delete the source file after upload
225 * self::OVERWRITE Overwrite an existing destination file instead of failing
226 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
227 * same contents as the source
228 * @return FileRepoStatus
230 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
231 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
232 if ( $status->successCount
== 0 ) {
239 * Store a batch of files
241 * @param array $triplets (src,zone,dest) triplets as per store()
242 * @param integer $flags Flags as per store
244 abstract function storeBatch( $triplets, $flags = 0 );
247 * Pick a random name in the temp zone and store a file to it.
248 * Returns a FileRepoStatus object with the URL in the value.
250 * @param string $originalName The base name of the file as specified
251 * by the user. The file extension will be maintained.
252 * @param string $srcPath The current location of the file.
254 abstract function storeTemp( $originalName, $srcPath );
257 * Remove a temporary file or mark it for garbage collection
258 * @param string $virtualUrl The virtual URL returned by storeTemp
259 * @return boolean True on success, false on failure
262 function freeTemp( $virtualUrl ) {
267 * Copy or move a file either from the local filesystem or from an mwrepo://
268 * virtual URL, into this repository at the specified destination location.
270 * Returns a FileRepoStatus object. On success, the value contains "new" or
271 * "archived", to indicate whether the file was new with that name.
273 * @param string $srcPath The source path or URL
274 * @param string $dstRel The destination relative path
275 * @param string $archiveRel The relative path where the existing file is to
276 * be archived, if there is one. Relative to the public zone root.
277 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
278 * that the source file should be deleted if possible
280 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
281 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
282 if ( $status->successCount
== 0 ) {
285 if ( isset( $status->value
[0] ) ) {
286 $status->value
= $status->value
[0];
288 $status->value
= false;
294 * Publish a batch of files
295 * @param array $triplets (source,dest,archive) triplets as per publish()
296 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
297 * that the source files should be deleted if possible
299 abstract function publishBatch( $triplets, $flags = 0 );
302 * Move a group of files to the deletion archive.
304 * If no valid deletion archive is configured, this may either delete the
305 * file or throw an exception, depending on the preference of the repository.
307 * The overwrite policy is determined by the repository -- currently FSRepo
308 * assumes a naming scheme in the deleted zone based on content hash, as
309 * opposed to the public zone which is assumed to be unique.
311 * @param array $sourceDestPairs Array of source/destination pairs. Each element
312 * is a two-element array containing the source file path relative to the
313 * public root in the first element, and the archive file path relative
314 * to the deleted zone root in the second element.
315 * @return FileRepoStatus
317 abstract function deleteBatch( $sourceDestPairs );
320 * Move a file to the deletion archive.
321 * If no valid deletion archive exists, this may either delete the file
322 * or throw an exception, depending on the preference of the repository
323 * @param mixed $srcRel Relative path for the file to be deleted
324 * @param mixed $archiveRel Relative path for the archive location.
325 * Relative to a private archive directory.
326 * @return WikiError object (wikitext-formatted), or true for success
328 function delete( $srcRel, $archiveRel ) {
329 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
333 * Get properties of a file with a given virtual URL
334 * The virtual URL must refer to this repo
335 * Properties should ultimately be obtained via File::getPropsFromPath()
337 abstract function getFileProps( $virtualUrl );
340 * Call a callback function for every file in the repository
341 * May use either the database or the filesystem
344 function enumFiles( $callback ) {
345 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
349 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
351 function validateFilename( $filename ) {
352 if ( strval( $filename ) == '' ) {
355 if ( wfIsWindows() ) {
356 $filename = strtr( $filename, '\\', '/' );
359 * Use the same traversal protection as Title::secureAndSplit()
361 if ( strpos( $filename, '.' ) !== false &&
362 ( $filename === '.' ||
$filename === '..' ||
363 strpos( $filename, './' ) === 0 ||
364 strpos( $filename, '../' ) === 0 ||
365 strpos( $filename, '/./' ) !== false ||
366 strpos( $filename, '/../' ) !== false ) )
375 * Path disclosure protection functions
377 function paranoidClean( $param ) { return '[hidden]'; }
378 function passThrough( $param ) { return $param; }
381 * Get a callback function to use for cleaning error message parameters
383 function getErrorCleanupFunction() {
384 switch ( $this->pathDisclosureProtection
) {
386 $callback = array( $this, 'passThrough' );
388 default: // 'paranoid'
389 $callback = array( $this, 'paranoidClean' );
396 * Create a new fatal error
398 function newFatal( $message /*, parameters...*/ ) {
399 $params = func_get_args();
400 array_unshift( $params, $this );
401 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
405 * Create a new good result
407 function newGood( $value = null ) {
408 return FileRepoStatus
::newGood( $this, $value );
412 * Delete files in the deleted directory if they are not referenced in the filearchive table
415 function cleanupDeletedBatch( $storageKeys ) {}
418 * Checks if there is a redirect named as $title
421 * @param Title $title Title of image
423 function checkRedirect( $title ) {