Debian Codegraph @

includes/filerepo/file/File.php

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