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