Localisation updates for core messages from Betawiki (2008-06-23 22:55 CEST)
[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 * @ingroup FileRepo
7 */
8 abstract class FileRepo {
9 const DELETE_SOURCE = 1;
10 const FIND_PRIVATE = 1;
11 const FIND_IGNORE_REDIRECT = 2;
12 const OVERWRITE = 2;
13 const OVERWRITE_SAME = 4;
14
15 var $thumbScriptUrl, $transformVia404;
16 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
17 var $pathDisclosureProtection = 'paranoid';
18
19 /**
20 * Factory functions for creating new files
21 * Override these in the base class
22 */
23 var $fileFactory = false, $oldFileFactory = false;
24 var $fileFactoryKey = false, $oldFileFactoryKey = false;
25
26 function __construct( $info ) {
27 // Required settings
28 $this->name = $info['name'];
29
30 // Optional settings
31 $this->initialCapital = true; // by default
32 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
33 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
34 {
35 if ( isset( $info[$var] ) ) {
36 $this->$var = $info[$var];
37 }
38 }
39 $this->transformVia404 = !empty( $info['transformVia404'] );
40 }
41
42 /**
43 * Determine if a string is an mwrepo:// URL
44 */
45 static function isVirtualUrl( $url ) {
46 return substr( $url, 0, 9 ) == 'mwrepo://';
47 }
48
49 /**
50 * Create a new File object from the local repository
51 * @param mixed $title Title object or string
52 * @param mixed $time Time at which the image was uploaded.
53 * If this is specified, the returned object will be an
54 * instance of the repository's old file class instead of
55 * a current file. Repositories not supporting version
56 * control should return false if this parameter is set.
57 */
58 function newFile( $title, $time = false ) {
59 if ( !($title instanceof Title) ) {
60 $title = Title::makeTitleSafe( NS_IMAGE, $title );
61 if ( !is_object( $title ) ) {
62 return null;
63 }
64 }
65 if ( $time ) {
66 if ( $this->oldFileFactory ) {
67 return call_user_func( $this->oldFileFactory, $title, $this, $time );
68 } else {
69 return false;
70 }
71 } else {
72 return call_user_func( $this->fileFactory, $title, $this );
73 }
74 }
75
76 /**
77 * Find an instance of the named file created at the specified time
78 * Returns false if the file does not exist. Repositories not supporting
79 * version control should return false if the time is specified.
80 *
81 * @param mixed $title Title object or string
82 * @param mixed $time 14-character timestamp, or false for the current version
83 */
84 function findFile( $title, $time = false, $flags = 0 ) {
85 if ( !($title instanceof Title) ) {
86 $title = Title::makeTitleSafe( NS_IMAGE, $title );
87 if ( !is_object( $title ) ) {
88 return false;
89 }
90 }
91 # First try the current version of the file to see if it precedes the timestamp
92 $img = $this->newFile( $title );
93 if ( !$img ) {
94 return false;
95 }
96 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
97 return $img;
98 }
99 # Now try an old version of the file
100 if ( $time !== false ) {
101 $img = $this->newFile( $title, $time );
102 if ( $img->exists() ) {
103 if ( !$img->isDeleted(File::DELETED_FILE) ) {
104 return $img;
105 } else if ( ($flags & FileRepo::FIND_PRIVATE) && $img->userCan(File::DELETED_FILE) ) {
106 return $img;
107 }
108 }
109 }
110
111 # Now try redirects
112 if ( $flags & FileRepo::FIND_IGNORE_REDIRECT ) {
113 return false;
114 }
115 $redir = $this->checkRedirect( $title );
116 if( $redir && $redir->getNamespace() == NS_IMAGE) {
117 $img = $this->newFile( $redir );
118 if( !$img ) {
119 return false;
120 }
121 if( $img->exists() ) {
122 $img->redirectedFrom( $title->getDBkey() );
123 return $img;
124 }
125 }
126 return false;
127 }
128
129 /*
130 * Find many files at once.
131 * @param array $titles, an array of titles
132 * @param int $flags
133 */
134 function findFiles( $titles, $flags ) {
135 $result = array();
136 foreach ( $titles as $index => $title ) {
137 $file = $this->findFile( $title, $flags );
138 if ( $file )
139 $result[$file->getTitle()->getDBkey()] = $file;
140 }
141 return $result;
142 }
143
144 /**
145 * Create a new File object from the local repository
146 * @param mixed $sha1 SHA-1 key
147 * @param mixed $time Time at which the image was uploaded.
148 * If this is specified, the returned object will be an
149 * instance of the repository's old file class instead of
150 * a current file. Repositories not supporting version
151 * control should return false if this parameter is set.
152 */
153 function newFileFromKey( $sha1, $time = false ) {
154 if ( $time ) {
155 if ( $this->oldFileFactoryKey ) {
156 return call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
157 } else {
158 return false;
159 }
160 } else {
161 return call_user_func( $this->fileFactoryKey, $sha1, $this );
162 }
163 }
164
165 /**
166 * Find an instance of the file with this key, created at the specified time
167 * Returns false if the file does not exist. Repositories not supporting
168 * version control should return false if the time is specified.
169 *
170 * @param string $sha1 string
171 * @param mixed $time 14-character timestamp, or false for the current version
172 */
173 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
174 # First try the current version of the file to see if it precedes the timestamp
175 $img = $this->newFileFromKey( $sha1 );
176 if ( !$img ) {
177 return false;
178 }
179 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
180 return $img;
181 }
182 # Now try an old version of the file
183 if ( $time !== false ) {
184 $img = $this->newFileFromKey( $sha1, $time );
185 if ( $img->exists() ) {
186 if ( !$img->isDeleted(File::DELETED_FILE) ) {
187 return $img;
188 } else if ( ($flags & FileRepo::FIND_PRIVATE) && $img->userCan(File::DELETED_FILE) ) {
189 return $img;
190 }
191 }
192 }
193 return false;
194 }
195
196 /**
197 * Get the URL of thumb.php
198 */
199 function getThumbScriptUrl() {
200 return $this->thumbScriptUrl;
201 }
202
203 /**
204 * Returns true if the repository can transform files via a 404 handler
205 */
206 function canTransformVia404() {
207 return $this->transformVia404;
208 }
209
210 /**
211 * Get the name of an image from its title object
212 */
213 function getNameFromTitle( $title ) {
214 global $wgCapitalLinks;
215 if ( $this->initialCapital != $wgCapitalLinks ) {
216 global $wgContLang;
217 $name = $title->getUserCaseDBKey();
218 if ( $this->initialCapital ) {
219 $name = $wgContLang->ucfirst( $name );
220 }
221 } else {
222 $name = $title->getDBkey();
223 }
224 return $name;
225 }
226
227 static function getHashPathForLevel( $name, $levels ) {
228 if ( $levels == 0 ) {
229 return '';
230 } else {
231 $hash = md5( $name );
232 $path = '';
233 for ( $i = 1; $i <= $levels; $i++ ) {
234 $path .= substr( $hash, 0, $i ) . '/';
235 }
236 return $path;
237 }
238 }
239
240 /**
241 * Get the name of this repository, as specified by $info['name]' to the constructor
242 */
243 function getName() {
244 return $this->name;
245 }
246
247 /**
248 * Get the file description page base URL, or false if there isn't one.
249 * @private
250 */
251 function getDescBaseUrl() {
252 if ( is_null( $this->descBaseUrl ) ) {
253 if ( !is_null( $this->articleUrl ) ) {
254 $this->descBaseUrl = str_replace( '$1',
255 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) ) . ':', $this->articleUrl );
256 } elseif ( !is_null( $this->scriptDirUrl ) ) {
257 $this->descBaseUrl = $this->scriptDirUrl . '/index.php?title=' .
258 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) ) . ':';
259 } else {
260 $this->descBaseUrl = false;
261 }
262 }
263 return $this->descBaseUrl;
264 }
265
266 /**
267 * Get the URL of an image description page. May return false if it is
268 * unknown or not applicable. In general this should only be called by the
269 * File class, since it may return invalid results for certain kinds of
270 * repositories. Use File::getDescriptionUrl() in user code.
271 *
272 * In particular, it uses the article paths as specified to the repository
273 * constructor, whereas local repositories use the local Title functions.
274 */
275 function getDescriptionUrl( $name ) {
276 $base = $this->getDescBaseUrl();
277 if ( $base ) {
278 return $base . wfUrlencode( $name );
279 } else {
280 return false;
281 }
282 }
283
284 /**
285 * Get the URL of the content-only fragment of the description page. For
286 * MediaWiki this means action=render. This should only be called by the
287 * repository's file class, since it may return invalid results. User code
288 * should use File::getDescriptionText().
289 */
290 function getDescriptionRenderUrl( $name ) {
291 if ( isset( $this->scriptDirUrl ) ) {
292 return $this->scriptDirUrl . '/index.php?title=' .
293 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) . ':' . $name ) .
294 '&action=render';
295 } else {
296 $descBase = $this->getDescBaseUrl();
297 if ( $descBase ) {
298 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
299 } else {
300 return false;
301 }
302 }
303 }
304
305 /**
306 * Store a file to a given destination.
307 *
308 * @param string $srcPath Source path or virtual URL
309 * @param string $dstZone Destination zone
310 * @param string $dstRel Destination relative path
311 * @param integer $flags Bitwise combination of the following flags:
312 * self::DELETE_SOURCE Delete the source file after upload
313 * self::OVERWRITE Overwrite an existing destination file instead of failing
314 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
315 * same contents as the source
316 * @return FileRepoStatus
317 */
318 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
319 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
320 if ( $status->successCount == 0 ) {
321 $status->ok = false;
322 }
323 return $status;
324 }
325
326 /**
327 * Store a batch of files
328 *
329 * @param array $triplets (src,zone,dest) triplets as per store()
330 * @param integer $flags Flags as per store
331 */
332 abstract function storeBatch( $triplets, $flags = 0 );
333
334 /**
335 * Pick a random name in the temp zone and store a file to it.
336 * Returns a FileRepoStatus object with the URL in the value.
337 *
338 * @param string $originalName The base name of the file as specified
339 * by the user. The file extension will be maintained.
340 * @param string $srcPath The current location of the file.
341 */
342 abstract function storeTemp( $originalName, $srcPath );
343
344 /**
345 * Remove a temporary file or mark it for garbage collection
346 * @param string $virtualUrl The virtual URL returned by storeTemp
347 * @return boolean True on success, false on failure
348 * STUB
349 */
350 function freeTemp( $virtualUrl ) {
351 return true;
352 }
353
354 /**
355 * Copy or move a file either from the local filesystem or from an mwrepo://
356 * virtual URL, into this repository at the specified destination location.
357 *
358 * Returns a FileRepoStatus object. On success, the value contains "new" or
359 * "archived", to indicate whether the file was new with that name.
360 *
361 * @param string $srcPath The source path or URL
362 * @param string $dstRel The destination relative path
363 * @param string $archiveRel The relative path where the existing file is to
364 * be archived, if there is one. Relative to the public zone root.
365 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
366 * that the source file should be deleted if possible
367 */
368 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
369 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
370 if ( $status->successCount == 0 ) {
371 $status->ok = false;
372 }
373 if ( isset( $status->value[0] ) ) {
374 $status->value = $status->value[0];
375 } else {
376 $status->value = false;
377 }
378 return $status;
379 }
380
381 /**
382 * Publish a batch of files
383 * @param array $triplets (source,dest,archive) triplets as per publish()
384 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
385 * that the source files should be deleted if possible
386 */
387 abstract function publishBatch( $triplets, $flags = 0 );
388
389 /**
390 * Move a group of files to the deletion archive.
391 *
392 * If no valid deletion archive is configured, this may either delete the
393 * file or throw an exception, depending on the preference of the repository.
394 *
395 * The overwrite policy is determined by the repository -- currently FSRepo
396 * assumes a naming scheme in the deleted zone based on content hash, as
397 * opposed to the public zone which is assumed to be unique.
398 *
399 * @param array $sourceDestPairs Array of source/destination pairs. Each element
400 * is a two-element array containing the source file path relative to the
401 * public root in the first element, and the archive file path relative
402 * to the deleted zone root in the second element.
403 * @return FileRepoStatus
404 */
405 abstract function deleteBatch( $sourceDestPairs );
406
407 /**
408 * Move a file to the deletion archive.
409 * If no valid deletion archive exists, this may either delete the file
410 * or throw an exception, depending on the preference of the repository
411 * @param mixed $srcRel Relative path for the file to be deleted
412 * @param mixed $archiveRel Relative path for the archive location.
413 * Relative to a private archive directory.
414 * @return WikiError object (wikitext-formatted), or true for success
415 */
416 function delete( $srcRel, $archiveRel ) {
417 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
418 }
419
420 /**
421 * Get properties of a file with a given virtual URL
422 * The virtual URL must refer to this repo
423 * Properties should ultimately be obtained via File::getPropsFromPath()
424 */
425 abstract function getFileProps( $virtualUrl );
426
427 /**
428 * Call a callback function for every file in the repository
429 * May use either the database or the filesystem
430 * STUB
431 */
432 function enumFiles( $callback ) {
433 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
434 }
435
436 /**
437 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
438 */
439 function validateFilename( $filename ) {
440 if ( strval( $filename ) == '' ) {
441 return false;
442 }
443 if ( wfIsWindows() ) {
444 $filename = strtr( $filename, '\\', '/' );
445 }
446 /**
447 * Use the same traversal protection as Title::secureAndSplit()
448 */
449 if ( strpos( $filename, '.' ) !== false &&
450 ( $filename === '.' || $filename === '..' ||
451 strpos( $filename, './' ) === 0 ||
452 strpos( $filename, '../' ) === 0 ||
453 strpos( $filename, '/./' ) !== false ||
454 strpos( $filename, '/../' ) !== false ) )
455 {
456 return false;
457 } else {
458 return true;
459 }
460 }
461
462 /**#@+
463 * Path disclosure protection functions
464 */
465 function paranoidClean( $param ) { return '[hidden]'; }
466 function passThrough( $param ) { return $param; }
467
468 /**
469 * Get a callback function to use for cleaning error message parameters
470 */
471 function getErrorCleanupFunction() {
472 switch ( $this->pathDisclosureProtection ) {
473 case 'none':
474 $callback = array( $this, 'passThrough' );
475 break;
476 default: // 'paranoid'
477 $callback = array( $this, 'paranoidClean' );
478 }
479 return $callback;
480 }
481 /**#@-*/
482
483 /**
484 * Create a new fatal error
485 */
486 function newFatal( $message /*, parameters...*/ ) {
487 $params = func_get_args();
488 array_unshift( $params, $this );
489 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
490 }
491
492 /**
493 * Create a new good result
494 */
495 function newGood( $value = null ) {
496 return FileRepoStatus::newGood( $this, $value );
497 }
498
499 /**
500 * Delete files in the deleted directory if they are not referenced in the filearchive table
501 * STUB
502 */
503 function cleanupDeletedBatch( $storageKeys ) {}
504
505 /**
506 * Checks if there is a redirect named as $title
507 * STUB
508 *
509 * @param Title $title Title of image
510 */
511 function checkRedirect( $title ) {
512 return false;
513 }
514
515 /**
516 * Invalidates image redirect cache related to that image
517 * STUB
518 *
519 * @param Title $title Title of image
520 */
521 function invalidateImageRedirect( $title ) {
522 }
523
524 function findBySha1( $hash ) {
525 return array();
526 }
527 }