Merge "Clean up handling of 'infinity'"
[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 implements IDBAccessObject {
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 $imageWidth = $this->getWidth( $page );
475
476 if ( $imageWidth === false ) {
477 return false;
478 }
479
480 if ( $desiredWidth > $imageWidth ) {
481 return false;
482 }
483
484 if ( !$wgThumbnailBuckets ) {
485 return false;
486 }
487
488 $sortedBuckets = $wgThumbnailBuckets;
489
490 sort( $sortedBuckets );
491
492 foreach ( $sortedBuckets as $bucket ) {
493 if ( $bucket >= $imageWidth ) {
494 return false;
495 }
496
497 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
498 return $bucket;
499 }
500 }
501
502 // Image is bigger than any available bucket
503 return false;
504 }
505
506 /**
507 * Returns ID or name of user who uploaded the file
508 * STUB
509 *
510 * @param string $type 'text' or 'id'
511 * @return string|int
512 */
513 public function getUser( $type = 'text' ) {
514 return null;
515 }
516
517 /**
518 * Get the duration of a media file in seconds
519 *
520 * @return int
521 */
522 public function getLength() {
523 $handler = $this->getHandler();
524 if ( $handler ) {
525 return $handler->getLength( $this );
526 } else {
527 return 0;
528 }
529 }
530
531 /**
532 * Return true if the file is vectorized
533 *
534 * @return bool
535 */
536 public function isVectorized() {
537 $handler = $this->getHandler();
538 if ( $handler ) {
539 return $handler->isVectorized( $this );
540 } else {
541 return false;
542 }
543 }
544
545 /**
546 * Gives a (possibly empty) list of languages to render
547 * the file in.
548 *
549 * If the file doesn't have translations, or if the file
550 * format does not support that sort of thing, returns
551 * an empty array.
552 *
553 * @return array
554 * @since 1.23
555 */
556 public function getAvailableLanguages() {
557 $handler = $this->getHandler();
558 if ( $handler ) {
559 return $handler->getAvailableLanguages( $this );
560 } else {
561 return array();
562 }
563 }
564
565 /**
566 * In files that support multiple language, what is the default language
567 * to use if none specified.
568 *
569 * @return string Lang code, or null if filetype doesn't support multiple languages.
570 * @since 1.23
571 */
572 public function getDefaultRenderLanguage() {
573 $handler = $this->getHandler();
574 if ( $handler ) {
575 return $handler->getDefaultRenderLanguage( $this );
576 } else {
577 return null;
578 }
579 }
580
581 /**
582 * Will the thumbnail be animated if one would expect it to be.
583 *
584 * Currently used to add a warning to the image description page
585 *
586 * @return bool False if the main image is both animated
587 * and the thumbnail is not. In all other cases must return
588 * true. If image is not renderable whatsoever, should
589 * return true.
590 */
591 public function canAnimateThumbIfAppropriate() {
592 $handler = $this->getHandler();
593 if ( !$handler ) {
594 // We cannot handle image whatsoever, thus
595 // one would not expect it to be animated
596 // so true.
597 return true;
598 } else {
599 if ( $this->allowInlineDisplay()
600 && $handler->isAnimatedImage( $this )
601 && !$handler->canAnimateThumbnail( $this )
602 ) {
603 // Image is animated, but thumbnail isn't.
604 // This is unexpected to the user.
605 return false;
606 } else {
607 // Image is not animated, so one would
608 // not expect thumb to be
609 return true;
610 }
611 }
612 }
613
614 /**
615 * Get handler-specific metadata
616 * Overridden by LocalFile, UnregisteredLocalFile
617 * STUB
618 * @return bool|array
619 */
620 public function getMetadata() {
621 return false;
622 }
623
624 /**
625 * Like getMetadata but returns a handler independent array of common values.
626 * @see MediaHandler::getCommonMetaArray()
627 * @return array|bool Array or false if not supported
628 * @since 1.23
629 */
630 public function getCommonMetaArray() {
631 $handler = $this->getHandler();
632
633 if ( !$handler ) {
634 return false;
635 }
636
637 return $handler->getCommonMetaArray( $this );
638 }
639
640 /**
641 * get versioned metadata
642 *
643 * @param array|string $metadata Array or string of (serialized) metadata
644 * @param int $version Version number.
645 * @return array Array containing metadata, or what was passed to it on fail
646 * (unserializing if not array)
647 */
648 public function convertMetadataVersion( $metadata, $version ) {
649 $handler = $this->getHandler();
650 if ( !is_array( $metadata ) ) {
651 // Just to make the return type consistent
652 $metadata = unserialize( $metadata );
653 }
654 if ( $handler ) {
655 return $handler->convertMetadataVersion( $metadata, $version );
656 } else {
657 return $metadata;
658 }
659 }
660
661 /**
662 * Return the bit depth of the file
663 * Overridden by LocalFile
664 * STUB
665 * @return int
666 */
667 public function getBitDepth() {
668 return 0;
669 }
670
671 /**
672 * Return the size of the image file, in bytes
673 * Overridden by LocalFile, UnregisteredLocalFile
674 * STUB
675 * @return bool
676 */
677 public function getSize() {
678 return false;
679 }
680
681 /**
682 * Returns the MIME type of the file.
683 * Overridden by LocalFile, UnregisteredLocalFile
684 * STUB
685 *
686 * @return string
687 */
688 function getMimeType() {
689 return 'unknown/unknown';
690 }
691
692 /**
693 * Return the type of the media in the file.
694 * Use the value returned by this function with the MEDIATYPE_xxx constants.
695 * Overridden by LocalFile,
696 * STUB
697 * @return string
698 */
699 function getMediaType() {
700 return MEDIATYPE_UNKNOWN;
701 }
702
703 /**
704 * Checks if the output of transform() for this file is likely
705 * to be valid. If this is false, various user elements will
706 * display a placeholder instead.
707 *
708 * Currently, this checks if the file is an image format
709 * that can be converted to a format
710 * supported by all browsers (namely GIF, PNG and JPEG),
711 * or if it is an SVG image and SVG conversion is enabled.
712 *
713 * @return bool
714 */
715 function canRender() {
716 if ( !isset( $this->canRender ) ) {
717 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
718 }
719
720 return $this->canRender;
721 }
722
723 /**
724 * Accessor for __get()
725 * @return bool
726 */
727 protected function getCanRender() {
728 return $this->canRender();
729 }
730
731 /**
732 * Return true if the file is of a type that can't be directly
733 * rendered by typical browsers and needs to be re-rasterized.
734 *
735 * This returns true for everything but the bitmap types
736 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
737 * also return true for any non-image formats.
738 *
739 * @return bool
740 */
741 function mustRender() {
742 return $this->getHandler() && $this->handler->mustRender( $this );
743 }
744
745 /**
746 * Alias for canRender()
747 *
748 * @return bool
749 */
750 function allowInlineDisplay() {
751 return $this->canRender();
752 }
753
754 /**
755 * Determines if this media file is in a format that is unlikely to
756 * contain viruses or malicious content. It uses the global
757 * $wgTrustedMediaFormats list to determine if the file is safe.
758 *
759 * This is used to show a warning on the description page of non-safe files.
760 * It may also be used to disallow direct [[media:...]] links to such files.
761 *
762 * Note that this function will always return true if allowInlineDisplay()
763 * or isTrustedFile() is true for this file.
764 *
765 * @return bool
766 */
767 function isSafeFile() {
768 if ( !isset( $this->isSafeFile ) ) {
769 $this->isSafeFile = $this->getIsSafeFileUncached();
770 }
771
772 return $this->isSafeFile;
773 }
774
775 /**
776 * Accessor for __get()
777 *
778 * @return bool
779 */
780 protected function getIsSafeFile() {
781 return $this->isSafeFile();
782 }
783
784 /**
785 * Uncached accessor
786 *
787 * @return bool
788 */
789 protected function getIsSafeFileUncached() {
790 global $wgTrustedMediaFormats;
791
792 if ( $this->allowInlineDisplay() ) {
793 return true;
794 }
795 if ( $this->isTrustedFile() ) {
796 return true;
797 }
798
799 $type = $this->getMediaType();
800 $mime = $this->getMimeType();
801 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
802
803 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
804 return false; #unknown type, not trusted
805 }
806 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
807 return true;
808 }
809
810 if ( $mime === "unknown/unknown" ) {
811 return false; #unknown type, not trusted
812 }
813 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
814 return true;
815 }
816
817 return false;
818 }
819
820 /**
821 * Returns true if the file is flagged as trusted. Files flagged that way
822 * can be linked to directly, even if that is not allowed for this type of
823 * file normally.
824 *
825 * This is a dummy function right now and always returns false. It could be
826 * implemented to extract a flag from the database. The trusted flag could be
827 * set on upload, if the user has sufficient privileges, to bypass script-
828 * and html-filters. It may even be coupled with cryptographics signatures
829 * or such.
830 *
831 * @return bool
832 */
833 function isTrustedFile() {
834 #this could be implemented to check a flag in the database,
835 #look for signatures, etc
836 return false;
837 }
838
839 /**
840 * Load any lazy-loaded file object fields from source
841 *
842 * This is only useful when setting $flags
843 *
844 * Overridden by LocalFile to actually query the DB
845 *
846 * @param integer $flags Bitfield of File::READ_* constants
847 */
848 public function load( $flags = 0 ) {
849 }
850
851 /**
852 * Returns true if file exists in the repository.
853 *
854 * Overridden by LocalFile to avoid unnecessary stat calls.
855 *
856 * @return bool Whether file exists in the repository.
857 */
858 public function exists() {
859 return $this->getPath() && $this->repo->fileExists( $this->path );
860 }
861
862 /**
863 * Returns true if file exists in the repository and can be included in a page.
864 * It would be unsafe to include private images, making public thumbnails inadvertently
865 *
866 * @return bool Whether file exists in the repository and is includable.
867 */
868 public function isVisible() {
869 return $this->exists();
870 }
871
872 /**
873 * @return string
874 */
875 function getTransformScript() {
876 if ( !isset( $this->transformScript ) ) {
877 $this->transformScript = false;
878 if ( $this->repo ) {
879 $script = $this->repo->getThumbScriptUrl();
880 if ( $script ) {
881 $this->transformScript = wfAppendQuery( $script, array( 'f' => $this->getName() ) );
882 }
883 }
884 }
885
886 return $this->transformScript;
887 }
888
889 /**
890 * Get a ThumbnailImage which is the same size as the source
891 *
892 * @param array $handlerParams
893 *
894 * @return string
895 */
896 function getUnscaledThumb( $handlerParams = array() ) {
897 $hp =& $handlerParams;
898 $page = isset( $hp['page'] ) ? $hp['page'] : false;
899 $width = $this->getWidth( $page );
900 if ( !$width ) {
901 return $this->iconThumb();
902 }
903 $hp['width'] = $width;
904 // be sure to ignore any height specification as well (bug 62258)
905 unset( $hp['height'] );
906
907 return $this->transform( $hp );
908 }
909
910 /**
911 * Return the file name of a thumbnail with the specified parameters.
912 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
913 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
914 *
915 * @param array $params Handler-specific parameters
916 * @param int $flags Bitfield that supports THUMB_* constants
917 * @return string
918 */
919 public function thumbName( $params, $flags = 0 ) {
920 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
921 ? $this->repo->nameForThumb( $this->getName() )
922 : $this->getName();
923
924 return $this->generateThumbName( $name, $params );
925 }
926
927 /**
928 * Generate a thumbnail file name from a name and specified parameters
929 *
930 * @param string $name
931 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
932 * @return string
933 */
934 public function generateThumbName( $name, $params ) {
935 if ( !$this->getHandler() ) {
936 return null;
937 }
938 $extension = $this->getExtension();
939 list( $thumbExt, ) = $this->getHandler()->getThumbType(
940 $extension, $this->getMimeType(), $params );
941 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $name;
942 if ( $thumbExt != $extension ) {
943 $thumbName .= ".$thumbExt";
944 }
945
946 return $thumbName;
947 }
948
949 /**
950 * Create a thumbnail of the image having the specified width/height.
951 * The thumbnail will not be created if the width is larger than the
952 * image's width. Let the browser do the scaling in this case.
953 * The thumbnail is stored on disk and is only computed if the thumbnail
954 * file does not exist OR if it is older than the image.
955 * Returns the URL.
956 *
957 * Keeps aspect ratio of original image. If both width and height are
958 * specified, the generated image will be no bigger than width x height,
959 * and will also have correct aspect ratio.
960 *
961 * @param int $width Maximum width of the generated thumbnail
962 * @param int $height Maximum height of the image (optional)
963 *
964 * @return string
965 */
966 public function createThumb( $width, $height = -1 ) {
967 $params = array( 'width' => $width );
968 if ( $height != -1 ) {
969 $params['height'] = $height;
970 }
971 $thumb = $this->transform( $params );
972 if ( !$thumb || $thumb->isError() ) {
973 return '';
974 }
975
976 return $thumb->getUrl();
977 }
978
979 /**
980 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
981 *
982 * @param string $thumbPath Thumbnail storage path
983 * @param string $thumbUrl Thumbnail URL
984 * @param array $params
985 * @param int $flags
986 * @return MediaTransformOutput
987 */
988 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
989 global $wgIgnoreImageErrors;
990
991 $handler = $this->getHandler();
992 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
993 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
994 } else {
995 return new MediaTransformError( 'thumbnail_error',
996 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
997 }
998 }
999
1000 /**
1001 * Transform a media file
1002 *
1003 * @param array $params An associative array of handler-specific parameters.
1004 * Typical keys are width, height and page.
1005 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1006 * @return MediaTransformOutput|bool False on failure
1007 */
1008 function transform( $params, $flags = 0 ) {
1009 global $wgThumbnailEpoch;
1010
1011 do {
1012 if ( !$this->canRender() ) {
1013 $thumb = $this->iconThumb();
1014 break; // not a bitmap or renderable image, don't try
1015 }
1016
1017 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1018 $descriptionUrl = $this->getDescriptionUrl();
1019 if ( $descriptionUrl ) {
1020 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
1021 }
1022
1023 $handler = $this->getHandler();
1024 $script = $this->getTransformScript();
1025 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1026 // Use a script to transform on client request, if possible
1027 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1028 if ( $thumb ) {
1029 break;
1030 }
1031 }
1032
1033 $normalisedParams = $params;
1034 $handler->normaliseParams( $this, $normalisedParams );
1035
1036 $thumbName = $this->thumbName( $normalisedParams );
1037 $thumbUrl = $this->getThumbUrl( $thumbName );
1038 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1039
1040 if ( $this->repo ) {
1041 // Defer rendering if a 404 handler is set up...
1042 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1043 wfDebug( __METHOD__ . " transformation deferred.\n" );
1044 // XXX: Pass in the storage path even though we are not rendering anything
1045 // and the path is supposed to be an FS path. This is due to getScalerType()
1046 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1047 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1048 break;
1049 }
1050 // Check if an up-to-date thumbnail already exists...
1051 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
1052 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1053 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1054 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1055 // XXX: Pass in the storage path even though we are not rendering anything
1056 // and the path is supposed to be an FS path. This is due to getScalerType()
1057 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1058 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1059 $thumb->setStoragePath( $thumbPath );
1060 break;
1061 }
1062 } elseif ( $flags & self::RENDER_FORCE ) {
1063 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1064 }
1065
1066 // If the backend is ready-only, don't keep generating thumbnails
1067 // only to return transformation errors, just return the error now.
1068 if ( $this->repo->getReadOnlyReason() !== false ) {
1069 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1070 break;
1071 }
1072 }
1073
1074 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1075
1076 if ( !$tmpFile ) {
1077 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1078 } else {
1079 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1080 }
1081 } while ( false );
1082
1083 return is_object( $thumb ) ? $thumb : false;
1084 }
1085
1086 /**
1087 * Generates a thumbnail according to the given parameters and saves it to storage
1088 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1089 * @param array $transformParams
1090 * @param int $flags
1091 * @return bool|MediaTransformOutput
1092 */
1093 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1094 global $wgUseSquid, $wgIgnoreImageErrors;
1095
1096 $handler = $this->getHandler();
1097
1098 $normalisedParams = $transformParams;
1099 $handler->normaliseParams( $this, $normalisedParams );
1100
1101 $thumbName = $this->thumbName( $normalisedParams );
1102 $thumbUrl = $this->getThumbUrl( $thumbName );
1103 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1104
1105 $tmpThumbPath = $tmpFile->getPath();
1106
1107 if ( $handler->supportsBucketing() ) {
1108 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1109 }
1110
1111 // Actually render the thumbnail...
1112 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1113 $tmpFile->bind( $thumb ); // keep alive with $thumb
1114
1115 if ( !$thumb ) { // bad params?
1116 $thumb = false;
1117 } elseif ( $thumb->isError() ) { // transform error
1118 $this->lastError = $thumb->toText();
1119 // Ignore errors if requested
1120 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1121 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1122 }
1123 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1124 // Copy the thumbnail from the file system into storage...
1125 $disposition = $this->getThumbDisposition( $thumbName );
1126 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1127 if ( $status->isOK() ) {
1128 $thumb->setStoragePath( $thumbPath );
1129 } else {
1130 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1131 }
1132 // Give extensions a chance to do something with this thumbnail...
1133 Hooks::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1134 }
1135
1136 // Purge. Useful in the event of Core -> Squid connection failure or squid
1137 // purge collisions from elsewhere during failure. Don't keep triggering for
1138 // "thumbs" which have the main image URL though (bug 13776)
1139 if ( $wgUseSquid ) {
1140 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
1141 SquidUpdate::purge( array( $thumbUrl ) );
1142 }
1143 }
1144
1145 return $thumb;
1146 }
1147
1148 /**
1149 * Generates chained bucketed thumbnails if needed
1150 * @param array $params
1151 * @param int $flags
1152 * @return bool Whether at least one bucket was generated
1153 */
1154 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1155 if ( !$this->repo
1156 || !isset( $params['physicalWidth'] )
1157 || !isset( $params['physicalHeight'] )
1158 || !( $bucket = $this->getThumbnailBucket( $params['physicalWidth'] ) )
1159 || $bucket == $params['physicalWidth'] ) {
1160 return false;
1161 }
1162
1163 $bucketPath = $this->getBucketThumbPath( $bucket );
1164
1165 if ( $this->repo->fileExists( $bucketPath ) ) {
1166 return false;
1167 }
1168
1169 $params['physicalWidth'] = $bucket;
1170 $params['width'] = $bucket;
1171
1172 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1173
1174 $bucketName = $this->getBucketThumbName( $bucket );
1175
1176 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1177
1178 if ( !$tmpFile ) {
1179 return false;
1180 }
1181
1182 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1183
1184 if ( !$thumb || $thumb->isError() ) {
1185 return false;
1186 }
1187
1188 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1189 // For the caching to work, we need to make the tmp file survive as long as
1190 // this object exists
1191 $tmpFile->bind( $this );
1192
1193 return true;
1194 }
1195
1196 /**
1197 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1198 * @param array $params
1199 * @return array Source path and width/height of the source
1200 */
1201 public function getThumbnailSource( $params ) {
1202 if ( $this->repo
1203 && $this->getHandler()->supportsBucketing()
1204 && isset( $params['physicalWidth'] )
1205 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1206 ) {
1207 if ( $this->getWidth() != 0 ) {
1208 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1209 } else {
1210 $bucketHeight = 0;
1211 }
1212
1213 // Try to avoid reading from storage if the file was generated by this script
1214 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1215 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1216
1217 if ( file_exists( $tmpPath ) ) {
1218 return array(
1219 'path' => $tmpPath,
1220 'width' => $bucket,
1221 'height' => $bucketHeight
1222 );
1223 }
1224 }
1225
1226 $bucketPath = $this->getBucketThumbPath( $bucket );
1227
1228 if ( $this->repo->fileExists( $bucketPath ) ) {
1229 $fsFile = $this->repo->getLocalReference( $bucketPath );
1230
1231 if ( $fsFile ) {
1232 return array(
1233 'path' => $fsFile->getPath(),
1234 'width' => $bucket,
1235 'height' => $bucketHeight
1236 );
1237 }
1238 }
1239 }
1240
1241 // Thumbnailing a very large file could result in network saturation if
1242 // everyone does it at once.
1243 if ( $this->getSize() >= 1e7 ) { // 10MB
1244 $that = $this;
1245 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1246 array(
1247 'doWork' => function () use ( $that ) {
1248 return $that->getLocalRefPath();
1249 }
1250 )
1251 );
1252 $srcPath = $work->execute();
1253 } else {
1254 $srcPath = $this->getLocalRefPath();
1255 }
1256
1257 // Original file
1258 return array(
1259 'path' => $srcPath,
1260 'width' => $this->getWidth(),
1261 'height' => $this->getHeight()
1262 );
1263 }
1264
1265 /**
1266 * Returns the repo path of the thumb for a given bucket
1267 * @param int $bucket
1268 * @return string
1269 */
1270 protected function getBucketThumbPath( $bucket ) {
1271 $thumbName = $this->getBucketThumbName( $bucket );
1272 return $this->getThumbPath( $thumbName );
1273 }
1274
1275 /**
1276 * Returns the name of the thumb for a given bucket
1277 * @param int $bucket
1278 * @return string
1279 */
1280 protected function getBucketThumbName( $bucket ) {
1281 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1282 }
1283
1284 /**
1285 * Creates a temp FS file with the same extension and the thumbnail
1286 * @param string $thumbPath Thumbnail path
1287 * @return TempFSFile
1288 */
1289 protected function makeTransformTmpFile( $thumbPath ) {
1290 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1291 return TempFSFile::factory( 'transform_', $thumbExt );
1292 }
1293
1294 /**
1295 * @param string $thumbName Thumbnail name
1296 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1297 * @return string Content-Disposition header value
1298 */
1299 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1300 $fileName = $this->name; // file name to suggest
1301 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1302 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1303 $fileName .= ".$thumbExt";
1304 }
1305
1306 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1307 }
1308
1309 /**
1310 * Hook into transform() to allow migration of thumbnail files
1311 * STUB
1312 * Overridden by LocalFile
1313 * @param string $thumbName
1314 */
1315 function migrateThumbFile( $thumbName ) {
1316 }
1317
1318 /**
1319 * Get a MediaHandler instance for this file
1320 *
1321 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1322 * or false if none found
1323 */
1324 function getHandler() {
1325 if ( !isset( $this->handler ) ) {
1326 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1327 }
1328
1329 return $this->handler;
1330 }
1331
1332 /**
1333 * Get a ThumbnailImage representing a file type icon
1334 *
1335 * @return ThumbnailImage
1336 */
1337 function iconThumb() {
1338 global $wgResourceBasePath, $IP;
1339 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1340 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1341
1342 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1343 foreach ( $try as $icon ) {
1344 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1345 $params = array( 'width' => 120, 'height' => 120 );
1346
1347 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1348 }
1349 }
1350
1351 return null;
1352 }
1353
1354 /**
1355 * Get last thumbnailing error.
1356 * Largely obsolete.
1357 * @return string
1358 */
1359 function getLastError() {
1360 return $this->lastError;
1361 }
1362
1363 /**
1364 * Get all thumbnail names previously generated for this file
1365 * STUB
1366 * Overridden by LocalFile
1367 * @return array
1368 */
1369 function getThumbnails() {
1370 return array();
1371 }
1372
1373 /**
1374 * Purge shared caches such as thumbnails and DB data caching
1375 * STUB
1376 * Overridden by LocalFile
1377 * @param array $options Options, which include:
1378 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1379 */
1380 function purgeCache( $options = array() ) {
1381 }
1382
1383 /**
1384 * Purge the file description page, but don't go after
1385 * pages using the file. Use when modifying file history
1386 * but not the current data.
1387 */
1388 function purgeDescription() {
1389 $title = $this->getTitle();
1390 if ( $title ) {
1391 $title->invalidateCache();
1392 $title->purgeSquid();
1393 }
1394 }
1395
1396 /**
1397 * Purge metadata and all affected pages when the file is created,
1398 * deleted, or majorly updated.
1399 */
1400 function purgeEverything() {
1401 // Delete thumbnails and refresh file metadata cache
1402 $this->purgeCache();
1403 $this->purgeDescription();
1404
1405 // Purge cache of all pages using this file
1406 $title = $this->getTitle();
1407 if ( $title ) {
1408 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1409 $update->doUpdate();
1410 }
1411 }
1412
1413 /**
1414 * Return a fragment of the history of file.
1415 *
1416 * STUB
1417 * @param int $limit Limit of rows to return
1418 * @param string $start Only revisions older than $start will be returned
1419 * @param string $end Only revisions newer than $end will be returned
1420 * @param bool $inc Include the endpoints of the time range
1421 *
1422 * @return array
1423 */
1424 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1425 return array();
1426 }
1427
1428 /**
1429 * Return the history of this file, line by line. Starts with current version,
1430 * then old versions. Should return an object similar to an image/oldimage
1431 * database row.
1432 *
1433 * STUB
1434 * Overridden in LocalFile
1435 * @return bool
1436 */
1437 public function nextHistoryLine() {
1438 return false;
1439 }
1440
1441 /**
1442 * Reset the history pointer to the first element of the history.
1443 * Always call this function after using nextHistoryLine() to free db resources
1444 * STUB
1445 * Overridden in LocalFile.
1446 */
1447 public function resetHistory() {
1448 }
1449
1450 /**
1451 * Get the filename hash component of the directory including trailing slash,
1452 * e.g. f/fa/
1453 * If the repository is not hashed, returns an empty string.
1454 *
1455 * @return string
1456 */
1457 function getHashPath() {
1458 if ( !isset( $this->hashPath ) ) {
1459 $this->assertRepoDefined();
1460 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1461 }
1462
1463 return $this->hashPath;
1464 }
1465
1466 /**
1467 * Get the path of the file relative to the public zone root.
1468 * This function is overridden in OldLocalFile to be like getArchiveRel().
1469 *
1470 * @return string
1471 */
1472 function getRel() {
1473 return $this->getHashPath() . $this->getName();
1474 }
1475
1476 /**
1477 * Get the path of an archived file relative to the public zone root
1478 *
1479 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1480 *
1481 * @return string
1482 */
1483 function getArchiveRel( $suffix = false ) {
1484 $path = 'archive/' . $this->getHashPath();
1485 if ( $suffix === false ) {
1486 $path = substr( $path, 0, -1 );
1487 } else {
1488 $path .= $suffix;
1489 }
1490
1491 return $path;
1492 }
1493
1494 /**
1495 * Get the path, relative to the thumbnail zone root, of the
1496 * thumbnail directory or a particular file if $suffix is specified
1497 *
1498 * @param bool|string $suffix If not false, the name of a thumbnail file
1499 * @return string
1500 */
1501 function getThumbRel( $suffix = false ) {
1502 $path = $this->getRel();
1503 if ( $suffix !== false ) {
1504 $path .= '/' . $suffix;
1505 }
1506
1507 return $path;
1508 }
1509
1510 /**
1511 * Get urlencoded path of the file relative to the public zone root.
1512 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1513 *
1514 * @return string
1515 */
1516 function getUrlRel() {
1517 return $this->getHashPath() . rawurlencode( $this->getName() );
1518 }
1519
1520 /**
1521 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1522 * or a specific thumb if the $suffix is given.
1523 *
1524 * @param string $archiveName The timestamped name of an archived image
1525 * @param bool|string $suffix If not false, the name of a thumbnail file
1526 * @return string
1527 */
1528 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1529 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1530 if ( $suffix === false ) {
1531 $path = substr( $path, 0, -1 );
1532 } else {
1533 $path .= $suffix;
1534 }
1535
1536 return $path;
1537 }
1538
1539 /**
1540 * Get the path of the archived file.
1541 *
1542 * @param bool|string $suffix If not false, the name of an archived file.
1543 * @return string
1544 */
1545 function getArchivePath( $suffix = false ) {
1546 $this->assertRepoDefined();
1547
1548 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1549 }
1550
1551 /**
1552 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1553 *
1554 * @param string $archiveName The timestamped name of an archived image
1555 * @param bool|string $suffix If not false, the name of a thumbnail file
1556 * @return string
1557 */
1558 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1559 $this->assertRepoDefined();
1560
1561 return $this->repo->getZonePath( 'thumb' ) . '/' .
1562 $this->getArchiveThumbRel( $archiveName, $suffix );
1563 }
1564
1565 /**
1566 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1567 *
1568 * @param bool|string $suffix If not false, the name of a thumbnail file
1569 * @return string
1570 */
1571 function getThumbPath( $suffix = false ) {
1572 $this->assertRepoDefined();
1573
1574 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1575 }
1576
1577 /**
1578 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1579 *
1580 * @param bool|string $suffix If not false, the name of a media file
1581 * @return string
1582 */
1583 function getTranscodedPath( $suffix = false ) {
1584 $this->assertRepoDefined();
1585
1586 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1587 }
1588
1589 /**
1590 * Get the URL of the archive directory, or a particular file if $suffix is specified
1591 *
1592 * @param bool|string $suffix If not false, the name of an archived file
1593 * @return string
1594 */
1595 function getArchiveUrl( $suffix = false ) {
1596 $this->assertRepoDefined();
1597 $ext = $this->getExtension();
1598 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1599 if ( $suffix === false ) {
1600 $path = substr( $path, 0, -1 );
1601 } else {
1602 $path .= rawurlencode( $suffix );
1603 }
1604
1605 return $path;
1606 }
1607
1608 /**
1609 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1610 *
1611 * @param string $archiveName The timestamped name of an archived image
1612 * @param bool|string $suffix If not false, the name of a thumbnail file
1613 * @return string
1614 */
1615 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1616 $this->assertRepoDefined();
1617 $ext = $this->getExtension();
1618 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1619 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1620 if ( $suffix === false ) {
1621 $path = substr( $path, 0, -1 );
1622 } else {
1623 $path .= rawurlencode( $suffix );
1624 }
1625
1626 return $path;
1627 }
1628
1629 /**
1630 * Get the URL of the zone directory, or a particular file if $suffix is specified
1631 *
1632 * @param string $zone Name of requested zone
1633 * @param bool|string $suffix If not false, the name of a file in zone
1634 * @return string Path
1635 */
1636 function getZoneUrl( $zone, $suffix = false ) {
1637 $this->assertRepoDefined();
1638 $ext = $this->getExtension();
1639 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1640 if ( $suffix !== false ) {
1641 $path .= '/' . rawurlencode( $suffix );
1642 }
1643
1644 return $path;
1645 }
1646
1647 /**
1648 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1649 *
1650 * @param bool|string $suffix If not false, the name of a thumbnail file
1651 * @return string Path
1652 */
1653 function getThumbUrl( $suffix = false ) {
1654 return $this->getZoneUrl( 'thumb', $suffix );
1655 }
1656
1657 /**
1658 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1659 *
1660 * @param bool|string $suffix If not false, the name of a media file
1661 * @return string Path
1662 */
1663 function getTranscodedUrl( $suffix = false ) {
1664 return $this->getZoneUrl( 'transcoded', $suffix );
1665 }
1666
1667 /**
1668 * Get the public zone virtual URL for a current version source file
1669 *
1670 * @param bool|string $suffix If not false, the name of a thumbnail file
1671 * @return string
1672 */
1673 function getVirtualUrl( $suffix = false ) {
1674 $this->assertRepoDefined();
1675 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1676 if ( $suffix !== false ) {
1677 $path .= '/' . rawurlencode( $suffix );
1678 }
1679
1680 return $path;
1681 }
1682
1683 /**
1684 * Get the public zone virtual URL for an archived version source file
1685 *
1686 * @param bool|string $suffix If not false, the name of a thumbnail file
1687 * @return string
1688 */
1689 function getArchiveVirtualUrl( $suffix = false ) {
1690 $this->assertRepoDefined();
1691 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1692 if ( $suffix === false ) {
1693 $path = substr( $path, 0, -1 );
1694 } else {
1695 $path .= rawurlencode( $suffix );
1696 }
1697
1698 return $path;
1699 }
1700
1701 /**
1702 * Get the virtual URL for a thumbnail file or directory
1703 *
1704 * @param bool|string $suffix If not false, the name of a thumbnail file
1705 * @return string
1706 */
1707 function getThumbVirtualUrl( $suffix = false ) {
1708 $this->assertRepoDefined();
1709 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1710 if ( $suffix !== false ) {
1711 $path .= '/' . rawurlencode( $suffix );
1712 }
1713
1714 return $path;
1715 }
1716
1717 /**
1718 * @return bool
1719 */
1720 function isHashed() {
1721 $this->assertRepoDefined();
1722
1723 return (bool)$this->repo->getHashLevels();
1724 }
1725
1726 /**
1727 * @throws MWException
1728 */
1729 function readOnlyError() {
1730 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1731 }
1732
1733 /**
1734 * Record a file upload in the upload log and the image table
1735 * STUB
1736 * Overridden by LocalFile
1737 * @param string $oldver
1738 * @param string $desc
1739 * @param string $license
1740 * @param string $copyStatus
1741 * @param string $source
1742 * @param bool $watch
1743 * @param string|bool $timestamp
1744 * @param null|User $user User object or null to use $wgUser
1745 * @return bool
1746 * @throws MWException
1747 */
1748 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1749 $watch = false, $timestamp = false, User $user = null
1750 ) {
1751 $this->readOnlyError();
1752 }
1753
1754 /**
1755 * Move or copy a file to its public location. If a file exists at the
1756 * destination, move it to an archive. Returns a FileRepoStatus object with
1757 * the archive name in the "value" member on success.
1758 *
1759 * The archive name should be passed through to recordUpload for database
1760 * registration.
1761 *
1762 * Options to $options include:
1763 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1764 *
1765 * @param string $srcPath Local filesystem path to the source image
1766 * @param int $flags A bitwise combination of:
1767 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1768 * @param array $options Optional additional parameters
1769 * @return FileRepoStatus On success, the value member contains the
1770 * archive name, or an empty string if it was a new file.
1771 *
1772 * STUB
1773 * Overridden by LocalFile
1774 */
1775 function publish( $srcPath, $flags = 0, array $options = array() ) {
1776 $this->readOnlyError();
1777 }
1778
1779 /**
1780 * @param bool|IContextSource $context Context to use (optional)
1781 * @return bool
1782 */
1783 function formatMetadata( $context = false ) {
1784 if ( !$this->getHandler() ) {
1785 return false;
1786 }
1787
1788 return $this->getHandler()->formatMetadata( $this, $context );
1789 }
1790
1791 /**
1792 * Returns true if the file comes from the local file repository.
1793 *
1794 * @return bool
1795 */
1796 function isLocal() {
1797 return $this->repo && $this->repo->isLocal();
1798 }
1799
1800 /**
1801 * Returns the name of the repository.
1802 *
1803 * @return string
1804 */
1805 function getRepoName() {
1806 return $this->repo ? $this->repo->getName() : 'unknown';
1807 }
1808
1809 /**
1810 * Returns the repository
1811 *
1812 * @return FileRepo|LocalRepo|bool
1813 */
1814 function getRepo() {
1815 return $this->repo;
1816 }
1817
1818 /**
1819 * Returns true if the image is an old version
1820 * STUB
1821 *
1822 * @return bool
1823 */
1824 function isOld() {
1825 return false;
1826 }
1827
1828 /**
1829 * Is this file a "deleted" file in a private archive?
1830 * STUB
1831 *
1832 * @param int $field One of DELETED_* bitfield constants
1833 * @return bool
1834 */
1835 function isDeleted( $field ) {
1836 return false;
1837 }
1838
1839 /**
1840 * Return the deletion bitfield
1841 * STUB
1842 * @return int
1843 */
1844 function getVisibility() {
1845 return 0;
1846 }
1847
1848 /**
1849 * Was this file ever deleted from the wiki?
1850 *
1851 * @return bool
1852 */
1853 function wasDeleted() {
1854 $title = $this->getTitle();
1855
1856 return $title && $title->isDeletedQuick();
1857 }
1858
1859 /**
1860 * Move file to the new title
1861 *
1862 * Move current, old version and all thumbnails
1863 * to the new filename. Old file is deleted.
1864 *
1865 * Cache purging is done; checks for validity
1866 * and logging are caller's responsibility
1867 *
1868 * @param Title $target New file name
1869 * @return FileRepoStatus
1870 */
1871 function move( $target ) {
1872 $this->readOnlyError();
1873 }
1874
1875 /**
1876 * Delete all versions of the file.
1877 *
1878 * Moves the files into an archive directory (or deletes them)
1879 * and removes the database rows.
1880 *
1881 * Cache purging is done; logging is caller's responsibility.
1882 *
1883 * @param string $reason
1884 * @param bool $suppress Hide content from sysops?
1885 * @param User|null $user
1886 * @return bool Boolean on success, false on some kind of failure
1887 * STUB
1888 * Overridden by LocalFile
1889 */
1890 function delete( $reason, $suppress = false, $user = null ) {
1891 $this->readOnlyError();
1892 }
1893
1894 /**
1895 * Restore all or specified deleted revisions to the given file.
1896 * Permissions and logging are left to the caller.
1897 *
1898 * May throw database exceptions on error.
1899 *
1900 * @param array $versions Set of record ids of deleted items to restore,
1901 * or empty to restore all revisions.
1902 * @param bool $unsuppress Remove restrictions on content upon restoration?
1903 * @return int|bool The number of file revisions restored if successful,
1904 * or false on failure
1905 * STUB
1906 * Overridden by LocalFile
1907 */
1908 function restore( $versions = array(), $unsuppress = false ) {
1909 $this->readOnlyError();
1910 }
1911
1912 /**
1913 * Returns 'true' if this file is a type which supports multiple pages,
1914 * e.g. DJVU or PDF. Note that this may be true even if the file in
1915 * question only has a single page.
1916 *
1917 * @return bool
1918 */
1919 function isMultipage() {
1920 return $this->getHandler() && $this->handler->isMultiPage( $this );
1921 }
1922
1923 /**
1924 * Returns the number of pages of a multipage document, or false for
1925 * documents which aren't multipage documents
1926 *
1927 * @return bool|int
1928 */
1929 function pageCount() {
1930 if ( !isset( $this->pageCount ) ) {
1931 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1932 $this->pageCount = $this->handler->pageCount( $this );
1933 } else {
1934 $this->pageCount = false;
1935 }
1936 }
1937
1938 return $this->pageCount;
1939 }
1940
1941 /**
1942 * Calculate the height of a thumbnail using the source and destination width
1943 *
1944 * @param int $srcWidth
1945 * @param int $srcHeight
1946 * @param int $dstWidth
1947 *
1948 * @return int
1949 */
1950 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1951 // Exact integer multiply followed by division
1952 if ( $srcWidth == 0 ) {
1953 return 0;
1954 } else {
1955 return round( $srcHeight * $dstWidth / $srcWidth );
1956 }
1957 }
1958
1959 /**
1960 * Get an image size array like that returned by getImageSize(), or false if it
1961 * can't be determined. Loads the image size directly from the file ignoring caches.
1962 *
1963 * @note Use getWidth()/getHeight() instead of this method unless you have a
1964 * a good reason. This method skips all caches.
1965 *
1966 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1967 * @return array The width, followed by height, with optionally more things after
1968 */
1969 function getImageSize( $filePath ) {
1970 if ( !$this->getHandler() ) {
1971 return false;
1972 }
1973
1974 return $this->getHandler()->getImageSize( $this, $filePath );
1975 }
1976
1977 /**
1978 * Get the URL of the image description page. May return false if it is
1979 * unknown or not applicable.
1980 *
1981 * @return string
1982 */
1983 function getDescriptionUrl() {
1984 if ( $this->repo ) {
1985 return $this->repo->getDescriptionUrl( $this->getName() );
1986 } else {
1987 return false;
1988 }
1989 }
1990
1991 /**
1992 * Get the HTML text of the description page, if available
1993 *
1994 * @param bool|Language $lang Optional language to fetch description in
1995 * @return string
1996 */
1997 function getDescriptionText( $lang = false ) {
1998 global $wgMemc, $wgLang;
1999 if ( !$this->repo || !$this->repo->fetchDescription ) {
2000 return false;
2001 }
2002 if ( !$lang ) {
2003 $lang = $wgLang;
2004 }
2005 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2006 if ( $renderUrl ) {
2007 if ( $this->repo->descriptionCacheExpiry > 0 ) {
2008 wfDebug( "Attempting to get the description from cache..." );
2009 $key = $this->repo->getLocalCacheKey(
2010 'RemoteFileDescription',
2011 'url',
2012 $lang->getCode(),
2013 $this->getName()
2014 );
2015 $obj = $wgMemc->get( $key );
2016 if ( $obj ) {
2017 wfDebug( "success!\n" );
2018
2019 return $obj;
2020 }
2021 wfDebug( "miss\n" );
2022 }
2023 wfDebug( "Fetching shared description from $renderUrl\n" );
2024 $res = Http::get( $renderUrl, array(), __METHOD__ );
2025 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
2026 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
2027 }
2028
2029 return $res;
2030 } else {
2031 return false;
2032 }
2033 }
2034
2035 /**
2036 * Get description of file revision
2037 * STUB
2038 *
2039 * @param int $audience One of:
2040 * File::FOR_PUBLIC to be displayed to all users
2041 * File::FOR_THIS_USER to be displayed to the given user
2042 * File::RAW get the description regardless of permissions
2043 * @param User $user User object to check for, only if FOR_THIS_USER is
2044 * passed to the $audience parameter
2045 * @return string
2046 */
2047 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2048 return null;
2049 }
2050
2051 /**
2052 * Get the 14-character timestamp of the file upload
2053 *
2054 * @return string|bool TS_MW timestamp or false on failure
2055 */
2056 function getTimestamp() {
2057 $this->assertRepoDefined();
2058
2059 return $this->repo->getFileTimestamp( $this->getPath() );
2060 }
2061
2062 /**
2063 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2064 * Returns false if the file does not have a description page, or retrieving the timestamp
2065 * would be expensive.
2066 * @since 1.25
2067 * @return string|bool
2068 */
2069 public function getDescriptionTouched() {
2070 return false;
2071 }
2072
2073 /**
2074 * Get the SHA-1 base 36 hash of the file
2075 *
2076 * @return string
2077 */
2078 function getSha1() {
2079 $this->assertRepoDefined();
2080
2081 return $this->repo->getFileSha1( $this->getPath() );
2082 }
2083
2084 /**
2085 * Get the deletion archive key, "<sha1>.<ext>"
2086 *
2087 * @return string
2088 */
2089 function getStorageKey() {
2090 $hash = $this->getSha1();
2091 if ( !$hash ) {
2092 return false;
2093 }
2094 $ext = $this->getExtension();
2095 $dotExt = $ext === '' ? '' : ".$ext";
2096
2097 return $hash . $dotExt;
2098 }
2099
2100 /**
2101 * Determine if the current user is allowed to view a particular
2102 * field of this file, if it's marked as deleted.
2103 * STUB
2104 * @param int $field
2105 * @param User $user User object to check, or null to use $wgUser
2106 * @return bool
2107 */
2108 function userCan( $field, User $user = null ) {
2109 return true;
2110 }
2111
2112 /**
2113 * @return array HTTP header name/value map to use for HEAD/GET request responses
2114 */
2115 function getStreamHeaders() {
2116 $handler = $this->getHandler();
2117 if ( $handler ) {
2118 return $handler->getStreamHeaders( $this->getMetadata() );
2119 } else {
2120 return array();
2121 }
2122 }
2123
2124 /**
2125 * @return string
2126 */
2127 function getLongDesc() {
2128 $handler = $this->getHandler();
2129 if ( $handler ) {
2130 return $handler->getLongDesc( $this );
2131 } else {
2132 return MediaHandler::getGeneralLongDesc( $this );
2133 }
2134 }
2135
2136 /**
2137 * @return string
2138 */
2139 function getShortDesc() {
2140 $handler = $this->getHandler();
2141 if ( $handler ) {
2142 return $handler->getShortDesc( $this );
2143 } else {
2144 return MediaHandler::getGeneralShortDesc( $this );
2145 }
2146 }
2147
2148 /**
2149 * @return string
2150 */
2151 function getDimensionsString() {
2152 $handler = $this->getHandler();
2153 if ( $handler ) {
2154 return $handler->getDimensionsString( $this );
2155 } else {
2156 return '';
2157 }
2158 }
2159
2160 /**
2161 * @return string
2162 */
2163 function getRedirected() {
2164 return $this->redirected;
2165 }
2166
2167 /**
2168 * @return Title|null
2169 */
2170 function getRedirectedTitle() {
2171 if ( $this->redirected ) {
2172 if ( !$this->redirectTitle ) {
2173 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2174 }
2175
2176 return $this->redirectTitle;
2177 }
2178
2179 return null;
2180 }
2181
2182 /**
2183 * @param string $from
2184 * @return void
2185 */
2186 function redirectedFrom( $from ) {
2187 $this->redirected = $from;
2188 }
2189
2190 /**
2191 * @return bool
2192 */
2193 function isMissing() {
2194 return false;
2195 }
2196
2197 /**
2198 * Check if this file object is small and can be cached
2199 * @return bool
2200 */
2201 public function isCacheable() {
2202 return true;
2203 }
2204
2205 /**
2206 * Assert that $this->repo is set to a valid FileRepo instance
2207 * @throws MWException
2208 */
2209 protected function assertRepoDefined() {
2210 if ( !( $this->repo instanceof $this->repoClass ) ) {
2211 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2212 }
2213 }
2214
2215 /**
2216 * Assert that $this->title is set to a Title
2217 * @throws MWException
2218 */
2219 protected function assertTitleDefined() {
2220 if ( !( $this->title instanceof Title ) ) {
2221 throw new MWException( "A Title object is not set for this File.\n" );
2222 }
2223 }
2224
2225 /**
2226 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2227 * @return bool
2228 */
2229 public function isExpensiveToThumbnail() {
2230 $handler = $this->getHandler();
2231 return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
2232 }
2233 }