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 is supposed to have existed.
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 did not exist. Repositories not supporting
76 * version control should return false if the time is specified.
78 * @param mixed $time 14-character timestamp, or false for the current version
80 function findFile( $title, $time = false, $flags = 0 ) {
81 # First try the current version of the file to see if it precedes the timestamp
82 $img = $this->newFile( $title );
86 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
89 # Now try an old version of the file
90 $img = $this->newFile( $title, $time );
91 if ( $img->exists() ) {
92 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
94 } else if ( ($flags & FileRepo
::FIND_PRIVATE
) && $img->userCan(File
::DELETED_FILE
) ) {
99 $redir = $this->checkRedirect( $title );
100 if( $redir && $redir->getNamespace() == NS_IMAGE
) {
101 $img = $this->newFile( $redir );
105 if( $img->exists() ) {
106 $img->redirectedFrom( $title->getText() );
114 * Get the URL of thumb.php
116 function getThumbScriptUrl() {
117 return $this->thumbScriptUrl
;
121 * Returns true if the repository can transform files via a 404 handler
123 function canTransformVia404() {
124 return $this->transformVia404
;
128 * Get the name of an image from its title object
130 function getNameFromTitle( $title ) {
131 global $wgCapitalLinks;
132 if ( $this->initialCapital
!= $wgCapitalLinks ) {
134 $name = $title->getUserCaseDBKey();
135 if ( $this->initialCapital
) {
136 $name = $wgContLang->ucfirst( $name );
139 $name = $title->getDBkey();
144 static function getHashPathForLevel( $name, $levels ) {
145 if ( $levels == 0 ) {
148 $hash = md5( $name );
150 for ( $i = 1; $i <= $levels; $i++
) {
151 $path .= substr( $hash, 0, $i ) . '/';
158 * Get the name of this repository, as specified by $info['name]' to the constructor
165 * Get the file description page base URL, or false if there isn't one.
168 function getDescBaseUrl() {
169 if ( is_null( $this->descBaseUrl
) ) {
170 if ( !is_null( $this->articleUrl
) ) {
171 $this->descBaseUrl
= str_replace( '$1',
172 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':', $this->articleUrl
);
173 } elseif ( !is_null( $this->scriptDirUrl
) ) {
174 $this->descBaseUrl
= $this->scriptDirUrl
. '/index.php?title=' .
175 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) ) . ':';
177 $this->descBaseUrl
= false;
180 return $this->descBaseUrl
;
184 * Get the URL of an image description page. May return false if it is
185 * unknown or not applicable. In general this should only be called by the
186 * File class, since it may return invalid results for certain kinds of
187 * repositories. Use File::getDescriptionUrl() in user code.
189 * In particular, it uses the article paths as specified to the repository
190 * constructor, whereas local repositories use the local Title functions.
192 function getDescriptionUrl( $name ) {
193 $base = $this->getDescBaseUrl();
195 return $base . wfUrlencode( $name );
202 * Get the URL of the content-only fragment of the description page. For
203 * MediaWiki this means action=render. This should only be called by the
204 * repository's file class, since it may return invalid results. User code
205 * should use File::getDescriptionText().
207 function getDescriptionRenderUrl( $name ) {
208 if ( isset( $this->scriptDirUrl
) ) {
209 return $this->scriptDirUrl
. '/index.php?title=' .
210 wfUrlencode( MWNamespace
::getCanonicalName( NS_IMAGE
) . ':' . $name ) .
213 $descBase = $this->getDescBaseUrl();
215 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
223 * Store a file to a given destination.
225 * @param string $srcPath Source path or virtual URL
226 * @param string $dstZone Destination zone
227 * @param string $dstRel Destination relative path
228 * @param integer $flags Bitwise combination of the following flags:
229 * self::DELETE_SOURCE Delete the source file after upload
230 * self::OVERWRITE Overwrite an existing destination file instead of failing
231 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
232 * same contents as the source
233 * @return FileRepoStatus
235 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
236 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
237 if ( $status->successCount
== 0 ) {
244 * Store a batch of files
246 * @param array $triplets (src,zone,dest) triplets as per store()
247 * @param integer $flags Flags as per store
249 abstract function storeBatch( $triplets, $flags = 0 );
252 * Pick a random name in the temp zone and store a file to it.
253 * Returns a FileRepoStatus object with the URL in the value.
255 * @param string $originalName The base name of the file as specified
256 * by the user. The file extension will be maintained.
257 * @param string $srcPath The current location of the file.
259 abstract function storeTemp( $originalName, $srcPath );
262 * Remove a temporary file or mark it for garbage collection
263 * @param string $virtualUrl The virtual URL returned by storeTemp
264 * @return boolean True on success, false on failure
267 function freeTemp( $virtualUrl ) {
272 * Copy or move a file either from the local filesystem or from an mwrepo://
273 * virtual URL, into this repository at the specified destination location.
275 * Returns a FileRepoStatus object. On success, the value contains "new" or
276 * "archived", to indicate whether the file was new with that name.
278 * @param string $srcPath The source path or URL
279 * @param string $dstRel The destination relative path
280 * @param string $archiveRel The relative path where the existing file is to
281 * be archived, if there is one. Relative to the public zone root.
282 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
283 * that the source file should be deleted if possible
285 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
286 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
287 if ( $status->successCount
== 0 ) {
290 if ( isset( $status->value
[0] ) ) {
291 $status->value
= $status->value
[0];
293 $status->value
= false;
299 * Publish a batch of files
300 * @param array $triplets (source,dest,archive) triplets as per publish()
301 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
302 * that the source files should be deleted if possible
304 abstract function publishBatch( $triplets, $flags = 0 );
307 * Move a group of files to the deletion archive.
309 * If no valid deletion archive is configured, this may either delete the
310 * file or throw an exception, depending on the preference of the repository.
312 * The overwrite policy is determined by the repository -- currently FSRepo
313 * assumes a naming scheme in the deleted zone based on content hash, as
314 * opposed to the public zone which is assumed to be unique.
316 * @param array $sourceDestPairs Array of source/destination pairs. Each element
317 * is a two-element array containing the source file path relative to the
318 * public root in the first element, and the archive file path relative
319 * to the deleted zone root in the second element.
320 * @return FileRepoStatus
322 abstract function deleteBatch( $sourceDestPairs );
325 * Move a file to the deletion archive.
326 * If no valid deletion archive exists, this may either delete the file
327 * or throw an exception, depending on the preference of the repository
328 * @param mixed $srcRel Relative path for the file to be deleted
329 * @param mixed $archiveRel Relative path for the archive location.
330 * Relative to a private archive directory.
331 * @return WikiError object (wikitext-formatted), or true for success
333 function delete( $srcRel, $archiveRel ) {
334 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
338 * Get properties of a file with a given virtual URL
339 * The virtual URL must refer to this repo
340 * Properties should ultimately be obtained via File::getPropsFromPath()
342 abstract function getFileProps( $virtualUrl );
345 * Call a callback function for every file in the repository
346 * May use either the database or the filesystem
349 function enumFiles( $callback ) {
350 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
354 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
356 function validateFilename( $filename ) {
357 if ( strval( $filename ) == '' ) {
360 if ( wfIsWindows() ) {
361 $filename = strtr( $filename, '\\', '/' );
364 * Use the same traversal protection as Title::secureAndSplit()
366 if ( strpos( $filename, '.' ) !== false &&
367 ( $filename === '.' ||
$filename === '..' ||
368 strpos( $filename, './' ) === 0 ||
369 strpos( $filename, '../' ) === 0 ||
370 strpos( $filename, '/./' ) !== false ||
371 strpos( $filename, '/../' ) !== false ) )
380 * Path disclosure protection functions
382 function paranoidClean( $param ) { return '[hidden]'; }
383 function passThrough( $param ) { return $param; }
386 * Get a callback function to use for cleaning error message parameters
388 function getErrorCleanupFunction() {
389 switch ( $this->pathDisclosureProtection
) {
391 $callback = array( $this, 'passThrough' );
393 default: // 'paranoid'
394 $callback = array( $this, 'paranoidClean' );
401 * Create a new fatal error
403 function newFatal( $message /*, parameters...*/ ) {
404 $params = func_get_args();
405 array_unshift( $params, $this );
406 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
410 * Create a new good result
412 function newGood( $value = null ) {
413 return FileRepoStatus
::newGood( $this, $value );
417 * Delete files in the deleted directory if they are not referenced in the filearchive table
420 function cleanupDeletedBatch( $storageKeys ) {}
423 * Checks if there is a redirect named as $title
426 * @param Title $title Title of image
428 function checkRedirect( $title ) {