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