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