* Fixed E_NOTICE..
[mediawiki.git] / includes / filerepo / FileRepo.php
blobcf6d65c2cec04bb682de7688f18c0885ce5a9a21
1 <?php
3 /**
4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
6 */
7 abstract class FileRepo {
8 const DELETE_SOURCE = 1;
9 const OVERWRITE = 2;
10 const OVERWRITE_SAME = 4;
12 var $thumbScriptUrl, $transformVia404;
13 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
14 var $pathDisclosureProtection = 'paranoid';
16 /**
17 * Factory functions for creating new files
18 * Override these in the base class
20 var $fileFactory = false, $oldFileFactory = false;
22 function __construct( $info ) {
23 // Required settings
24 $this->name = $info['name'];
26 // Optional settings
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'] );
38 /**
39 * Determine if a string is an mwrepo:// URL
41 static function isVirtualUrl( $url ) {
42 return substr( $url, 0, 9 ) == 'mwrepo://';
45 /**
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 ) ) {
58 return null;
61 if ( $time ) {
62 if ( $this->oldFileFactory ) {
63 return call_user_func( $this->oldFileFactory, $title, $this, $time );
64 } else {
65 return false;
67 } else {
68 return call_user_func( $this->fileFactory, $title, $this );
72 /**
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 );
82 if ( !$img ) {
83 return false;
85 if ( $img->exists() && ( !$time || $img->getTimestamp() <= $time ) ) {
86 return $img;
88 # Now try an old version of the file
89 $img = $this->newFile( $title, $time );
90 if ( $img->exists() ) {
91 return $img;
95 /**
96 * Get the URL of thumb.php
98 function getThumbScriptUrl() {
99 return $this->thumbScriptUrl;
103 * Returns true if the repository can transform files via a 404 handler
105 function canTransformVia404() {
106 return $this->transformVia404;
110 * Get the name of an image from its title object
112 function getNameFromTitle( $title ) {
113 global $wgCapitalLinks;
114 if ( $this->initialCapital != $wgCapitalLinks ) {
115 global $wgContLang;
116 $name = $title->getUserCaseDBKey();
117 if ( $this->initialCapital ) {
118 $name = $wgContLang->ucfirst( $name );
120 } else {
121 $name = $title->getDBkey();
123 return $name;
126 static function getHashPathForLevel( $name, $levels ) {
127 if ( $levels == 0 ) {
128 return '';
129 } else {
130 $hash = md5( $name );
131 $path = '';
132 for ( $i = 1; $i <= $levels; $i++ ) {
133 $path .= substr( $hash, 0, $i ) . '/';
135 return $path;
140 * Get the name of this repository, as specified by $info['name]' to the constructor
142 function getName() {
143 return $this->name;
147 * Get the file description page base URL, or false if there isn't one.
148 * @private
150 function getDescBaseUrl() {
151 if ( is_null( $this->descBaseUrl ) ) {
152 if ( !is_null( $this->articleUrl ) ) {
153 $this->descBaseUrl = str_replace( '$1',
154 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) ) . ':', $this->articleUrl );
155 } elseif ( !is_null( $this->scriptDirUrl ) ) {
156 $this->descBaseUrl = $this->scriptDirUrl . '/index.php?title=' .
157 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) ) . ':';
158 } else {
159 $this->descBaseUrl = false;
162 return $this->descBaseUrl;
166 * Get the URL of an image description page. May return false if it is
167 * unknown or not applicable. In general this should only be called by the
168 * File class, since it may return invalid results for certain kinds of
169 * repositories. Use File::getDescriptionUrl() in user code.
171 * In particular, it uses the article paths as specified to the repository
172 * constructor, whereas local repositories use the local Title functions.
174 function getDescriptionUrl( $name ) {
175 $base = $this->getDescBaseUrl();
176 if ( $base ) {
177 return $base . wfUrlencode( $name );
178 } else {
179 return false;
184 * Get the URL of the content-only fragment of the description page. For
185 * MediaWiki this means action=render. This should only be called by the
186 * repository's file class, since it may return invalid results. User code
187 * should use File::getDescriptionText().
189 function getDescriptionRenderUrl( $name ) {
190 if ( isset( $this->scriptDirUrl ) ) {
191 return $this->scriptDirUrl . '/index.php?title=' .
192 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) . ':' . $name ) .
193 '&action=render';
194 } else {
195 $descBase = $this->getDescBaseUrl();
196 if ( $descBase ) {
197 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
198 } else {
199 return false;
205 * Store a file to a given destination.
207 * @param string $srcPath Source path or virtual URL
208 * @param string $dstZone Destination zone
209 * @param string $dstRel Destination relative path
210 * @param integer $flags Bitwise combination of the following flags:
211 * self::DELETE_SOURCE Delete the source file after upload
212 * self::OVERWRITE Overwrite an existing destination file instead of failing
213 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
214 * same contents as the source
215 * @return FileRepoStatus
217 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
218 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
219 if ( $status->successCount == 0 ) {
220 $status->ok = false;
222 return $status;
226 * Store a batch of files
228 * @param array $triplets (src,zone,dest) triplets as per store()
229 * @param integer $flags Flags as per store
231 abstract function storeBatch( $triplets, $flags = 0 );
234 * Pick a random name in the temp zone and store a file to it.
235 * Returns a FileRepoStatus object with the URL in the value.
237 * @param string $originalName The base name of the file as specified
238 * by the user. The file extension will be maintained.
239 * @param string $srcPath The current location of the file.
241 abstract function storeTemp( $originalName, $srcPath );
244 * Remove a temporary file or mark it for garbage collection
245 * @param string $virtualUrl The virtual URL returned by storeTemp
246 * @return boolean True on success, false on failure
247 * STUB
249 function freeTemp( $virtualUrl ) {
250 return true;
254 * Copy or move a file either from the local filesystem or from an mwrepo://
255 * virtual URL, into this repository at the specified destination location.
257 * Returns a FileRepoStatus object. On success, the value contains "new" or
258 * "archived", to indicate whether the file was new with that name.
260 * @param string $srcPath The source path or URL
261 * @param string $dstRel The destination relative path
262 * @param string $archiveRel The relative path where the existing file is to
263 * be archived, if there is one. Relative to the public zone root.
264 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
265 * that the source file should be deleted if possible
267 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
268 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
269 if ( $status->successCount == 0 ) {
270 $status->ok = false;
272 if ( isset( $status->value[0] ) ) {
273 $status->value = $status->value[0];
274 } else {
275 $status->value = false;
277 return $status;
281 * Publish a batch of files
282 * @param array $triplets (source,dest,archive) triplets as per publish()
283 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
284 * that the source files should be deleted if possible
286 abstract function publishBatch( $triplets, $flags = 0 );
289 * Move a group of files to the deletion archive.
291 * If no valid deletion archive is configured, this may either delete the
292 * file or throw an exception, depending on the preference of the repository.
294 * The overwrite policy is determined by the repository -- currently FSRepo
295 * assumes a naming scheme in the deleted zone based on content hash, as
296 * opposed to the public zone which is assumed to be unique.
298 * @param array $sourceDestPairs Array of source/destination pairs. Each element
299 * is a two-element array containing the source file path relative to the
300 * public root in the first element, and the archive file path relative
301 * to the deleted zone root in the second element.
302 * @return FileRepoStatus
304 abstract function deleteBatch( $sourceDestPairs );
307 * Move a file to the deletion archive.
308 * If no valid deletion archive exists, this may either delete the file
309 * or throw an exception, depending on the preference of the repository
310 * @param mixed $srcRel Relative path for the file to be deleted
311 * @param mixed $archiveRel Relative path for the archive location.
312 * Relative to a private archive directory.
313 * @return WikiError object (wikitext-formatted), or true for success
315 function delete( $srcRel, $archiveRel ) {
316 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
320 * Get properties of a file with a given virtual URL
321 * The virtual URL must refer to this repo
322 * Properties should ultimately be obtained via File::getPropsFromPath()
324 abstract function getFileProps( $virtualUrl );
327 * Call a callback function for every file in the repository
328 * May use either the database or the filesystem
329 * STUB
331 function enumFiles( $callback ) {
332 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
336 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
338 function validateFilename( $filename ) {
339 if ( strval( $filename ) == '' ) {
340 return false;
342 if ( wfIsWindows() ) {
343 $filename = strtr( $filename, '\\', '/' );
346 * Use the same traversal protection as Title::secureAndSplit()
348 if ( strpos( $filename, '.' ) !== false &&
349 ( $filename === '.' || $filename === '..' ||
350 strpos( $filename, './' ) === 0 ||
351 strpos( $filename, '../' ) === 0 ||
352 strpos( $filename, '/./' ) !== false ||
353 strpos( $filename, '/../' ) !== false ) )
355 return false;
356 } else {
357 return true;
361 /**#@+
362 * Path disclosure protection functions
364 function paranoidClean( $param ) { return '[hidden]'; }
365 function passThrough( $param ) { return $param; }
368 * Get a callback function to use for cleaning error message parameters
370 function getErrorCleanupFunction() {
371 switch ( $this->pathDisclosureProtection ) {
372 case 'none':
373 $callback = array( $this, 'passThrough' );
374 break;
375 default: // 'paranoid'
376 $callback = array( $this, 'paranoidClean' );
378 return $callback;
380 /**#@-*/
383 * Create a new fatal error
385 function newFatal( $message /*, parameters...*/ ) {
386 $params = func_get_args();
387 array_unshift( $params, $this );
388 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
392 * Create a new good result
394 function newGood( $value = null ) {
395 return FileRepoStatus::newGood( $this, $value );
399 * Delete files in the deleted directory if they are not referenced in the filearchive table
400 * STUB
402 function cleanupDeletedBatch( $storageKeys ) {}