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