Merge "Get to the point about howto download Vector :p"
[lhc/web/wiklou.git] / includes / filerepo / file / File.php
1 <?php
2 /**
3 * @defgroup FileAbstraction File abstraction
4 * @ingroup FileRepo
5 *
6 * Represents files in a repository.
7 */
8
9 /**
10 * Base code for files.
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
26 *
27 * @file
28 * @ingroup FileAbstraction
29 */
30
31 /**
32 * Implements some public methods and some protected utility functions which
33 * are required by multiple child classes. Contains stub functionality for
34 * unimplemented public methods.
35 *
36 * Stub functions which should be overridden are marked with STUB. Some more
37 * concrete functions are also typically overridden by child classes.
38 *
39 * Note that only the repo object knows what its file class is called. You should
40 * never name a file class explictly outside of the repo class. Instead use the
41 * repo's factory functions to generate file objects, for example:
42 *
43 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
44 *
45 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
46 * in most cases.
47 *
48 * @ingroup FileAbstraction
49 */
50 abstract class File {
51 // Bitfield values akin to the Revision deletion constants
52 const DELETED_FILE = 1;
53 const DELETED_COMMENT = 2;
54 const DELETED_USER = 4;
55 const DELETED_RESTRICTED = 8;
56
57 /** Force rendering in the current process */
58 const RENDER_NOW = 1;
59 /**
60 * Force rendering even if thumbnail already exist and using RENDER_NOW
61 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
62 */
63 const RENDER_FORCE = 2;
64
65 const DELETE_SOURCE = 1;
66
67 // Audience options for File::getDescription()
68 const FOR_PUBLIC = 1;
69 const FOR_THIS_USER = 2;
70 const RAW = 3;
71
72 // Options for File::thumbName()
73 const THUMB_FULL_NAME = 1;
74
75 /**
76 * Some member variables can be lazy-initialised using __get(). The
77 * initialisation function for these variables is always a function named
78 * like getVar(), where Var is the variable name with upper-case first
79 * letter.
80 *
81 * The following variables are initialised in this way in this base class:
82 * name, extension, handler, path, canRender, isSafeFile,
83 * transformScript, hashPath, pageCount, url
84 *
85 * Code within this class should generally use the accessor function
86 * directly, since __get() isn't re-entrant and therefore causes bugs that
87 * depend on initialisation order.
88 */
89
90 /**
91 * The following member variables are not lazy-initialised
92 */
93
94 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
95 public $repo;
96
97 /** @var Title|string|bool */
98 protected $title;
99
100 /** @var string Text of last error */
101 protected $lastError;
102
103 /** @var string Main part of the title, with underscores (Title::getDBkey) */
104 protected $redirected;
105
106 /** @var Title */
107 protected $redirectedTitle;
108
109 /** @var FSFile|bool False if undefined */
110 protected $fsFile;
111
112 /** @var MediaHandler */
113 protected $handler;
114
115 /** @var string The URL corresponding to one of the four basic zones */
116 protected $url;
117
118 /** @var string File extension */
119 protected $extension;
120
121 /** @var string The name of a file from its title object */
122 protected $name;
123
124 /** @var string The storage path corresponding to one of the zones */
125 protected $path;
126
127 /** @var string Relative path including trailing slash */
128 protected $hashPath;
129
130 /** @var string Number of pages of a multipage document, or false for
131 * documents which aren't multipage documents
132 */
133 protected $pageCount;
134
135 /** @var string URL of transformscript (for example thumb.php) */
136 protected $transformScript;
137
138 /** @var Title */
139 protected $redirectTitle;
140
141 /** @var bool Whether the output of transform() for this file is likely to be valid. */
142 protected $canRender;
143
144 /** @var bool Whether this media file is in a format that is unlikely to
145 * contain viruses or malicious content
146 */
147 protected $isSafeFile;
148
149 /** @var string Required Repository class type */
150 protected $repoClass = 'FileRepo';
151
152 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
153 protected $tmpBucketedThumbCache = array();
154
155 /**
156 * Call this constructor from child classes.
157 *
158 * Both $title and $repo are optional, though some functions
159 * may return false or throw exceptions if they are not set.
160 * Most subclasses will want to call assertRepoDefined() here.
161 *
162 * @param Title|string|bool $title
163 * @param FileRepo|bool $repo
164 */
165 function __construct( $title, $repo ) {
166 if ( $title !== false ) { // subclasses may not use MW titles
167 $title = self::normalizeTitle( $title, 'exception' );
168 }
169 $this->title = $title;
170 $this->repo = $repo;
171 }
172
173 /**
174 * Given a string or Title object return either a
175 * valid Title object with namespace NS_FILE or null
176 *
177 * @param Title|string $title
178 * @param string|bool $exception Use 'exception' to throw an error on bad titles
179 * @throws MWException
180 * @return Title|null
181 */
182 static function normalizeTitle( $title, $exception = false ) {
183 $ret = $title;
184 if ( $ret instanceof Title ) {
185 # Normalize NS_MEDIA -> NS_FILE
186 if ( $ret->getNamespace() == NS_MEDIA ) {
187 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
188 # Sanity check the title namespace
189 } elseif ( $ret->getNamespace() !== NS_FILE ) {
190 $ret = null;
191 }
192 } else {
193 # Convert strings to Title objects
194 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
195 }
196 if ( !$ret && $exception !== false ) {
197 throw new MWException( "`$title` is not a valid file title." );
198 }
199
200 return $ret;
201 }
202
203 function __get( $name ) {
204 $function = array( $this, 'get' . ucfirst( $name ) );
205 if ( !is_callable( $function ) ) {
206 return null;
207 } else {
208 $this->$name = call_user_func( $function );
209
210 return $this->$name;
211 }
212 }
213
214 /**
215 * Normalize a file extension to the common form, and ensure it's clean.
216 * Extensions with non-alphanumeric characters will be discarded.
217 *
218 * @param string $ext (without the .)
219 * @return string
220 */
221 static function normalizeExtension( $ext ) {
222 $lower = strtolower( $ext );
223 $squish = array(
224 'htm' => 'html',
225 'jpeg' => 'jpg',
226 'mpeg' => 'mpg',
227 'tiff' => 'tif',
228 'ogv' => 'ogg' );
229 if ( isset( $squish[$lower] ) ) {
230 return $squish[$lower];
231 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
232 return $lower;
233 } else {
234 return '';
235 }
236 }
237
238 /**
239 * Checks if file extensions are compatible
240 *
241 * @param File $old Old file
242 * @param string $new New name
243 *
244 * @return bool|null
245 */
246 static function checkExtensionCompatibility( File $old, $new ) {
247 $oldMime = $old->getMimeType();
248 $n = strrpos( $new, '.' );
249 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
250 $mimeMagic = MimeMagic::singleton();
251
252 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
253 }
254
255 /**
256 * Upgrade the database row if there is one
257 * Called by ImagePage
258 * STUB
259 */
260 function upgradeRow() {
261 }
262
263 /**
264 * Split an internet media type into its two components; if not
265 * a two-part name, set the minor type to 'unknown'.
266 *
267 * @param string $mime "text/html" etc
268 * @return array ("text", "html") etc
269 */
270 public static function splitMime( $mime ) {
271 if ( strpos( $mime, '/' ) !== false ) {
272 return explode( '/', $mime, 2 );
273 } else {
274 return array( $mime, 'unknown' );
275 }
276 }
277
278 /**
279 * Callback for usort() to do file sorts by name
280 *
281 * @param File $a
282 * @param File $b
283 * @return int Result of name comparison
284 */
285 public static function compare( File $a, File $b ) {
286 return strcmp( $a->getName(), $b->getName() );
287 }
288
289 /**
290 * Return the name of this file
291 *
292 * @return string
293 */
294 public function getName() {
295 if ( !isset( $this->name ) ) {
296 $this->assertRepoDefined();
297 $this->name = $this->repo->getNameFromTitle( $this->title );
298 }
299
300 return $this->name;
301 }
302
303 /**
304 * Get the file extension, e.g. "svg"
305 *
306 * @return string
307 */
308 function getExtension() {
309 if ( !isset( $this->extension ) ) {
310 $n = strrpos( $this->getName(), '.' );
311 $this->extension = self::normalizeExtension(
312 $n ? substr( $this->getName(), $n + 1 ) : '' );
313 }
314
315 return $this->extension;
316 }
317
318 /**
319 * Return the associated title object
320 *
321 * @return Title
322 */
323 public function getTitle() {
324 return $this->title;
325 }
326
327 /**
328 * Return the title used to find this file
329 *
330 * @return Title
331 */
332 public function getOriginalTitle() {
333 if ( $this->redirected ) {
334 return $this->getRedirectedTitle();
335 }
336
337 return $this->title;
338 }
339
340 /**
341 * Return the URL of the file
342 *
343 * @return string
344 */
345 public function getUrl() {
346 if ( !isset( $this->url ) ) {
347 $this->assertRepoDefined();
348 $ext = $this->getExtension();
349 $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
350 }
351
352 return $this->url;
353 }
354
355 /**
356 * Return a fully-qualified URL to the file.
357 * Upload URL paths _may or may not_ be fully qualified, so
358 * we check. Local paths are assumed to belong on $wgServer.
359 *
360 * @return string
361 */
362 public function getFullUrl() {
363 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
364 }
365
366 /**
367 * @return string
368 */
369 public function getCanonicalUrl() {
370 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
371 }
372
373 /**
374 * @return string
375 */
376 function getViewURL() {
377 if ( $this->mustRender() ) {
378 if ( $this->canRender() ) {
379 return $this->createThumb( $this->getWidth() );
380 } else {
381 wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
382 ' (' . $this->getMimeType() . "), but can't!\n" );
383
384 return $this->getURL(); #hm... return NULL?
385 }
386 } else {
387 return $this->getURL();
388 }
389 }
390
391 /**
392 * Return the storage path to the file. Note that this does
393 * not mean that a file actually exists under that location.
394 *
395 * This path depends on whether directory hashing is active or not,
396 * i.e. whether the files are all found in the same directory,
397 * or in hashed paths like /images/3/3c.
398 *
399 * Most callers don't check the return value, but ForeignAPIFile::getPath
400 * returns false.
401 *
402 * @return string|bool ForeignAPIFile::getPath can return false
403 */
404 public function getPath() {
405 if ( !isset( $this->path ) ) {
406 $this->assertRepoDefined();
407 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
408 }
409
410 return $this->path;
411 }
412
413 /**
414 * Get an FS copy or original of this file and return the path.
415 * Returns false on failure. Callers must not alter the file.
416 * Temporary files are cleared automatically.
417 *
418 * @return string|bool False on failure
419 */
420 public function getLocalRefPath() {
421 $this->assertRepoDefined();
422 if ( !isset( $this->fsFile ) ) {
423 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
424 if ( !$this->fsFile ) {
425 $this->fsFile = false; // null => false; cache negative hits
426 }
427 }
428
429 return ( $this->fsFile )
430 ? $this->fsFile->getPath()
431 : false;
432 }
433
434 /**
435 * Return the width of the image. Returns false if the width is unknown
436 * or undefined.
437 *
438 * STUB
439 * Overridden by LocalFile, UnregisteredLocalFile
440 *
441 * @param int $page
442 * @return int|bool
443 */
444 public function getWidth( $page = 1 ) {
445 return false;
446 }
447
448 /**
449 * Return the height of the image. Returns false if the height is unknown
450 * or undefined
451 *
452 * STUB
453 * Overridden by LocalFile, UnregisteredLocalFile
454 *
455 * @param int $page
456 * @return bool|int False on failure
457 */
458 public function getHeight( $page = 1 ) {
459 return false;
460 }
461
462 /**
463 * Return the smallest bucket from $wgThumbnailBuckets which is at least
464 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
465 * will always be bigger than $desiredWidth.
466 *
467 * @param int $desiredWidth
468 * @param int $page
469 * @return bool|int
470 */
471 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
472 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
473
474 wfDebugLog( 'thumbnail', 'thumbnail buckets ' . json_encode( $wgThumbnailBuckets ) );
475
476 $imageWidth = $this->getWidth( $page );
477
478 if ( $imageWidth === false ) {
479 return false;
480 }
481
482 if ( $desiredWidth > $imageWidth ) {
483 return false;
484 }
485
486 if ( !$wgThumbnailBuckets ) {
487 return false;
488 }
489
490 $sortedBuckets = $wgThumbnailBuckets;
491
492 sort( $sortedBuckets );
493
494 foreach ( $sortedBuckets as $bucket ) {
495 if ( $bucket >= $imageWidth ) {
496 return false;
497 }
498
499 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
500 return $bucket;
501 }
502 }
503
504 // Image is bigger than any available bucket
505 return false;
506 }
507
508 /**
509 * Returns ID or name of user who uploaded the file
510 * STUB
511 *
512 * @param string $type 'text' or 'id'
513 * @return string|int
514 */
515 public function getUser( $type = 'text' ) {
516 return null;
517 }
518
519 /**
520 * Get the duration of a media file in seconds
521 *
522 * @return int
523 */
524 public function getLength() {
525 $handler = $this->getHandler();
526 if ( $handler ) {
527 return $handler->getLength( $this );
528 } else {
529 return 0;
530 }
531 }
532
533 /**
534 * Return true if the file is vectorized
535 *
536 * @return bool
537 */
538 public function isVectorized() {
539 $handler = $this->getHandler();
540 if ( $handler ) {
541 return $handler->isVectorized( $this );
542 } else {
543 return false;
544 }
545 }
546
547 /**
548 * Gives a (possibly empty) list of languages to render
549 * the file in.
550 *
551 * If the file doesn't have translations, or if the file
552 * format does not support that sort of thing, returns
553 * an empty array.
554 *
555 * @return array
556 * @since 1.23
557 */
558 public function getAvailableLanguages() {
559 $handler = $this->getHandler();
560 if ( $handler ) {
561 return $handler->getAvailableLanguages( $this );
562 } else {
563 return array();
564 }
565 }
566
567 /**
568 * In files that support multiple language, what is the default language
569 * to use if none specified.
570 *
571 * @return string Lang code, or null if filetype doesn't support multiple languages.
572 * @since 1.23
573 */
574 public function getDefaultRenderLanguage() {
575 $handler = $this->getHandler();
576 if ( $handler ) {
577 return $handler->getDefaultRenderLanguage( $this );
578 } else {
579 return null;
580 }
581 }
582
583 /**
584 * Will the thumbnail be animated if one would expect it to be.
585 *
586 * Currently used to add a warning to the image description page
587 *
588 * @return bool False if the main image is both animated
589 * and the thumbnail is not. In all other cases must return
590 * true. If image is not renderable whatsoever, should
591 * return true.
592 */
593 public function canAnimateThumbIfAppropriate() {
594 $handler = $this->getHandler();
595 if ( !$handler ) {
596 // We cannot handle image whatsoever, thus
597 // one would not expect it to be animated
598 // so true.
599 return true;
600 } else {
601 if ( $this->allowInlineDisplay()
602 && $handler->isAnimatedImage( $this )
603 && !$handler->canAnimateThumbnail( $this )
604 ) {
605 // Image is animated, but thumbnail isn't.
606 // This is unexpected to the user.
607 return false;
608 } else {
609 // Image is not animated, so one would
610 // not expect thumb to be
611 return true;
612 }
613 }
614 }
615
616 /**
617 * Get handler-specific metadata
618 * Overridden by LocalFile, UnregisteredLocalFile
619 * STUB
620 * @return bool|array
621 */
622 public function getMetadata() {
623 return false;
624 }
625
626 /**
627 * Like getMetadata but returns a handler independent array of common values.
628 * @see MediaHandler::getCommonMetaArray()
629 * @return array|bool Array or false if not supported
630 * @since 1.23
631 */
632 public function getCommonMetaArray() {
633 $handler = $this->getHandler();
634
635 if ( !$handler ) {
636 return false;
637 }
638
639 return $handler->getCommonMetaArray( $this );
640 }
641
642 /**
643 * get versioned metadata
644 *
645 * @param array|string $metadata Array or string of (serialized) metadata
646 * @param int $version Version number.
647 * @return array Array containing metadata, or what was passed to it on fail
648 * (unserializing if not array)
649 */
650 public function convertMetadataVersion( $metadata, $version ) {
651 $handler = $this->getHandler();
652 if ( !is_array( $metadata ) ) {
653 // Just to make the return type consistent
654 $metadata = unserialize( $metadata );
655 }
656 if ( $handler ) {
657 return $handler->convertMetadataVersion( $metadata, $version );
658 } else {
659 return $metadata;
660 }
661 }
662
663 /**
664 * Return the bit depth of the file
665 * Overridden by LocalFile
666 * STUB
667 * @return int
668 */
669 public function getBitDepth() {
670 return 0;
671 }
672
673 /**
674 * Return the size of the image file, in bytes
675 * Overridden by LocalFile, UnregisteredLocalFile
676 * STUB
677 * @return bool
678 */
679 public function getSize() {
680 return false;
681 }
682
683 /**
684 * Returns the MIME type of the file.
685 * Overridden by LocalFile, UnregisteredLocalFile
686 * STUB
687 *
688 * @return string
689 */
690 function getMimeType() {
691 return 'unknown/unknown';
692 }
693
694 /**
695 * Return the type of the media in the file.
696 * Use the value returned by this function with the MEDIATYPE_xxx constants.
697 * Overridden by LocalFile,
698 * STUB
699 * @return string
700 */
701 function getMediaType() {
702 return MEDIATYPE_UNKNOWN;
703 }
704
705 /**
706 * Checks if the output of transform() for this file is likely
707 * to be valid. If this is false, various user elements will
708 * display a placeholder instead.
709 *
710 * Currently, this checks if the file is an image format
711 * that can be converted to a format
712 * supported by all browsers (namely GIF, PNG and JPEG),
713 * or if it is an SVG image and SVG conversion is enabled.
714 *
715 * @return bool
716 */
717 function canRender() {
718 if ( !isset( $this->canRender ) ) {
719 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
720 }
721
722 return $this->canRender;
723 }
724
725 /**
726 * Accessor for __get()
727 * @return bool
728 */
729 protected function getCanRender() {
730 return $this->canRender();
731 }
732
733 /**
734 * Return true if the file is of a type that can't be directly
735 * rendered by typical browsers and needs to be re-rasterized.
736 *
737 * This returns true for everything but the bitmap types
738 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
739 * also return true for any non-image formats.
740 *
741 * @return bool
742 */
743 function mustRender() {
744 return $this->getHandler() && $this->handler->mustRender( $this );
745 }
746
747 /**
748 * Alias for canRender()
749 *
750 * @return bool
751 */
752 function allowInlineDisplay() {
753 return $this->canRender();
754 }
755
756 /**
757 * Determines if this media file is in a format that is unlikely to
758 * contain viruses or malicious content. It uses the global
759 * $wgTrustedMediaFormats list to determine if the file is safe.
760 *
761 * This is used to show a warning on the description page of non-safe files.
762 * It may also be used to disallow direct [[media:...]] links to such files.
763 *
764 * Note that this function will always return true if allowInlineDisplay()
765 * or isTrustedFile() is true for this file.
766 *
767 * @return bool
768 */
769 function isSafeFile() {
770 if ( !isset( $this->isSafeFile ) ) {
771 $this->isSafeFile = $this->getIsSafeFileUncached();
772 }
773
774 return $this->isSafeFile;
775 }
776
777 /**
778 * Accessor for __get()
779 *
780 * @return bool
781 */
782 protected function getIsSafeFile() {
783 return $this->isSafeFile();
784 }
785
786 /**
787 * Uncached accessor
788 *
789 * @return bool
790 */
791 protected function getIsSafeFileUncached() {
792 global $wgTrustedMediaFormats;
793
794 if ( $this->allowInlineDisplay() ) {
795 return true;
796 }
797 if ( $this->isTrustedFile() ) {
798 return true;
799 }
800
801 $type = $this->getMediaType();
802 $mime = $this->getMimeType();
803 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
804
805 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
806 return false; #unknown type, not trusted
807 }
808 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
809 return true;
810 }
811
812 if ( $mime === "unknown/unknown" ) {
813 return false; #unknown type, not trusted
814 }
815 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
816 return true;
817 }
818
819 return false;
820 }
821
822 /**
823 * Returns true if the file is flagged as trusted. Files flagged that way
824 * can be linked to directly, even if that is not allowed for this type of
825 * file normally.
826 *
827 * This is a dummy function right now and always returns false. It could be
828 * implemented to extract a flag from the database. The trusted flag could be
829 * set on upload, if the user has sufficient privileges, to bypass script-
830 * and html-filters. It may even be coupled with cryptographics signatures
831 * or such.
832 *
833 * @return bool
834 */
835 function isTrustedFile() {
836 #this could be implemented to check a flag in the database,
837 #look for signatures, etc
838 return false;
839 }
840
841 /**
842 * Returns true if file exists in the repository.
843 *
844 * Overridden by LocalFile to avoid unnecessary stat calls.
845 *
846 * @return bool Whether file exists in the repository.
847 */
848 public function exists() {
849 return $this->getPath() && $this->repo->fileExists( $this->path );
850 }
851
852 /**
853 * Returns true if file exists in the repository and can be included in a page.
854 * It would be unsafe to include private images, making public thumbnails inadvertently
855 *
856 * @return bool Whether file exists in the repository and is includable.
857 */
858 public function isVisible() {
859 return $this->exists();
860 }
861
862 /**
863 * @return string
864 */
865 function getTransformScript() {
866 if ( !isset( $this->transformScript ) ) {
867 $this->transformScript = false;
868 if ( $this->repo ) {
869 $script = $this->repo->getThumbScriptUrl();
870 if ( $script ) {
871 $this->transformScript = wfAppendQuery( $script, array( 'f' => $this->getName() ) );
872 }
873 }
874 }
875
876 return $this->transformScript;
877 }
878
879 /**
880 * Get a ThumbnailImage which is the same size as the source
881 *
882 * @param array $handlerParams
883 *
884 * @return string
885 */
886 function getUnscaledThumb( $handlerParams = array() ) {
887 $hp =& $handlerParams;
888 $page = isset( $hp['page'] ) ? $hp['page'] : false;
889 $width = $this->getWidth( $page );
890 if ( !$width ) {
891 return $this->iconThumb();
892 }
893 $hp['width'] = $width;
894 // be sure to ignore any height specification as well (bug 62258)
895 unset( $hp['height'] );
896
897 return $this->transform( $hp );
898 }
899
900 /**
901 * Return the file name of a thumbnail with the specified parameters.
902 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
903 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
904 *
905 * @param array $params Handler-specific parameters
906 * @param int $flags Bitfield that supports THUMB_* constants
907 * @return string
908 */
909 public function thumbName( $params, $flags = 0 ) {
910 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
911 ? $this->repo->nameForThumb( $this->getName() )
912 : $this->getName();
913
914 return $this->generateThumbName( $name, $params );
915 }
916
917 /**
918 * Generate a thumbnail file name from a name and specified parameters
919 *
920 * @param string $name
921 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
922 * @return string
923 */
924 public function generateThumbName( $name, $params ) {
925 if ( !$this->getHandler() ) {
926 return null;
927 }
928 $extension = $this->getExtension();
929 list( $thumbExt, ) = $this->getHandler()->getThumbType(
930 $extension, $this->getMimeType(), $params );
931 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $name;
932 if ( $thumbExt != $extension ) {
933 $thumbName .= ".$thumbExt";
934 }
935
936 return $thumbName;
937 }
938
939 /**
940 * Create a thumbnail of the image having the specified width/height.
941 * The thumbnail will not be created if the width is larger than the
942 * image's width. Let the browser do the scaling in this case.
943 * The thumbnail is stored on disk and is only computed if the thumbnail
944 * file does not exist OR if it is older than the image.
945 * Returns the URL.
946 *
947 * Keeps aspect ratio of original image. If both width and height are
948 * specified, the generated image will be no bigger than width x height,
949 * and will also have correct aspect ratio.
950 *
951 * @param int $width Maximum width of the generated thumbnail
952 * @param int $height Maximum height of the image (optional)
953 *
954 * @return string
955 */
956 public function createThumb( $width, $height = -1 ) {
957 $params = array( 'width' => $width );
958 if ( $height != -1 ) {
959 $params['height'] = $height;
960 }
961 $thumb = $this->transform( $params );
962 if ( !$thumb || $thumb->isError() ) {
963 return '';
964 }
965
966 return $thumb->getUrl();
967 }
968
969 /**
970 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
971 *
972 * @param string $thumbPath Thumbnail storage path
973 * @param string $thumbUrl Thumbnail URL
974 * @param array $params
975 * @param int $flags
976 * @return MediaTransformOutput
977 */
978 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
979 global $wgIgnoreImageErrors;
980
981 $handler = $this->getHandler();
982 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
983 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
984 } else {
985 return new MediaTransformError( 'thumbnail_error',
986 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
987 }
988 }
989
990 /**
991 * Transform a media file
992 *
993 * @param array $params An associative array of handler-specific parameters.
994 * Typical keys are width, height and page.
995 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
996 * @return MediaTransformOutput|bool False on failure
997 */
998 function transform( $params, $flags = 0 ) {
999 global $wgThumbnailEpoch;
1000
1001 wfProfileIn( __METHOD__ );
1002 do {
1003 if ( !$this->canRender() ) {
1004 $thumb = $this->iconThumb();
1005 break; // not a bitmap or renderable image, don't try
1006 }
1007
1008 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1009 $descriptionUrl = $this->getDescriptionUrl();
1010 if ( $descriptionUrl ) {
1011 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
1012 }
1013
1014 $handler = $this->getHandler();
1015 $script = $this->getTransformScript();
1016 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1017 // Use a script to transform on client request, if possible
1018 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1019 if ( $thumb ) {
1020 break;
1021 }
1022 }
1023
1024 $normalisedParams = $params;
1025 $handler->normaliseParams( $this, $normalisedParams );
1026
1027 $thumbName = $this->thumbName( $normalisedParams );
1028 $thumbUrl = $this->getThumbUrl( $thumbName );
1029 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1030
1031 if ( $this->repo ) {
1032 // Defer rendering if a 404 handler is set up...
1033 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1034 wfDebug( __METHOD__ . " transformation deferred.\n" );
1035 // XXX: Pass in the storage path even though we are not rendering anything
1036 // and the path is supposed to be an FS path. This is due to getScalerType()
1037 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1038 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1039 break;
1040 }
1041 // Check if an up-to-date thumbnail already exists...
1042 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
1043 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1044 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1045 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1046 // XXX: Pass in the storage path even though we are not rendering anything
1047 // and the path is supposed to be an FS path. This is due to getScalerType()
1048 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1049 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1050 $thumb->setStoragePath( $thumbPath );
1051 break;
1052 }
1053 } elseif ( $flags & self::RENDER_FORCE ) {
1054 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1055 }
1056
1057 // If the backend is ready-only, don't keep generating thumbnails
1058 // only to return transformation errors, just return the error now.
1059 if ( $this->repo->getReadOnlyReason() !== false ) {
1060 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1061 break;
1062 }
1063 }
1064
1065 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1066
1067 if ( !$tmpFile ) {
1068 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1069 } else {
1070 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1071 }
1072 } while ( false );
1073
1074 wfProfileOut( __METHOD__ );
1075
1076 return is_object( $thumb ) ? $thumb : false;
1077 }
1078
1079 /**
1080 * Generates a thumbnail according to the given parameters and saves it to storage
1081 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1082 * @param array $transformParams
1083 * @param int $flags
1084 * @return bool|MediaTransformOutput
1085 */
1086 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1087 global $wgUseSquid, $wgIgnoreImageErrors;
1088
1089 $handler = $this->getHandler();
1090
1091 $normalisedParams = $transformParams;
1092 $handler->normaliseParams( $this, $normalisedParams );
1093
1094 $thumbName = $this->thumbName( $normalisedParams );
1095 $thumbUrl = $this->getThumbUrl( $thumbName );
1096 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1097
1098 $tmpThumbPath = $tmpFile->getPath();
1099
1100 if ( $handler->supportsBucketing() ) {
1101 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1102 }
1103
1104 // Actually render the thumbnail...
1105 wfProfileIn( __METHOD__ . '-doTransform' );
1106 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1107 wfProfileOut( __METHOD__ . '-doTransform' );
1108 $tmpFile->bind( $thumb ); // keep alive with $thumb
1109
1110 if ( !$thumb ) { // bad params?
1111 $thumb = false;
1112 } elseif ( $thumb->isError() ) { // transform error
1113 $this->lastError = $thumb->toText();
1114 // Ignore errors if requested
1115 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1116 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1117 }
1118 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1119 // Copy the thumbnail from the file system into storage...
1120 $disposition = $this->getThumbDisposition( $thumbName );
1121 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1122 if ( $status->isOK() ) {
1123 $thumb->setStoragePath( $thumbPath );
1124 } else {
1125 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1126 }
1127 // Give extensions a chance to do something with this thumbnail...
1128 Hooks::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1129 }
1130
1131 // Purge. Useful in the event of Core -> Squid connection failure or squid
1132 // purge collisions from elsewhere during failure. Don't keep triggering for
1133 // "thumbs" which have the main image URL though (bug 13776)
1134 if ( $wgUseSquid ) {
1135 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
1136 SquidUpdate::purge( array( $thumbUrl ) );
1137 }
1138 }
1139
1140 return $thumb;
1141 }
1142
1143 /**
1144 * Generates chained bucketed thumbnails if needed
1145 * @param array $params
1146 * @param int $flags
1147 * @return bool Whether at least one bucket was generated
1148 */
1149 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1150 if ( !$this->repo
1151 || !isset( $params['physicalWidth'] )
1152 || !isset( $params['physicalHeight'] )
1153 || !( $bucket = $this->getThumbnailBucket( $params['physicalWidth'] ) )
1154 || $bucket == $params['physicalWidth'] ) {
1155 return false;
1156 }
1157
1158 $bucketPath = $this->getBucketThumbPath( $bucket );
1159
1160 if ( $this->repo->fileExists( $bucketPath ) ) {
1161 return false;
1162 }
1163
1164 $params['physicalWidth'] = $bucket;
1165 $params['width'] = $bucket;
1166
1167 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1168
1169 $bucketName = $this->getBucketThumbName( $bucket );
1170
1171 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1172
1173 if ( !$tmpFile ) {
1174 return false;
1175 }
1176
1177 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1178
1179 if ( !$thumb || $thumb->isError() ) {
1180 return false;
1181 }
1182
1183 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1184 // For the caching to work, we need to make the tmp file survive as long as
1185 // this object exists
1186 $tmpFile->bind( $this );
1187
1188 return true;
1189 }
1190
1191 /**
1192 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1193 * @param array $params
1194 * @return array Source path and width/height of the source
1195 */
1196 public function getThumbnailSource( $params ) {
1197 if ( $this->repo
1198 && $this->getHandler()->supportsBucketing()
1199 && isset( $params['physicalWidth'] )
1200 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1201 ) {
1202 if ( $this->getWidth() != 0 ) {
1203 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1204 } else {
1205 $bucketHeight = 0;
1206 }
1207
1208 // Try to avoid reading from storage if the file was generated by this script
1209 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1210 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1211
1212 if ( file_exists( $tmpPath ) ) {
1213 return array(
1214 'path' => $tmpPath,
1215 'width' => $bucket,
1216 'height' => $bucketHeight
1217 );
1218 }
1219 }
1220
1221 $bucketPath = $this->getBucketThumbPath( $bucket );
1222
1223 if ( $this->repo->fileExists( $bucketPath ) ) {
1224 $fsFile = $this->repo->getLocalReference( $bucketPath );
1225
1226 if ( $fsFile ) {
1227 return array(
1228 'path' => $fsFile->getPath(),
1229 'width' => $bucket,
1230 'height' => $bucketHeight
1231 );
1232 }
1233 }
1234 }
1235
1236 // Thumbnailing a very large file could result in network saturation if
1237 // everyone does it at once.
1238 if ( $this->getSize() >= 1e7 ) { // 10MB
1239 $that = $this;
1240 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1241 array(
1242 'doWork' => function () use ( $that ) {
1243 return $that->getLocalRefPath();
1244 }
1245 )
1246 );
1247 $srcPath = $work->execute();
1248 } else {
1249 $srcPath = $this->getLocalRefPath();
1250 }
1251
1252 // Original file
1253 return array(
1254 'path' => $srcPath,
1255 'width' => $this->getWidth(),
1256 'height' => $this->getHeight()
1257 );
1258 }
1259
1260 /**
1261 * Returns the repo path of the thumb for a given bucket
1262 * @param int $bucket
1263 * @return string
1264 */
1265 protected function getBucketThumbPath( $bucket ) {
1266 $thumbName = $this->getBucketThumbName( $bucket );
1267 return $this->getThumbPath( $thumbName );
1268 }
1269
1270 /**
1271 * Returns the name of the thumb for a given bucket
1272 * @param int $bucket
1273 * @return string
1274 */
1275 protected function getBucketThumbName( $bucket ) {
1276 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1277 }
1278
1279 /**
1280 * Creates a temp FS file with the same extension and the thumbnail
1281 * @param string $thumbPath Thumbnail path
1282 * @return TempFSFile
1283 */
1284 protected function makeTransformTmpFile( $thumbPath ) {
1285 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1286 return TempFSFile::factory( 'transform_', $thumbExt );
1287 }
1288
1289 /**
1290 * @param string $thumbName Thumbnail name
1291 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1292 * @return string Content-Disposition header value
1293 */
1294 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1295 $fileName = $this->name; // file name to suggest
1296 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1297 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1298 $fileName .= ".$thumbExt";
1299 }
1300
1301 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1302 }
1303
1304 /**
1305 * Hook into transform() to allow migration of thumbnail files
1306 * STUB
1307 * Overridden by LocalFile
1308 * @param string $thumbName
1309 */
1310 function migrateThumbFile( $thumbName ) {
1311 }
1312
1313 /**
1314 * Get a MediaHandler instance for this file
1315 *
1316 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1317 * or false if none found
1318 */
1319 function getHandler() {
1320 if ( !isset( $this->handler ) ) {
1321 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1322 }
1323
1324 return $this->handler;
1325 }
1326
1327 /**
1328 * Get a ThumbnailImage representing a file type icon
1329 *
1330 * @return ThumbnailImage
1331 */
1332 function iconThumb() {
1333 global $wgResourceBasePath, $IP;
1334 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1335 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1336
1337 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1338 foreach ( $try as $icon ) {
1339 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1340 $params = array( 'width' => 120, 'height' => 120 );
1341
1342 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1343 }
1344 }
1345
1346 return null;
1347 }
1348
1349 /**
1350 * Get last thumbnailing error.
1351 * Largely obsolete.
1352 * @return string
1353 */
1354 function getLastError() {
1355 return $this->lastError;
1356 }
1357
1358 /**
1359 * Get all thumbnail names previously generated for this file
1360 * STUB
1361 * Overridden by LocalFile
1362 * @return array
1363 */
1364 function getThumbnails() {
1365 return array();
1366 }
1367
1368 /**
1369 * Purge shared caches such as thumbnails and DB data caching
1370 * STUB
1371 * Overridden by LocalFile
1372 * @param array $options Options, which include:
1373 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1374 */
1375 function purgeCache( $options = array() ) {
1376 }
1377
1378 /**
1379 * Purge the file description page, but don't go after
1380 * pages using the file. Use when modifying file history
1381 * but not the current data.
1382 */
1383 function purgeDescription() {
1384 $title = $this->getTitle();
1385 if ( $title ) {
1386 $title->invalidateCache();
1387 $title->purgeSquid();
1388 }
1389 }
1390
1391 /**
1392 * Purge metadata and all affected pages when the file is created,
1393 * deleted, or majorly updated.
1394 */
1395 function purgeEverything() {
1396 // Delete thumbnails and refresh file metadata cache
1397 $this->purgeCache();
1398 $this->purgeDescription();
1399
1400 // Purge cache of all pages using this file
1401 $title = $this->getTitle();
1402 if ( $title ) {
1403 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1404 $update->doUpdate();
1405 }
1406 }
1407
1408 /**
1409 * Return a fragment of the history of file.
1410 *
1411 * STUB
1412 * @param int $limit Limit of rows to return
1413 * @param string $start Only revisions older than $start will be returned
1414 * @param string $end Only revisions newer than $end will be returned
1415 * @param bool $inc Include the endpoints of the time range
1416 *
1417 * @return array
1418 */
1419 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1420 return array();
1421 }
1422
1423 /**
1424 * Return the history of this file, line by line. Starts with current version,
1425 * then old versions. Should return an object similar to an image/oldimage
1426 * database row.
1427 *
1428 * STUB
1429 * Overridden in LocalFile
1430 * @return bool
1431 */
1432 public function nextHistoryLine() {
1433 return false;
1434 }
1435
1436 /**
1437 * Reset the history pointer to the first element of the history.
1438 * Always call this function after using nextHistoryLine() to free db resources
1439 * STUB
1440 * Overridden in LocalFile.
1441 */
1442 public function resetHistory() {
1443 }
1444
1445 /**
1446 * Get the filename hash component of the directory including trailing slash,
1447 * e.g. f/fa/
1448 * If the repository is not hashed, returns an empty string.
1449 *
1450 * @return string
1451 */
1452 function getHashPath() {
1453 if ( !isset( $this->hashPath ) ) {
1454 $this->assertRepoDefined();
1455 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1456 }
1457
1458 return $this->hashPath;
1459 }
1460
1461 /**
1462 * Get the path of the file relative to the public zone root.
1463 * This function is overridden in OldLocalFile to be like getArchiveRel().
1464 *
1465 * @return string
1466 */
1467 function getRel() {
1468 return $this->getHashPath() . $this->getName();
1469 }
1470
1471 /**
1472 * Get the path of an archived file relative to the public zone root
1473 *
1474 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1475 *
1476 * @return string
1477 */
1478 function getArchiveRel( $suffix = false ) {
1479 $path = 'archive/' . $this->getHashPath();
1480 if ( $suffix === false ) {
1481 $path = substr( $path, 0, -1 );
1482 } else {
1483 $path .= $suffix;
1484 }
1485
1486 return $path;
1487 }
1488
1489 /**
1490 * Get the path, relative to the thumbnail zone root, of the
1491 * thumbnail directory or a particular file if $suffix is specified
1492 *
1493 * @param bool|string $suffix If not false, the name of a thumbnail file
1494 * @return string
1495 */
1496 function getThumbRel( $suffix = false ) {
1497 $path = $this->getRel();
1498 if ( $suffix !== false ) {
1499 $path .= '/' . $suffix;
1500 }
1501
1502 return $path;
1503 }
1504
1505 /**
1506 * Get urlencoded path of the file relative to the public zone root.
1507 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1508 *
1509 * @return string
1510 */
1511 function getUrlRel() {
1512 return $this->getHashPath() . rawurlencode( $this->getName() );
1513 }
1514
1515 /**
1516 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1517 * or a specific thumb if the $suffix is given.
1518 *
1519 * @param string $archiveName The timestamped name of an archived image
1520 * @param bool|string $suffix If not false, the name of a thumbnail file
1521 * @return string
1522 */
1523 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1524 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1525 if ( $suffix === false ) {
1526 $path = substr( $path, 0, -1 );
1527 } else {
1528 $path .= $suffix;
1529 }
1530
1531 return $path;
1532 }
1533
1534 /**
1535 * Get the path of the archived file.
1536 *
1537 * @param bool|string $suffix If not false, the name of an archived file.
1538 * @return string
1539 */
1540 function getArchivePath( $suffix = false ) {
1541 $this->assertRepoDefined();
1542
1543 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1544 }
1545
1546 /**
1547 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1548 *
1549 * @param string $archiveName The timestamped name of an archived image
1550 * @param bool|string $suffix If not false, the name of a thumbnail file
1551 * @return string
1552 */
1553 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1554 $this->assertRepoDefined();
1555
1556 return $this->repo->getZonePath( 'thumb' ) . '/' .
1557 $this->getArchiveThumbRel( $archiveName, $suffix );
1558 }
1559
1560 /**
1561 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1562 *
1563 * @param bool|string $suffix If not false, the name of a thumbnail file
1564 * @return string
1565 */
1566 function getThumbPath( $suffix = false ) {
1567 $this->assertRepoDefined();
1568
1569 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1570 }
1571
1572 /**
1573 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1574 *
1575 * @param bool|string $suffix If not false, the name of a media file
1576 * @return string
1577 */
1578 function getTranscodedPath( $suffix = false ) {
1579 $this->assertRepoDefined();
1580
1581 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1582 }
1583
1584 /**
1585 * Get the URL of the archive directory, or a particular file if $suffix is specified
1586 *
1587 * @param bool|string $suffix If not false, the name of an archived file
1588 * @return string
1589 */
1590 function getArchiveUrl( $suffix = false ) {
1591 $this->assertRepoDefined();
1592 $ext = $this->getExtension();
1593 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1594 if ( $suffix === false ) {
1595 $path = substr( $path, 0, -1 );
1596 } else {
1597 $path .= rawurlencode( $suffix );
1598 }
1599
1600 return $path;
1601 }
1602
1603 /**
1604 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1605 *
1606 * @param string $archiveName The timestamped name of an archived image
1607 * @param bool|string $suffix If not false, the name of a thumbnail file
1608 * @return string
1609 */
1610 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1611 $this->assertRepoDefined();
1612 $ext = $this->getExtension();
1613 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1614 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1615 if ( $suffix === false ) {
1616 $path = substr( $path, 0, -1 );
1617 } else {
1618 $path .= rawurlencode( $suffix );
1619 }
1620
1621 return $path;
1622 }
1623
1624 /**
1625 * Get the URL of the zone directory, or a particular file if $suffix is specified
1626 *
1627 * @param string $zone Name of requested zone
1628 * @param bool|string $suffix If not false, the name of a file in zone
1629 * @return string Path
1630 */
1631 function getZoneUrl( $zone, $suffix = false ) {
1632 $this->assertRepoDefined();
1633 $ext = $this->getExtension();
1634 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1635 if ( $suffix !== false ) {
1636 $path .= '/' . rawurlencode( $suffix );
1637 }
1638
1639 return $path;
1640 }
1641
1642 /**
1643 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1644 *
1645 * @param bool|string $suffix If not false, the name of a thumbnail file
1646 * @return string Path
1647 */
1648 function getThumbUrl( $suffix = false ) {
1649 return $this->getZoneUrl( 'thumb', $suffix );
1650 }
1651
1652 /**
1653 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1654 *
1655 * @param bool|string $suffix If not false, the name of a media file
1656 * @return string Path
1657 */
1658 function getTranscodedUrl( $suffix = false ) {
1659 return $this->getZoneUrl( 'transcoded', $suffix );
1660 }
1661
1662 /**
1663 * Get the public zone virtual URL for a current version source file
1664 *
1665 * @param bool|string $suffix If not false, the name of a thumbnail file
1666 * @return string
1667 */
1668 function getVirtualUrl( $suffix = false ) {
1669 $this->assertRepoDefined();
1670 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1671 if ( $suffix !== false ) {
1672 $path .= '/' . rawurlencode( $suffix );
1673 }
1674
1675 return $path;
1676 }
1677
1678 /**
1679 * Get the public zone virtual URL for an archived version source file
1680 *
1681 * @param bool|string $suffix If not false, the name of a thumbnail file
1682 * @return string
1683 */
1684 function getArchiveVirtualUrl( $suffix = false ) {
1685 $this->assertRepoDefined();
1686 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1687 if ( $suffix === false ) {
1688 $path = substr( $path, 0, -1 );
1689 } else {
1690 $path .= rawurlencode( $suffix );
1691 }
1692
1693 return $path;
1694 }
1695
1696 /**
1697 * Get the virtual URL for a thumbnail file or directory
1698 *
1699 * @param bool|string $suffix If not false, the name of a thumbnail file
1700 * @return string
1701 */
1702 function getThumbVirtualUrl( $suffix = false ) {
1703 $this->assertRepoDefined();
1704 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1705 if ( $suffix !== false ) {
1706 $path .= '/' . rawurlencode( $suffix );
1707 }
1708
1709 return $path;
1710 }
1711
1712 /**
1713 * @return bool
1714 */
1715 function isHashed() {
1716 $this->assertRepoDefined();
1717
1718 return (bool)$this->repo->getHashLevels();
1719 }
1720
1721 /**
1722 * @throws MWException
1723 */
1724 function readOnlyError() {
1725 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1726 }
1727
1728 /**
1729 * Record a file upload in the upload log and the image table
1730 * STUB
1731 * Overridden by LocalFile
1732 * @param string $oldver
1733 * @param string $desc
1734 * @param string $license
1735 * @param string $copyStatus
1736 * @param string $source
1737 * @param bool $watch
1738 * @param string|bool $timestamp
1739 * @param null|User $user User object or null to use $wgUser
1740 * @return bool
1741 * @throws MWException
1742 */
1743 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1744 $watch = false, $timestamp = false, User $user = null
1745 ) {
1746 $this->readOnlyError();
1747 }
1748
1749 /**
1750 * Move or copy a file to its public location. If a file exists at the
1751 * destination, move it to an archive. Returns a FileRepoStatus object with
1752 * the archive name in the "value" member on success.
1753 *
1754 * The archive name should be passed through to recordUpload for database
1755 * registration.
1756 *
1757 * Options to $options include:
1758 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1759 *
1760 * @param string $srcPath Local filesystem path to the source image
1761 * @param int $flags A bitwise combination of:
1762 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1763 * @param array $options Optional additional parameters
1764 * @return FileRepoStatus On success, the value member contains the
1765 * archive name, or an empty string if it was a new file.
1766 *
1767 * STUB
1768 * Overridden by LocalFile
1769 */
1770 function publish( $srcPath, $flags = 0, array $options = array() ) {
1771 $this->readOnlyError();
1772 }
1773
1774 /**
1775 * @return bool
1776 */
1777 function formatMetadata() {
1778 if ( !$this->getHandler() ) {
1779 return false;
1780 }
1781
1782 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1783 }
1784
1785 /**
1786 * Returns true if the file comes from the local file repository.
1787 *
1788 * @return bool
1789 */
1790 function isLocal() {
1791 return $this->repo && $this->repo->isLocal();
1792 }
1793
1794 /**
1795 * Returns the name of the repository.
1796 *
1797 * @return string
1798 */
1799 function getRepoName() {
1800 return $this->repo ? $this->repo->getName() : 'unknown';
1801 }
1802
1803 /**
1804 * Returns the repository
1805 *
1806 * @return FileRepo|LocalRepo|bool
1807 */
1808 function getRepo() {
1809 return $this->repo;
1810 }
1811
1812 /**
1813 * Returns true if the image is an old version
1814 * STUB
1815 *
1816 * @return bool
1817 */
1818 function isOld() {
1819 return false;
1820 }
1821
1822 /**
1823 * Is this file a "deleted" file in a private archive?
1824 * STUB
1825 *
1826 * @param int $field One of DELETED_* bitfield constants
1827 * @return bool
1828 */
1829 function isDeleted( $field ) {
1830 return false;
1831 }
1832
1833 /**
1834 * Return the deletion bitfield
1835 * STUB
1836 * @return int
1837 */
1838 function getVisibility() {
1839 return 0;
1840 }
1841
1842 /**
1843 * Was this file ever deleted from the wiki?
1844 *
1845 * @return bool
1846 */
1847 function wasDeleted() {
1848 $title = $this->getTitle();
1849
1850 return $title && $title->isDeletedQuick();
1851 }
1852
1853 /**
1854 * Move file to the new title
1855 *
1856 * Move current, old version and all thumbnails
1857 * to the new filename. Old file is deleted.
1858 *
1859 * Cache purging is done; checks for validity
1860 * and logging are caller's responsibility
1861 *
1862 * @param Title $target New file name
1863 * @return FileRepoStatus
1864 */
1865 function move( $target ) {
1866 $this->readOnlyError();
1867 }
1868
1869 /**
1870 * Delete all versions of the file.
1871 *
1872 * Moves the files into an archive directory (or deletes them)
1873 * and removes the database rows.
1874 *
1875 * Cache purging is done; logging is caller's responsibility.
1876 *
1877 * @param string $reason
1878 * @param bool $suppress Hide content from sysops?
1879 * @param User|null $user
1880 * @return bool Boolean on success, false on some kind of failure
1881 * STUB
1882 * Overridden by LocalFile
1883 */
1884 function delete( $reason, $suppress = false, $user = null ) {
1885 $this->readOnlyError();
1886 }
1887
1888 /**
1889 * Restore all or specified deleted revisions to the given file.
1890 * Permissions and logging are left to the caller.
1891 *
1892 * May throw database exceptions on error.
1893 *
1894 * @param array $versions Set of record ids of deleted items to restore,
1895 * or empty to restore all revisions.
1896 * @param bool $unsuppress Remove restrictions on content upon restoration?
1897 * @return int|bool The number of file revisions restored if successful,
1898 * or false on failure
1899 * STUB
1900 * Overridden by LocalFile
1901 */
1902 function restore( $versions = array(), $unsuppress = false ) {
1903 $this->readOnlyError();
1904 }
1905
1906 /**
1907 * Returns 'true' if this file is a type which supports multiple pages,
1908 * e.g. DJVU or PDF. Note that this may be true even if the file in
1909 * question only has a single page.
1910 *
1911 * @return bool
1912 */
1913 function isMultipage() {
1914 return $this->getHandler() && $this->handler->isMultiPage( $this );
1915 }
1916
1917 /**
1918 * Returns the number of pages of a multipage document, or false for
1919 * documents which aren't multipage documents
1920 *
1921 * @return bool|int
1922 */
1923 function pageCount() {
1924 if ( !isset( $this->pageCount ) ) {
1925 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1926 $this->pageCount = $this->handler->pageCount( $this );
1927 } else {
1928 $this->pageCount = false;
1929 }
1930 }
1931
1932 return $this->pageCount;
1933 }
1934
1935 /**
1936 * Calculate the height of a thumbnail using the source and destination width
1937 *
1938 * @param int $srcWidth
1939 * @param int $srcHeight
1940 * @param int $dstWidth
1941 *
1942 * @return int
1943 */
1944 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1945 // Exact integer multiply followed by division
1946 if ( $srcWidth == 0 ) {
1947 return 0;
1948 } else {
1949 return round( $srcHeight * $dstWidth / $srcWidth );
1950 }
1951 }
1952
1953 /**
1954 * Get an image size array like that returned by getImageSize(), or false if it
1955 * can't be determined. Loads the image size directly from the file ignoring caches.
1956 *
1957 * @note Use getWidth()/getHeight() instead of this method unless you have a
1958 * a good reason. This method skips all caches.
1959 *
1960 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1961 * @return array The width, followed by height, with optionally more things after
1962 */
1963 function getImageSize( $filePath ) {
1964 if ( !$this->getHandler() ) {
1965 return false;
1966 }
1967
1968 return $this->getHandler()->getImageSize( $this, $filePath );
1969 }
1970
1971 /**
1972 * Get the URL of the image description page. May return false if it is
1973 * unknown or not applicable.
1974 *
1975 * @return string
1976 */
1977 function getDescriptionUrl() {
1978 if ( $this->repo ) {
1979 return $this->repo->getDescriptionUrl( $this->getName() );
1980 } else {
1981 return false;
1982 }
1983 }
1984
1985 /**
1986 * Get the HTML text of the description page, if available
1987 *
1988 * @param bool|Language $lang Optional language to fetch description in
1989 * @return string
1990 */
1991 function getDescriptionText( $lang = false ) {
1992 global $wgMemc, $wgLang;
1993 if ( !$this->repo || !$this->repo->fetchDescription ) {
1994 return false;
1995 }
1996 if ( !$lang ) {
1997 $lang = $wgLang;
1998 }
1999 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2000 if ( $renderUrl ) {
2001 if ( $this->repo->descriptionCacheExpiry > 0 ) {
2002 wfDebug( "Attempting to get the description from cache..." );
2003 $key = $this->repo->getLocalCacheKey(
2004 'RemoteFileDescription',
2005 'url',
2006 $lang->getCode(),
2007 $this->getName()
2008 );
2009 $obj = $wgMemc->get( $key );
2010 if ( $obj ) {
2011 wfDebug( "success!\n" );
2012
2013 return $obj;
2014 }
2015 wfDebug( "miss\n" );
2016 }
2017 wfDebug( "Fetching shared description from $renderUrl\n" );
2018 $res = Http::get( $renderUrl );
2019 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
2020 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
2021 }
2022
2023 return $res;
2024 } else {
2025 return false;
2026 }
2027 }
2028
2029 /**
2030 * Get description of file revision
2031 * STUB
2032 *
2033 * @param int $audience One of:
2034 * File::FOR_PUBLIC to be displayed to all users
2035 * File::FOR_THIS_USER to be displayed to the given user
2036 * File::RAW get the description regardless of permissions
2037 * @param User $user User object to check for, only if FOR_THIS_USER is
2038 * passed to the $audience parameter
2039 * @return string
2040 */
2041 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2042 return null;
2043 }
2044
2045 /**
2046 * Get the 14-character timestamp of the file upload
2047 *
2048 * @return string|bool TS_MW timestamp or false on failure
2049 */
2050 function getTimestamp() {
2051 $this->assertRepoDefined();
2052
2053 return $this->repo->getFileTimestamp( $this->getPath() );
2054 }
2055
2056 /**
2057 * Get the SHA-1 base 36 hash of the file
2058 *
2059 * @return string
2060 */
2061 function getSha1() {
2062 $this->assertRepoDefined();
2063
2064 return $this->repo->getFileSha1( $this->getPath() );
2065 }
2066
2067 /**
2068 * Get the deletion archive key, "<sha1>.<ext>"
2069 *
2070 * @return string
2071 */
2072 function getStorageKey() {
2073 $hash = $this->getSha1();
2074 if ( !$hash ) {
2075 return false;
2076 }
2077 $ext = $this->getExtension();
2078 $dotExt = $ext === '' ? '' : ".$ext";
2079
2080 return $hash . $dotExt;
2081 }
2082
2083 /**
2084 * Determine if the current user is allowed to view a particular
2085 * field of this file, if it's marked as deleted.
2086 * STUB
2087 * @param int $field
2088 * @param User $user User object to check, or null to use $wgUser
2089 * @return bool
2090 */
2091 function userCan( $field, User $user = null ) {
2092 return true;
2093 }
2094
2095 /**
2096 * @return array HTTP header name/value map to use for HEAD/GET request responses
2097 */
2098 function getStreamHeaders() {
2099 $handler = $this->getHandler();
2100 if ( $handler ) {
2101 return $handler->getStreamHeaders( $this->getMetadata() );
2102 } else {
2103 return array();
2104 }
2105 }
2106
2107 /**
2108 * @return string
2109 */
2110 function getLongDesc() {
2111 $handler = $this->getHandler();
2112 if ( $handler ) {
2113 return $handler->getLongDesc( $this );
2114 } else {
2115 return MediaHandler::getGeneralLongDesc( $this );
2116 }
2117 }
2118
2119 /**
2120 * @return string
2121 */
2122 function getShortDesc() {
2123 $handler = $this->getHandler();
2124 if ( $handler ) {
2125 return $handler->getShortDesc( $this );
2126 } else {
2127 return MediaHandler::getGeneralShortDesc( $this );
2128 }
2129 }
2130
2131 /**
2132 * @return string
2133 */
2134 function getDimensionsString() {
2135 $handler = $this->getHandler();
2136 if ( $handler ) {
2137 return $handler->getDimensionsString( $this );
2138 } else {
2139 return '';
2140 }
2141 }
2142
2143 /**
2144 * @return string
2145 */
2146 function getRedirected() {
2147 return $this->redirected;
2148 }
2149
2150 /**
2151 * @return Title|null
2152 */
2153 function getRedirectedTitle() {
2154 if ( $this->redirected ) {
2155 if ( !$this->redirectTitle ) {
2156 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2157 }
2158
2159 return $this->redirectTitle;
2160 }
2161
2162 return null;
2163 }
2164
2165 /**
2166 * @param string $from
2167 * @return void
2168 */
2169 function redirectedFrom( $from ) {
2170 $this->redirected = $from;
2171 }
2172
2173 /**
2174 * @return bool
2175 */
2176 function isMissing() {
2177 return false;
2178 }
2179
2180 /**
2181 * Check if this file object is small and can be cached
2182 * @return bool
2183 */
2184 public function isCacheable() {
2185 return true;
2186 }
2187
2188 /**
2189 * Assert that $this->repo is set to a valid FileRepo instance
2190 * @throws MWException
2191 */
2192 protected function assertRepoDefined() {
2193 if ( !( $this->repo instanceof $this->repoClass ) ) {
2194 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2195 }
2196 }
2197
2198 /**
2199 * Assert that $this->title is set to a Title
2200 * @throws MWException
2201 */
2202 protected function assertTitleDefined() {
2203 if ( !( $this->title instanceof Title ) ) {
2204 throw new MWException( "A Title object is not set for this File.\n" );
2205 }
2206 }
2207
2208 /**
2209 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2210 * @return bool
2211 */
2212 public function isExpensiveToThumbnail() {
2213 $handler = $this->getHandler();
2214 return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
2215 }
2216 }