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