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