* (bug 27721) Make JavaScript variables wgSeparatorTransformTable and wgDigitTransfor...
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * Base code for file repositories.
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * Base class for file repositories.
11 * Do not instantiate, use a derived class.
12 *
13 * @ingroup FileRepo
14 */
15 abstract class FileRepo {
16 const FILES_ONLY = 1;
17 const DELETE_SOURCE = 1;
18 const OVERWRITE = 2;
19 const OVERWRITE_SAME = 4;
20 const SKIP_VALIDATION = 8;
21
22 var $thumbScriptUrl, $transformVia404;
23 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
24 var $fetchDescription, $initialCapital;
25 var $pathDisclosureProtection = 'paranoid';
26 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
27
28 /**
29 * Factory functions for creating new files
30 * Override these in the base class
31 */
32 var $fileFactory = false, $oldFileFactory = false;
33 var $fileFactoryKey = false, $oldFileFactoryKey = false;
34
35 function __construct( $info ) {
36 // Required settings
37 $this->name = $info['name'];
38
39 // Optional settings
40 $this->initialCapital = MWNamespace::isCapitalized( NS_FILE );
41 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
42 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
43 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
44 as $var )
45 {
46 if ( isset( $info[$var] ) ) {
47 $this->$var = $info[$var];
48 }
49 }
50 $this->transformVia404 = !empty( $info['transformVia404'] );
51 }
52
53 /**
54 * Determine if a string is an mwrepo:// URL
55 *
56 * @param $url string
57 *
58 * @return bool
59 */
60 static function isVirtualUrl( $url ) {
61 return substr( $url, 0, 9 ) == 'mwrepo://';
62 }
63
64 /**
65 * Create a new File object from the local repository
66 *
67 * @param $title Mixed: Title object or string
68 * @param $time Mixed: Time at which the image was uploaded.
69 * If this is specified, the returned object will be an
70 * instance of the repository's old file class instead of a
71 * current file. Repositories not supporting version control
72 * should return false if this parameter is set.
73 *
74 * @return File|null A File, or null if passed an invalid Title
75 */
76 function newFile( $title, $time = false ) {
77 $title = File::normalizeTitle( $title );
78 if ( !$title ) {
79 return null;
80 }
81 if ( $time ) {
82 if ( $this->oldFileFactory ) {
83 return call_user_func( $this->oldFileFactory, $title, $this, $time );
84 } else {
85 return false;
86 }
87 } else {
88 return call_user_func( $this->fileFactory, $title, $this );
89 }
90 }
91
92 /**
93 * Find an instance of the named file created at the specified time
94 * Returns false if the file does not exist. Repositories not supporting
95 * version control should return false if the time is specified.
96 *
97 * @param $title Mixed: Title object or string
98 * @param $options array Associative array of options:
99 * time: requested time for an archived image, or false for the
100 * current version. An image object will be returned which was
101 * created at the specified time.
102 *
103 * ignoreRedirect: If true, do not follow file redirects
104 *
105 * private: If true, return restricted (deleted) files if the current
106 * user is allowed to view them. Otherwise, such files will not
107 * be found.
108 *
109 * @return File|false
110 */
111 function findFile( $title, $options = array() ) {
112 $title = File::normalizeTitle( $title );
113 if ( !$title ) {
114 return false;
115 }
116 $time = isset( $options['time'] ) ? $options['time'] : false;
117 # First try the current version of the file to see if it precedes the timestamp
118 $img = $this->newFile( $title );
119 if ( !$img ) {
120 return false;
121 }
122 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
123 return $img;
124 }
125 # Now try an old version of the file
126 if ( $time !== false ) {
127 $img = $this->newFile( $title, $time );
128 if ( $img && $img->exists() ) {
129 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
130 return $img; // always OK
131 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
132 return $img;
133 }
134 }
135 }
136
137 # Now try redirects
138 if ( !empty( $options['ignoreRedirect'] ) ) {
139 return false;
140 }
141 $redir = $this->checkRedirect( $title );
142 if( $redir && $title->getNamespace() == NS_FILE) {
143 $img = $this->newFile( $redir );
144 if( !$img ) {
145 return false;
146 }
147 if( $img->exists() ) {
148 $img->redirectedFrom( $title->getDBkey() );
149 return $img;
150 }
151 }
152 return false;
153 }
154
155 /**
156 * Find many files at once.
157 * @param $items An array of titles, or an array of findFile() options with
158 * the "title" option giving the title. Example:
159 *
160 * $findItem = array( 'title' => $title, 'private' => true );
161 * $findBatch = array( $findItem );
162 * $repo->findFiles( $findBatch );
163 *
164 * @return array
165 */
166 function findFiles( $items ) {
167 $result = array();
168 foreach ( $items as $item ) {
169 if ( is_array( $item ) ) {
170 $title = $item['title'];
171 $options = $item;
172 unset( $options['title'] );
173 } else {
174 $title = $item;
175 $options = array();
176 }
177 $file = $this->findFile( $title, $options );
178 if ( $file ) {
179 $result[$file->getTitle()->getDBkey()] = $file;
180 }
181 }
182 return $result;
183 }
184
185 /**
186 * Find an instance of the file with this key, created at the specified time
187 * Returns false if the file does not exist. Repositories not supporting
188 * version control should return false if the time is specified.
189 *
190 * @param $sha1 String base 36 SHA-1 hash
191 * @param $options Option array, same as findFile().
192 */
193 function findFileFromKey( $sha1, $options = array() ) {
194 $time = isset( $options['time'] ) ? $options['time'] : false;
195
196 # First try to find a matching current version of a file...
197 if ( $this->fileFactoryKey ) {
198 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
199 } else {
200 return false; // find-by-sha1 not supported
201 }
202 if ( $img && $img->exists() ) {
203 return $img;
204 }
205 # Now try to find a matching old version of a file...
206 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
207 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
208 if ( $img && $img->exists() ) {
209 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
210 return $img; // always OK
211 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
212 return $img;
213 }
214 }
215 }
216 return false;
217 }
218
219 /**
220 * Get the URL of thumb.php
221 */
222 function getThumbScriptUrl() {
223 return $this->thumbScriptUrl;
224 }
225
226 /**
227 * Get the URL corresponding to one of the four basic zones
228 * @param $zone String: one of: public, deleted, temp, thumb
229 * @return String or false
230 */
231 function getZoneUrl( $zone ) {
232 return false;
233 }
234
235 /**
236 * Returns true if the repository can transform files via a 404 handler
237 *
238 * @return bool
239 */
240 function canTransformVia404() {
241 return $this->transformVia404;
242 }
243
244 /**
245 * Get the name of an image from its title object
246 * @param $title Title
247 */
248 function getNameFromTitle( Title $title ) {
249 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
250 global $wgContLang;
251 $name = $title->getUserCaseDBKey();
252 if ( $this->initialCapital ) {
253 $name = $wgContLang->ucfirst( $name );
254 }
255 } else {
256 $name = $title->getDBkey();
257 }
258 return $name;
259 }
260
261 /**
262 * @param $name
263 * @param $levels
264 * @return string
265 */
266 static function getHashPathForLevel( $name, $levels ) {
267 if ( $levels == 0 ) {
268 return '';
269 } else {
270 $hash = md5( $name );
271 $path = '';
272 for ( $i = 1; $i <= $levels; $i++ ) {
273 $path .= substr( $hash, 0, $i ) . '/';
274 }
275 return $path;
276 }
277 }
278
279 /**
280 * Get a relative path including trailing slash, e.g. f/fa/
281 * If the repo is not hashed, returns an empty string
282 *
283 * @param $name string
284 *
285 * @return string
286 */
287 function getHashPath( $name ) {
288 return self::getHashPathForLevel( $name, $this->hashLevels );
289 }
290
291 /**
292 * Get the name of this repository, as specified by $info['name]' to the constructor
293 */
294 function getName() {
295 return $this->name;
296 }
297
298 /**
299 * Make an url to this repo
300 *
301 * @param $query mixed Query string to append
302 * @param $entry string Entry point; defaults to index
303 * @return string
304 */
305 function makeUrl( $query = '', $entry = 'index' ) {
306 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
307 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
308 }
309
310 /**
311 * Get the URL of an image description page. May return false if it is
312 * unknown or not applicable. In general this should only be called by the
313 * File class, since it may return invalid results for certain kinds of
314 * repositories. Use File::getDescriptionUrl() in user code.
315 *
316 * In particular, it uses the article paths as specified to the repository
317 * constructor, whereas local repositories use the local Title functions.
318 */
319 function getDescriptionUrl( $name ) {
320 $encName = wfUrlencode( $name );
321 if ( !is_null( $this->descBaseUrl ) ) {
322 # "http://example.com/wiki/Image:"
323 return $this->descBaseUrl . $encName;
324 }
325 if ( !is_null( $this->articleUrl ) ) {
326 # "http://example.com/wiki/$1"
327 #
328 # We use "Image:" as the canonical namespace for
329 # compatibility across all MediaWiki versions.
330 return str_replace( '$1',
331 "Image:$encName", $this->articleUrl );
332 }
333 if ( !is_null( $this->scriptDirUrl ) ) {
334 # "http://example.com/w"
335 #
336 # We use "Image:" as the canonical namespace for
337 # compatibility across all MediaWiki versions,
338 # and just sort of hope index.php is right. ;)
339 return $this->makeUrl( "title=Image:$encName" );
340 }
341 return false;
342 }
343
344 /**
345 * Get the URL of the content-only fragment of the description page. For
346 * MediaWiki this means action=render. This should only be called by the
347 * repository's file class, since it may return invalid results. User code
348 * should use File::getDescriptionText().
349 * @param $name String: name of image to fetch
350 * @param $lang String: language to fetch it in, if any.
351 */
352 function getDescriptionRenderUrl( $name, $lang = null ) {
353 $query = 'action=render';
354 if ( !is_null( $lang ) ) {
355 $query .= '&uselang=' . $lang;
356 }
357 if ( isset( $this->scriptDirUrl ) ) {
358 return $this->makeUrl(
359 'title=' .
360 wfUrlencode( 'Image:' . $name ) .
361 "&$query" );
362 } else {
363 $descUrl = $this->getDescriptionUrl( $name );
364 if ( $descUrl ) {
365 return wfAppendQuery( $descUrl, $query );
366 } else {
367 return false;
368 }
369 }
370 }
371
372 /**
373 * Get the URL of the stylesheet to apply to description pages
374 * @return string
375 */
376 function getDescriptionStylesheetUrl() {
377 if ( $this->scriptDirUrl ) {
378 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
379 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
380 }
381 }
382
383 /**
384 * Store a file to a given destination.
385 *
386 * @param $srcPath String: source path or virtual URL
387 * @param $dstZone String: destination zone
388 * @param $dstRel String: destination relative path
389 * @param $flags Integer: bitwise combination of the following flags:
390 * self::DELETE_SOURCE Delete the source file after upload
391 * self::OVERWRITE Overwrite an existing destination file instead of failing
392 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
393 * same contents as the source
394 * @return FileRepoStatus
395 */
396 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
397 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
398 if ( $status->successCount == 0 ) {
399 $status->ok = false;
400 }
401 return $status;
402 }
403
404 /**
405 * Store a batch of files
406 *
407 * @param $triplets Array: (src,zone,dest) triplets as per store()
408 * @param $flags Integer: flags as per store
409 */
410 abstract function storeBatch( $triplets, $flags = 0 );
411
412 /**
413 * Pick a random name in the temp zone and store a file to it.
414 * Returns a FileRepoStatus object with the URL in the value.
415 *
416 * @param $originalName String: the base name of the file as specified
417 * by the user. The file extension will be maintained.
418 * @param $srcPath String: the current location of the file.
419 */
420 abstract function storeTemp( $originalName, $srcPath );
421
422
423 /**
424 * Append the contents of the source path to the given file, OR queue
425 * the appending operation in anticipation of a later appendFinish() call.
426 * @param $srcPath String: location of the source file
427 * @param $toAppendPath String: path to append to.
428 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
429 * that the source file should be deleted if possible
430 * @return mixed Status or false
431 */
432 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
433
434 /**
435 * Finish the append operation.
436 * @param $toAppendPath String: path to append to.
437 * @return mixed Status or false
438 */
439 abstract function appendFinish( $toAppendPath );
440
441 /**
442 * Remove a temporary file or mark it for garbage collection
443 * @param $virtualUrl String: the virtual URL returned by storeTemp
444 * @return Boolean: true on success, false on failure
445 * STUB
446 */
447 function freeTemp( $virtualUrl ) {
448 return true;
449 }
450
451 /**
452 * Copy or move a file either from the local filesystem or from an mwrepo://
453 * virtual URL, into this repository at the specified destination location.
454 *
455 * Returns a FileRepoStatus object. On success, the value contains "new" or
456 * "archived", to indicate whether the file was new with that name.
457 *
458 * @param $srcPath String: the source path or URL
459 * @param $dstRel String: the destination relative path
460 * @param $archiveRel String: the relative path where the existing file is to
461 * be archived, if there is one. Relative to the public zone root.
462 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
463 * that the source file should be deleted if possible
464 */
465 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
466 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
467 if ( $status->successCount == 0 ) {
468 $status->ok = false;
469 }
470 if ( isset( $status->value[0] ) ) {
471 $status->value = $status->value[0];
472 } else {
473 $status->value = false;
474 }
475 return $status;
476 }
477
478 /**
479 * Publish a batch of files
480 * @param $triplets Array: (source,dest,archive) triplets as per publish()
481 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
482 * that the source files should be deleted if possible
483 */
484 abstract function publishBatch( $triplets, $flags = 0 );
485
486 /**
487 * @param $file
488 * @param int $flags
489 * @return bool
490 */
491 function fileExists( $file, $flags = 0 ) {
492 $result = $this->fileExistsBatch( array( $file ), $flags );
493 return $result[0];
494 }
495
496 /**
497 * Checks existence of an array of files.
498 *
499 * @param $files Array: URLs (or paths) of files to check
500 * @param $flags Integer: bitwise combination of the following flags:
501 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
502 * @return Either array of files and existence flags, or false
503 */
504 abstract function fileExistsBatch( $files, $flags = 0 );
505
506 /**
507 * Move a group of files to the deletion archive.
508 *
509 * If no valid deletion archive is configured, this may either delete the
510 * file or throw an exception, depending on the preference of the repository.
511 *
512 * The overwrite policy is determined by the repository -- currently FSRepo
513 * assumes a naming scheme in the deleted zone based on content hash, as
514 * opposed to the public zone which is assumed to be unique.
515 *
516 * @param $sourceDestPairs Array of source/destination pairs. Each element
517 * is a two-element array containing the source file path relative to the
518 * public root in the first element, and the archive file path relative
519 * to the deleted zone root in the second element.
520 * @return FileRepoStatus
521 */
522 abstract function deleteBatch( $sourceDestPairs );
523
524 /**
525 * Move a file to the deletion archive.
526 * If no valid deletion archive exists, this may either delete the file
527 * or throw an exception, depending on the preference of the repository
528 * @param $srcRel Mixed: relative path for the file to be deleted
529 * @param $archiveRel Mixed: relative path for the archive location.
530 * Relative to a private archive directory.
531 * @return FileRepoStatus object
532 */
533 function delete( $srcRel, $archiveRel ) {
534 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
535 }
536
537 /**
538 * Get properties of a file with a given virtual URL
539 * The virtual URL must refer to this repo
540 * Properties should ultimately be obtained via File::getPropsFromPath()
541 *
542 * @param $virtualUrl string
543 */
544 abstract function getFileProps( $virtualUrl );
545
546 /**
547 * Call a callback function for every file in the repository
548 * May use either the database or the filesystem
549 * STUB
550 */
551 function enumFiles( $callback ) {
552 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
553 }
554
555 /**
556 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
557 *
558 * @param $filename string
559 *
560 * @return bool
561 */
562 function validateFilename( $filename ) {
563 if ( strval( $filename ) == '' ) {
564 return false;
565 }
566 if ( wfIsWindows() ) {
567 $filename = strtr( $filename, '\\', '/' );
568 }
569 /**
570 * Use the same traversal protection as Title::secureAndSplit()
571 */
572 if ( strpos( $filename, '.' ) !== false &&
573 ( $filename === '.' || $filename === '..' ||
574 strpos( $filename, './' ) === 0 ||
575 strpos( $filename, '../' ) === 0 ||
576 strpos( $filename, '/./' ) !== false ||
577 strpos( $filename, '/../' ) !== false ) )
578 {
579 return false;
580 } else {
581 return true;
582 }
583 }
584
585 /**#@+
586 * Path disclosure protection functions
587 */
588 function paranoidClean( $param ) { return '[hidden]'; }
589
590 /**
591 * @param $param
592 * @return
593 */
594 function passThrough( $param ) { return $param; }
595
596 /**
597 * Get a callback function to use for cleaning error message parameters
598 */
599 function getErrorCleanupFunction() {
600 switch ( $this->pathDisclosureProtection ) {
601 case 'none':
602 $callback = array( $this, 'passThrough' );
603 break;
604 default: // 'paranoid'
605 $callback = array( $this, 'paranoidClean' );
606 }
607 return $callback;
608 }
609 /**#@-*/
610
611 /**
612 * Create a new fatal error
613 */
614 function newFatal( $message /*, parameters...*/ ) {
615 $params = func_get_args();
616 array_unshift( $params, $this );
617 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
618 }
619
620 /**
621 * Create a new good result
622 *
623 * @return FileRepoStatus
624 */
625 function newGood( $value = null ) {
626 return FileRepoStatus::newGood( $this, $value );
627 }
628
629 /**
630 * Delete files in the deleted directory if they are not referenced in the filearchive table
631 * STUB
632 */
633 function cleanupDeletedBatch( $storageKeys ) {}
634
635 /**
636 * Checks if there is a redirect named as $title. If there is, return the
637 * title object. If not, return false.
638 * STUB
639 *
640 * @param $title Title of image
641 * @return Bool
642 */
643 function checkRedirect( Title $title ) {
644 return false;
645 }
646
647 /**
648 * Invalidates image redirect cache related to that image
649 * Doesn't do anything for repositories that don't support image redirects.
650 *
651 * STUB
652 * @param $title Title of image
653 */
654 function invalidateImageRedirect( Title $title ) {}
655
656 /**
657 * Get an array or iterator of file objects for files that have a given
658 * SHA-1 content hash.
659 *
660 * STUB
661 */
662 function findBySha1( $hash ) {
663 return array();
664 }
665
666 /**
667 * Get the human-readable name of the repo.
668 * @return string
669 */
670 public function getDisplayName() {
671 // We don't name our own repo, return nothing
672 if ( $this->isLocal() ) {
673 return null;
674 }
675 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
676 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
677 }
678
679 /**
680 * Returns true if this the local file repository.
681 *
682 * @return bool
683 */
684 function isLocal() {
685 return $this->getName() == 'local';
686 }
687
688 /**
689 * Get a key on the primary cache for this repository.
690 * Returns false if the repository's cache is not accessible at this site.
691 * The parameters are the parts of the key, as for wfMemcKey().
692 *
693 * STUB
694 */
695 function getSharedCacheKey( /*...*/ ) {
696 return false;
697 }
698
699 /**
700 * Get a key for this repo in the local cache domain. These cache keys are
701 * not shared with remote instances of the repo.
702 * The parameters are the parts of the key, as for wfMemcKey().
703 */
704 function getLocalCacheKey( /*...*/ ) {
705 $args = func_get_args();
706 array_unshift( $args, 'filerepo', $this->getName() );
707 return call_user_func_array( 'wfMemcKey', $args );
708 }
709
710 /**
711 * Get an UploadStash associated with this repo.
712 *
713 * @return UploadStash
714 */
715 function getUploadStash() {
716 return new UploadStash( $this );
717 }
718 }