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