Don't check for existence twice for non-existent files when no time is specified.
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2
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 FIND_PRIVATE = 1;
10 const OVERWRITE = 2;
11 const OVERWRITE_SAME = 4;
12
13 var $thumbScriptUrl, $transformVia404;
14 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
15 var $pathDisclosureProtection = 'paranoid';
16
17 /**
18 * Factory functions for creating new files
19 * Override these in the base class
20 */
21 var $fileFactory = false, $oldFileFactory = false;
22
23 function __construct( $info ) {
24 // Required settings
25 $this->name = $info['name'];
26
27 // Optional settings
28 $this->initialCapital = true; // by default
29 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
30 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
31 {
32 if ( isset( $info[$var] ) ) {
33 $this->$var = $info[$var];
34 }
35 }
36 $this->transformVia404 = !empty( $info['transformVia404'] );
37 }
38
39 /**
40 * Determine if a string is an mwrepo:// URL
41 */
42 static function isVirtualUrl( $url ) {
43 return substr( $url, 0, 9 ) == 'mwrepo://';
44 }
45
46 /**
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.
54 */
55 function newFile( $title, $time = false ) {
56 if ( !($title instanceof Title) ) {
57 $title = Title::makeTitleSafe( NS_IMAGE, $title );
58 if ( !is_object( $title ) ) {
59 return null;
60 }
61 }
62 if ( $time ) {
63 if ( $this->oldFileFactory ) {
64 return call_user_func( $this->oldFileFactory, $title, $this, $time );
65 } else {
66 return false;
67 }
68 } else {
69 return call_user_func( $this->fileFactory, $title, $this );
70 }
71 }
72
73 /**
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.
77 *
78 * @param mixed $title Title object or string
79 * @param mixed $time 14-character timestamp, or false for the current version
80 */
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 ) ) {
85 return false;
86 }
87 }
88 # First try the current version of the file to see if it precedes the timestamp
89 $img = $this->newFile( $title );
90 if ( !$img ) {
91 return false;
92 }
93 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
94 return $img;
95 }
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) ) {
101 return $img;
102 } else if ( ($flags & FileRepo::FIND_PRIVATE) && $img->userCan(File::DELETED_FILE) ) {
103 return $img;
104 }
105 }
106 }
107 # Now try redirects
108 $redir = $this->checkRedirect( $title );
109 if( $redir && $redir->getNamespace() == NS_IMAGE) {
110 $img = $this->newFile( $redir );
111 if( !$img ) {
112 return false;
113 }
114 if( $img->exists() ) {
115 $img->redirectedFrom( $title->getText() );
116 return $img;
117 }
118 }
119 return false;
120 }
121
122 /**
123 * Get the URL of thumb.php
124 */
125 function getThumbScriptUrl() {
126 return $this->thumbScriptUrl;
127 }
128
129 /**
130 * Returns true if the repository can transform files via a 404 handler
131 */
132 function canTransformVia404() {
133 return $this->transformVia404;
134 }
135
136 /**
137 * Get the name of an image from its title object
138 */
139 function getNameFromTitle( $title ) {
140 global $wgCapitalLinks;
141 if ( $this->initialCapital != $wgCapitalLinks ) {
142 global $wgContLang;
143 $name = $title->getUserCaseDBKey();
144 if ( $this->initialCapital ) {
145 $name = $wgContLang->ucfirst( $name );
146 }
147 } else {
148 $name = $title->getDBkey();
149 }
150 return $name;
151 }
152
153 static function getHashPathForLevel( $name, $levels ) {
154 if ( $levels == 0 ) {
155 return '';
156 } else {
157 $hash = md5( $name );
158 $path = '';
159 for ( $i = 1; $i <= $levels; $i++ ) {
160 $path .= substr( $hash, 0, $i ) . '/';
161 }
162 return $path;
163 }
164 }
165
166 /**
167 * Get the name of this repository, as specified by $info['name]' to the constructor
168 */
169 function getName() {
170 return $this->name;
171 }
172
173 /**
174 * Get the file description page base URL, or false if there isn't one.
175 * @private
176 */
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 ) ) . ':';
185 } else {
186 $this->descBaseUrl = false;
187 }
188 }
189 return $this->descBaseUrl;
190 }
191
192 /**
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.
197 *
198 * In particular, it uses the article paths as specified to the repository
199 * constructor, whereas local repositories use the local Title functions.
200 */
201 function getDescriptionUrl( $name ) {
202 $base = $this->getDescBaseUrl();
203 if ( $base ) {
204 return $base . wfUrlencode( $name );
205 } else {
206 return false;
207 }
208 }
209
210 /**
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().
215 */
216 function getDescriptionRenderUrl( $name ) {
217 if ( isset( $this->scriptDirUrl ) ) {
218 return $this->scriptDirUrl . '/index.php?title=' .
219 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) . ':' . $name ) .
220 '&action=render';
221 } else {
222 $descBase = $this->getDescBaseUrl();
223 if ( $descBase ) {
224 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
225 } else {
226 return false;
227 }
228 }
229 }
230
231 /**
232 * Store a file to a given destination.
233 *
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
243 */
244 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
245 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
246 if ( $status->successCount == 0 ) {
247 $status->ok = false;
248 }
249 return $status;
250 }
251
252 /**
253 * Store a batch of files
254 *
255 * @param array $triplets (src,zone,dest) triplets as per store()
256 * @param integer $flags Flags as per store
257 */
258 abstract function storeBatch( $triplets, $flags = 0 );
259
260 /**
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.
263 *
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.
267 */
268 abstract function storeTemp( $originalName, $srcPath );
269
270 /**
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
274 * STUB
275 */
276 function freeTemp( $virtualUrl ) {
277 return true;
278 }
279
280 /**
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.
283 *
284 * Returns a FileRepoStatus object. On success, the value contains "new" or
285 * "archived", to indicate whether the file was new with that name.
286 *
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
293 */
294 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
295 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
296 if ( $status->successCount == 0 ) {
297 $status->ok = false;
298 }
299 if ( isset( $status->value[0] ) ) {
300 $status->value = $status->value[0];
301 } else {
302 $status->value = false;
303 }
304 return $status;
305 }
306
307 /**
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
312 */
313 abstract function publishBatch( $triplets, $flags = 0 );
314
315 /**
316 * Move a group of files to the deletion archive.
317 *
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.
320 *
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.
324 *
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
330 */
331 abstract function deleteBatch( $sourceDestPairs );
332
333 /**
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
341 */
342 function delete( $srcRel, $archiveRel ) {
343 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
344 }
345
346 /**
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()
350 */
351 abstract function getFileProps( $virtualUrl );
352
353 /**
354 * Call a callback function for every file in the repository
355 * May use either the database or the filesystem
356 * STUB
357 */
358 function enumFiles( $callback ) {
359 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
360 }
361
362 /**
363 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
364 */
365 function validateFilename( $filename ) {
366 if ( strval( $filename ) == '' ) {
367 return false;
368 }
369 if ( wfIsWindows() ) {
370 $filename = strtr( $filename, '\\', '/' );
371 }
372 /**
373 * Use the same traversal protection as Title::secureAndSplit()
374 */
375 if ( strpos( $filename, '.' ) !== false &&
376 ( $filename === '.' || $filename === '..' ||
377 strpos( $filename, './' ) === 0 ||
378 strpos( $filename, '../' ) === 0 ||
379 strpos( $filename, '/./' ) !== false ||
380 strpos( $filename, '/../' ) !== false ) )
381 {
382 return false;
383 } else {
384 return true;
385 }
386 }
387
388 /**#@+
389 * Path disclosure protection functions
390 */
391 function paranoidClean( $param ) { return '[hidden]'; }
392 function passThrough( $param ) { return $param; }
393
394 /**
395 * Get a callback function to use for cleaning error message parameters
396 */
397 function getErrorCleanupFunction() {
398 switch ( $this->pathDisclosureProtection ) {
399 case 'none':
400 $callback = array( $this, 'passThrough' );
401 break;
402 default: // 'paranoid'
403 $callback = array( $this, 'paranoidClean' );
404 }
405 return $callback;
406 }
407 /**#@-*/
408
409 /**
410 * Create a new fatal error
411 */
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 );
416 }
417
418 /**
419 * Create a new good result
420 */
421 function newGood( $value = null ) {
422 return FileRepoStatus::newGood( $this, $value );
423 }
424
425 /**
426 * Delete files in the deleted directory if they are not referenced in the filearchive table
427 * STUB
428 */
429 function cleanupDeletedBatch( $storageKeys ) {}
430
431 /**
432 * Checks if there is a redirect named as $title
433 * STUB
434 *
435 * @param Title $title Title of image
436 */
437 function checkRedirect( $title ) {
438 return false;
439 }
440
441 /**
442 * Invalidates image redirect cache related to that image
443 * STUB
444 *
445 * @param Title $title Title of image
446 */
447 function invalidateImageRedirect( $title ) {
448 }
449 }