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