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