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