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