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