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