Merge "Skin: Remove deprecated skin methods"
[mediawiki.git] / includes / filerepo / file / File.php
blob5a6ee39e8944aaa1115124a20e903456bbb4b8f8
1 <?php
2 /**
3 * @defgroup FileAbstraction File abstraction
4 * @ingroup FileRepo
6 * Represents files in a repository.
7 */
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 Wikimedia\FileBackend\FileBackend;
24 use Wikimedia\ObjectCache\WANObjectCache;
26 /**
27 * Base code for files.
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation; either version 2 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License along
40 * with this program; if not, write to the Free Software Foundation, Inc.,
41 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
42 * http://www.gnu.org/copyleft/gpl.html
44 * @file
45 * @ingroup FileAbstraction
48 /**
49 * Implements some public methods and some protected utility functions which
50 * are required by multiple child classes. Contains stub functionality for
51 * unimplemented public methods.
53 * Stub functions which should be overridden are marked with STUB. Some more
54 * concrete functions are also typically overridden by child classes.
56 * Note that only the repo object knows what its file class is called. You should
57 * never name a file class explicitly outside of the repo class. Instead use the
58 * repo's factory functions to generate file objects, for example:
60 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
62 * Consider the services container below;
64 * $services = MediaWikiServices::getInstance();
66 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
67 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
69 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
70 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
71 * and $this->repoGroup->getLocalRepo()->newFile().
73 * @stable to extend
74 * @ingroup FileAbstraction
76 abstract class File implements MediaHandlerState {
77 use ProtectedHookAccessorTrait;
79 // Bitfield values akin to the revision deletion constants
80 public const DELETED_FILE = 1;
81 public const DELETED_COMMENT = 2;
82 public const DELETED_USER = 4;
83 public const DELETED_RESTRICTED = 8;
85 /** Force rendering in the current process */
86 public const RENDER_NOW = 1;
87 /**
88 * Force rendering even if thumbnail already exist and using RENDER_NOW
89 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
91 public const RENDER_FORCE = 2;
93 public const DELETE_SOURCE = 1;
95 // Audience options for File::getDescription()
96 public const FOR_PUBLIC = 1;
97 public const FOR_THIS_USER = 2;
98 public const RAW = 3;
100 // Options for File::thumbName()
101 public const THUMB_FULL_NAME = 1;
104 * Some member variables can be lazy-initialised using __get(). The
105 * initialisation function for these variables is always a function named
106 * like getVar(), where Var is the variable name with upper-case first
107 * letter.
109 * The following variables are initialised in this way in this base class:
110 * name, extension, handler, path, canRender, isSafeFile,
111 * transformScript, hashPath, pageCount, url
113 * Code within this class should generally use the accessor function
114 * directly, since __get() isn't re-entrant and therefore causes bugs that
115 * depend on initialisation order.
119 * The following member variables are not lazy-initialised
122 /** @var FileRepo|LocalRepo|ForeignAPIRepo|false */
123 public $repo;
125 /** @var Title|string|false */
126 protected $title;
128 /** @var string Text of last error */
129 protected $lastError;
131 /** @var ?string The name that was used to access the file, before
132 * resolving redirects. Main part of the title, with underscores
133 * per Title::getDBkey().
135 protected $redirected;
137 /** @var Title */
138 protected $redirectedTitle;
140 /** @var FSFile|false False if undefined */
141 protected $fsFile;
143 /** @var MediaHandler */
144 protected $handler;
146 /** @var string The URL corresponding to one of the four basic zones */
147 protected $url;
149 /** @var string File extension */
150 protected $extension;
152 /** @var string|null The name of a file from its title object */
153 protected $name;
155 /** @var string The storage path corresponding to one of the zones */
156 protected $path;
158 /** @var string|null Relative path including trailing slash */
159 protected $hashPath;
161 /** @var int|false Number of pages of a multipage document, or false for
162 * documents which aren't multipage documents
164 protected $pageCount;
166 /** @var string|false URL of transformscript (for example thumb.php) */
167 protected $transformScript;
169 /** @var Title */
170 protected $redirectTitle;
172 /** @var bool Whether the output of transform() for this file is likely to be valid. */
173 protected $canRender;
175 /** @var bool Whether this media file is in a format that is unlikely to
176 * contain viruses or malicious content
178 protected $isSafeFile;
180 /** @var string Required Repository class type */
181 protected $repoClass = FileRepo::class;
183 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
184 protected $tmpBucketedThumbCache = [];
186 /** @var array */
187 private $handlerState = [];
190 * Call this constructor from child classes.
192 * Both $title and $repo are optional, though some functions
193 * may return false or throw exceptions if they are not set.
194 * Most subclasses will want to call assertRepoDefined() here.
196 * @stable to call
197 * @param Title|string|false $title
198 * @param FileRepo|false $repo
200 public function __construct( $title, $repo ) {
201 // Some subclasses do not use $title, but set name/title some other way
202 if ( $title !== false ) {
203 $title = self::normalizeTitle( $title, 'exception' );
205 $this->title = $title;
206 $this->repo = $repo;
210 * Given a string or Title object return either a
211 * valid Title object with namespace NS_FILE or null
213 * @param PageIdentity|LinkTarget|string $title
214 * @param string|false $exception Use 'exception' to throw an error on bad titles
215 * @return Title|null
217 public static function normalizeTitle( $title, $exception = false ) {
218 $ret = $title;
220 if ( !$ret instanceof Title ) {
221 if ( $ret instanceof PageIdentity ) {
222 $ret = Title::castFromPageIdentity( $ret );
223 } elseif ( $ret instanceof LinkTarget ) {
224 $ret = Title::castFromLinkTarget( $ret );
228 if ( $ret instanceof Title ) {
229 # Normalize NS_MEDIA -> NS_FILE
230 if ( $ret->getNamespace() === NS_MEDIA ) {
231 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
232 # Double check the titles namespace
233 } elseif ( $ret->getNamespace() !== NS_FILE ) {
234 $ret = null;
236 } else {
237 # Convert strings to Title objects
238 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
240 if ( !$ret && $exception !== false ) {
241 throw new RuntimeException( "`$title` is not a valid file title." );
244 return $ret;
247 public function __get( $name ) {
248 $function = [ $this, 'get' . ucfirst( $name ) ];
249 if ( !is_callable( $function ) ) {
250 return null;
251 } else {
252 $this->$name = $function();
254 return $this->$name;
259 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
260 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
261 * Keep in sync with mw.Title.normalizeExtension() in JS.
263 * @param string $extension File extension (without the leading dot)
264 * @return string File extension in canonical form
266 public static function normalizeExtension( $extension ) {
267 $lower = strtolower( $extension );
268 $squish = [
269 'htm' => 'html',
270 'jpeg' => 'jpg',
271 'mpeg' => 'mpg',
272 'tiff' => 'tif',
273 'ogv' => 'ogg' ];
274 if ( isset( $squish[$lower] ) ) {
275 return $squish[$lower];
276 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
277 return $lower;
278 } else {
279 return '';
284 * Checks if file extensions are compatible
286 * @param File $old Old file
287 * @param string $new New name
289 * @return bool|null
291 public static function checkExtensionCompatibility( File $old, $new ) {
292 $oldMime = $old->getMimeType();
293 $n = strrpos( $new, '.' );
294 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
295 $mimeMagic = MediaWikiServices::getInstance()->getMimeAnalyzer();
297 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
301 * Upgrade the database row if there is one
302 * Called by ImagePage
303 * STUB
305 * @stable to override
307 public function upgradeRow() {
311 * Split an internet media type into its two components; if not
312 * a two-part name, set the minor type to 'unknown'.
314 * @param ?string $mime "text/html" etc
315 * @return string[] ("text", "html") etc
317 public static function splitMime( ?string $mime ) {
318 if ( $mime === null ) {
319 return [ 'unknown', 'unknown' ];
320 } elseif ( str_contains( $mime, '/' ) ) {
321 return explode( '/', $mime, 2 );
322 } else {
323 return [ $mime, 'unknown' ];
328 * Callback for usort() to do file sorts by name
330 * @param File $a
331 * @param File $b
332 * @return int Result of name comparison
334 public static function compare( File $a, File $b ) {
335 return strcmp( $a->getName(), $b->getName() );
339 * Return the name of this file
341 * @stable to override
342 * @return string
344 public function getName() {
345 if ( $this->name === null ) {
346 $this->assertRepoDefined();
347 $this->name = $this->repo->getNameFromTitle( $this->title );
350 return $this->name;
354 * Get the file extension, e.g. "svg"
356 * @stable to override
357 * @return string
359 public function getExtension() {
360 if ( !isset( $this->extension ) ) {
361 $n = strrpos( $this->getName(), '.' );
362 $this->extension = self::normalizeExtension(
363 $n ? substr( $this->getName(), $n + 1 ) : '' );
366 return $this->extension;
370 * Return the associated title object
372 * @return Title
374 public function getTitle() {
375 return $this->title;
379 * Return the title used to find this file
381 * @return Title
383 public function getOriginalTitle() {
384 if ( $this->redirected !== null ) {
385 return $this->getRedirectedTitle();
388 return $this->title;
392 * Return the URL of the file
393 * @stable to override
395 * @return string
397 public function getUrl() {
398 if ( !isset( $this->url ) ) {
399 $this->assertRepoDefined();
400 $ext = $this->getExtension();
401 $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
404 return $this->url;
408 * Get short description URL for a files based on the page ID
409 * @stable to override
411 * @return string|null
412 * @since 1.27
414 public function getDescriptionShortUrl() {
415 return null;
419 * Return a fully-qualified URL to the file.
420 * Upload URL paths _may or may not_ be fully qualified, so
421 * we check. Local paths are assumed to belong on $wgServer.
422 * @stable to override
424 * @return string
426 public function getFullUrl() {
427 return (string)MediaWikiServices::getInstance()->getUrlUtils()
428 ->expand( $this->getUrl(), PROTO_RELATIVE );
432 * @stable to override
433 * @return string
435 public function getCanonicalUrl() {
436 return (string)MediaWikiServices::getInstance()->getUrlUtils()
437 ->expand( $this->getUrl(), PROTO_CANONICAL );
441 * @return string
443 public function getViewURL() {
444 if ( $this->mustRender() ) {
445 if ( $this->canRender() ) {
446 return $this->createThumb( $this->getWidth() );
447 } else {
448 wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
449 ' (' . $this->getMimeType() . "), but can't!" );
451 return $this->getUrl(); # hm... return NULL?
453 } else {
454 return $this->getUrl();
459 * Return the storage path to the file. Note that this does
460 * not mean that a file actually exists under that location.
462 * This path depends on whether directory hashing is active or not,
463 * i.e. whether the files are all found in the same directory,
464 * or in hashed paths like /images/3/3c.
466 * Most callers don't check the return value, but ForeignAPIFile::getPath
467 * returns false.
469 * @stable to override
470 * @return string|false ForeignAPIFile::getPath can return false
472 public function getPath() {
473 if ( !isset( $this->path ) ) {
474 $this->assertRepoDefined();
475 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
478 return $this->path;
482 * Get an FS copy or original of this file and return the path.
483 * Returns false on failure. Callers must not alter the file.
484 * Temporary files are cleared automatically.
486 * @return string|false False on failure
488 public function getLocalRefPath() {
489 $this->assertRepoDefined();
490 if ( !isset( $this->fsFile ) ) {
491 $timer = MediaWikiServices::getInstance()->getStatsFactory()
492 ->getTiming( 'media_thumbnail_generate_fetchoriginal_seconds' )
493 ->copyToStatsdAt( 'media.thumbnail.generate.fetchoriginal' );
494 $timer->start();
496 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
498 $timer->stop();
500 if ( !$this->fsFile ) {
501 $this->fsFile = false; // null => false; cache negative hits
505 return ( $this->fsFile )
506 ? $this->fsFile->getPath()
507 : false;
511 * Return the width of the image. Returns false if the width is unknown
512 * or undefined.
514 * STUB
515 * Overridden by LocalFile, UnregisteredLocalFile
517 * @stable to override
518 * @param int $page
519 * @return int|false
521 public function getWidth( $page = 1 ) {
522 return false;
526 * Return the height of the image. Returns false if the height is unknown
527 * or undefined
529 * STUB
530 * Overridden by LocalFile, UnregisteredLocalFile
532 * @stable to override
533 * @param int $page
534 * @return int|false False on failure
536 public function getHeight( $page = 1 ) {
537 return false;
541 * Return the smallest bucket from $wgThumbnailBuckets which is at least
542 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
543 * will always be bigger than $desiredWidth.
545 * @param int $desiredWidth
546 * @param int $page
547 * @return int|false
549 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
550 $thumbnailBuckets = MediaWikiServices::getInstance()
551 ->getMainConfig()->get( MainConfigNames::ThumbnailBuckets );
552 $thumbnailMinimumBucketDistance = MediaWikiServices::getInstance()
553 ->getMainConfig()->get( MainConfigNames::ThumbnailMinimumBucketDistance );
554 $imageWidth = $this->getWidth( $page );
556 if ( $imageWidth === false ) {
557 return false;
560 if ( $desiredWidth > $imageWidth ) {
561 return false;
564 if ( !$thumbnailBuckets ) {
565 return false;
568 $sortedBuckets = $thumbnailBuckets;
570 sort( $sortedBuckets );
572 foreach ( $sortedBuckets as $bucket ) {
573 if ( $bucket >= $imageWidth ) {
574 return false;
577 if ( $bucket - $thumbnailMinimumBucketDistance > $desiredWidth ) {
578 return $bucket;
582 // Image is bigger than any available bucket
583 return false;
587 * Get the width and height to display image at.
589 * @param int $maxWidth Max width to display at
590 * @param int $maxHeight Max height to display at
591 * @param int $page
592 * @return array Array (width, height)
593 * @since 1.35
595 public function getDisplayWidthHeight( $maxWidth, $maxHeight, $page = 1 ) {
596 if ( !$maxWidth || !$maxHeight ) {
597 // should never happen
598 throw new ConfigException( 'Using a choice from $wgImageLimits that is 0x0' );
601 $width = $this->getWidth( $page );
602 $height = $this->getHeight( $page );
603 if ( !$width || !$height ) {
604 return [ 0, 0 ];
607 // Calculate the thumbnail size.
608 if ( $width <= $maxWidth && $height <= $maxHeight ) {
609 // Vectorized image, do nothing.
610 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
611 # The limiting factor is the width, not the height.
612 $height = round( $height * $maxWidth / $width );
613 $width = $maxWidth;
614 // Note that $height <= $maxHeight now.
615 } else {
616 $newwidth = floor( $width * $maxHeight / $height );
617 $height = round( $height * $newwidth / $width );
618 $width = $newwidth;
619 // Note that $height <= $maxHeight now, but might not be identical
620 // because of rounding.
622 return [ $width, $height ];
626 * Get the duration of a media file in seconds
628 * @stable to override
629 * @return float|int
631 public function getLength() {
632 $handler = $this->getHandler();
633 if ( $handler ) {
634 return $handler->getLength( $this );
635 } else {
636 return 0;
641 * Return true if the file is vectorized
643 * @return bool
645 public function isVectorized() {
646 $handler = $this->getHandler();
647 if ( $handler ) {
648 return $handler->isVectorized( $this );
649 } else {
650 return false;
655 * Gives a (possibly empty) list of IETF languages to render
656 * the file in.
658 * If the file doesn't have translations, or if the file
659 * format does not support that sort of thing, returns
660 * an empty array.
662 * @return string[]
663 * @since 1.23
665 public function getAvailableLanguages() {
666 $handler = $this->getHandler();
667 if ( $handler ) {
668 return $handler->getAvailableLanguages( $this );
669 } else {
670 return [];
675 * Get the IETF language code from the available languages for this file that matches the language
676 * requested by the user
678 * @param string $userPreferredLanguage
679 * @return string|null
681 public function getMatchedLanguage( $userPreferredLanguage ) {
682 $handler = $this->getHandler();
683 if ( $handler ) {
684 return $handler->getMatchedLanguage(
685 $userPreferredLanguage,
686 $handler->getAvailableLanguages( $this )
690 return null;
694 * In files that support multiple language, what is the default language
695 * to use if none specified.
697 * @return string|null IETF Lang code, or null if filetype doesn't support multiple languages.
698 * @since 1.23
700 public function getDefaultRenderLanguage() {
701 $handler = $this->getHandler();
702 if ( $handler ) {
703 return $handler->getDefaultRenderLanguage( $this );
704 } else {
705 return null;
710 * Will the thumbnail be animated if one would expect it to be.
712 * Currently used to add a warning to the image description page
714 * @return bool False if the main image is both animated
715 * and the thumbnail is not. In all other cases must return
716 * true. If image is not renderable whatsoever, should
717 * return true.
719 public function canAnimateThumbIfAppropriate() {
720 $handler = $this->getHandler();
721 if ( !$handler ) {
722 // We cannot handle image whatsoever, thus
723 // one would not expect it to be animated
724 // so true.
725 return true;
728 return !$this->allowInlineDisplay()
729 // Image is not animated, so one would
730 // not expect thumb to be
731 || !$handler->isAnimatedImage( $this )
732 // Image is animated, but thumbnail isn't.
733 // This is unexpected to the user.
734 || $handler->canAnimateThumbnail( $this );
738 * Get handler-specific metadata
739 * Overridden by LocalFile, UnregisteredLocalFile
740 * STUB
741 * @deprecated since 1.37 use getMetadataArray() or getMetadataItem()
742 * @return string|false
744 public function getMetadata() {
745 return false;
748 public function getHandlerState( string $key ) {
749 return $this->handlerState[$key] ?? null;
752 public function setHandlerState( string $key, $value ) {
753 $this->handlerState[$key] = $value;
757 * Get the unserialized handler-specific metadata
758 * STUB
759 * @since 1.37
760 * @return array
762 public function getMetadataArray(): array {
763 return [];
767 * Get a specific element of the unserialized handler-specific metadata.
769 * @since 1.37
770 * @param string $itemName
771 * @return mixed
773 public function getMetadataItem( string $itemName ) {
774 $items = $this->getMetadataItems( [ $itemName ] );
775 return $items[$itemName] ?? null;
779 * Get multiple elements of the unserialized handler-specific metadata.
781 * @since 1.37
782 * @param string[] $itemNames
783 * @return array
785 public function getMetadataItems( array $itemNames ): array {
786 return array_intersect_key(
787 $this->getMetadataArray(),
788 array_fill_keys( $itemNames, true ) );
792 * Like getMetadata but returns a handler independent array of common values.
793 * @see MediaHandler::getCommonMetaArray()
794 * @return array|false Array or false if not supported
795 * @since 1.23
797 public function getCommonMetaArray() {
798 $handler = $this->getHandler();
799 return $handler ? $handler->getCommonMetaArray( $this ) : false;
803 * get versioned metadata
805 * @param array $metadata Array of unserialized metadata
806 * @param int|string $version Version number.
807 * @return array Array containing metadata, or what was passed to it on fail
809 public function convertMetadataVersion( $metadata, $version ) {
810 $handler = $this->getHandler();
811 if ( $handler ) {
812 return $handler->convertMetadataVersion( $metadata, $version );
813 } else {
814 return $metadata;
819 * Return the bit depth of the file
820 * Overridden by LocalFile
821 * STUB
822 * @stable to override
823 * @return int
825 public function getBitDepth() {
826 return 0;
830 * Return the size of the image file, in bytes
831 * Overridden by LocalFile, UnregisteredLocalFile
832 * STUB
833 * @stable to override
834 * @return int|false
836 public function getSize() {
837 return false;
841 * Returns the MIME type of the file.
842 * Overridden by LocalFile, UnregisteredLocalFile
843 * STUB
845 * @stable to override
846 * @return string
848 public function getMimeType() {
849 return 'unknown/unknown';
853 * Return the type of the media in the file.
854 * Use the value returned by this function with the MEDIATYPE_xxx constants.
855 * Overridden by LocalFile,
856 * STUB
857 * @stable to override
858 * @return string
860 public function getMediaType() {
861 return MEDIATYPE_UNKNOWN;
865 * Checks if the output of transform() for this file is likely to be valid.
867 * In other words, this will return true if a thumbnail can be provided for this
868 * image (e.g. if [[File:...|thumb]] produces a result on a wikitext page).
870 * If this is false, various user elements will display a placeholder instead.
872 * @return bool
874 public function canRender() {
875 if ( !isset( $this->canRender ) ) {
876 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
879 return $this->canRender;
883 * Accessor for __get()
884 * @return bool
886 protected function getCanRender() {
887 return $this->canRender();
891 * Return true if the file is of a type that can't be directly
892 * rendered by typical browsers and needs to be re-rasterized.
894 * This returns true for everything but the bitmap types
895 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
896 * also return true for any non-image formats.
898 * @stable to override
899 * @return bool
901 public function mustRender() {
902 return $this->getHandler() && $this->handler->mustRender( $this );
906 * Alias for canRender()
908 * @return bool
910 public function allowInlineDisplay() {
911 return $this->canRender();
915 * Determines if this media file is in a format that is unlikely to
916 * contain viruses or malicious content. It uses the global
917 * $wgTrustedMediaFormats list to determine if the file is safe.
919 * This is used to show a warning on the description page of non-safe files.
920 * It may also be used to disallow direct [[media:...]] links to such files.
922 * Note that this function will always return true if allowInlineDisplay()
923 * or isTrustedFile() is true for this file.
925 * @return bool
927 public function isSafeFile() {
928 if ( !isset( $this->isSafeFile ) ) {
929 $this->isSafeFile = $this->getIsSafeFileUncached();
932 return $this->isSafeFile;
936 * Accessor for __get()
938 * @return bool
940 protected function getIsSafeFile() {
941 return $this->isSafeFile();
945 * Uncached accessor
947 * @return bool
949 protected function getIsSafeFileUncached() {
950 $trustedMediaFormats = MediaWikiServices::getInstance()->getMainConfig()
951 ->get( MainConfigNames::TrustedMediaFormats );
953 if ( $this->allowInlineDisplay() ) {
954 return true;
956 if ( $this->isTrustedFile() ) {
957 return true;
960 $type = $this->getMediaType();
961 $mime = $this->getMimeType();
963 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
964 return false; # unknown type, not trusted
966 if ( in_array( $type, $trustedMediaFormats ) ) {
967 return true;
970 if ( $mime === "unknown/unknown" ) {
971 return false; # unknown type, not trusted
973 if ( in_array( $mime, $trustedMediaFormats ) ) {
974 return true;
977 return false;
981 * Returns true if the file is flagged as trusted. Files flagged that way
982 * can be linked to directly, even if that is not allowed for this type of
983 * file normally.
985 * This is a dummy function right now and always returns false. It could be
986 * implemented to extract a flag from the database. The trusted flag could be
987 * set on upload, if the user has sufficient privileges, to bypass script-
988 * and html-filters. It may even be coupled with cryptographic signatures
989 * or such.
991 * @return bool
993 protected function isTrustedFile() {
994 # this could be implemented to check a flag in the database,
995 # look for signatures, etc
996 return false;
1000 * Load any lazy-loaded file object fields from source
1002 * This is only useful when setting $flags
1004 * Overridden by LocalFile to actually query the DB
1006 * @stable to override
1007 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
1009 public function load( $flags = 0 ) {
1013 * Returns true if file exists in the repository.
1015 * Overridden by LocalFile to avoid unnecessary stat calls.
1017 * @stable to override
1018 * @return bool Whether file exists in the repository.
1020 public function exists() {
1021 return $this->getPath() && $this->repo->fileExists( $this->path );
1025 * Returns true if file exists in the repository and can be included in a page.
1026 * It would be unsafe to include private images, making public thumbnails inadvertently
1028 * @stable to override
1029 * @return bool Whether file exists in the repository and is includable.
1031 public function isVisible() {
1032 return $this->exists();
1036 * @return string|false
1038 private function getTransformScript() {
1039 if ( !isset( $this->transformScript ) ) {
1040 $this->transformScript = false;
1041 if ( $this->repo ) {
1042 $script = $this->repo->getThumbScriptUrl();
1043 if ( $script ) {
1044 $this->transformScript = wfAppendQuery( $script, [ 'f' => $this->getName() ] );
1049 return $this->transformScript;
1053 * Get a ThumbnailImage which is the same size as the source
1055 * @param array $handlerParams
1057 * @return ThumbnailImage|MediaTransformOutput|false False on failure
1059 public function getUnscaledThumb( $handlerParams = [] ) {
1060 $hp =& $handlerParams;
1061 $page = $hp['page'] ?? false;
1062 $width = $this->getWidth( $page );
1063 if ( !$width ) {
1064 return $this->iconThumb();
1066 $hp['width'] = $width;
1067 // be sure to ignore any height specification as well (T64258)
1068 unset( $hp['height'] );
1070 return $this->transform( $hp );
1074 * Return the file name of a thumbnail with the specified parameters.
1075 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
1076 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
1077 * @stable to override
1079 * @param array $params Handler-specific parameters
1080 * @param int $flags Bitfield that supports THUMB_* constants
1081 * @return string|null
1083 public function thumbName( $params, $flags = 0 ) {
1084 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
1085 ? $this->repo->nameForThumb( $this->getName() )
1086 : $this->getName();
1088 return $this->generateThumbName( $name, $params );
1092 * Generate a thumbnail file name from a name and specified parameters
1093 * @stable to override
1095 * @param string $name
1096 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
1097 * @return string|null
1099 public function generateThumbName( $name, $params ) {
1100 if ( !$this->getHandler() ) {
1101 return null;
1103 $extension = $this->getExtension();
1104 [ $thumbExt, ] = $this->getHandler()->getThumbType(
1105 $extension, $this->getMimeType(), $params );
1106 $thumbName = $this->getHandler()->makeParamString( $params );
1108 if ( $this->repo->supportsSha1URLs() ) {
1109 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
1110 } else {
1111 $thumbName .= '-' . $name;
1113 if ( $thumbExt != $extension ) {
1114 $thumbName .= ".$thumbExt";
1118 return $thumbName;
1122 * Create a thumbnail of the image having the specified width/height.
1123 * The thumbnail will not be created if the width is larger than the
1124 * image's width. Let the browser do the scaling in this case.
1125 * The thumbnail is stored on disk and is only computed if the thumbnail
1126 * file does not exist OR if it is older than the image.
1127 * Returns the URL.
1129 * Keeps aspect ratio of original image. If both width and height are
1130 * specified, the generated image will be no bigger than width x height,
1131 * and will also have correct aspect ratio.
1133 * @param int $width Maximum width of the generated thumbnail
1134 * @param int $height Maximum height of the image (optional)
1136 * @return string
1138 public function createThumb( $width, $height = -1 ) {
1139 $params = [ 'width' => $width ];
1140 if ( $height != -1 ) {
1141 $params['height'] = $height;
1143 $thumb = $this->transform( $params );
1144 if ( !$thumb || $thumb->isError() ) {
1145 return '';
1148 return $thumb->getUrl();
1152 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
1154 * @param string $thumbPath Thumbnail storage path
1155 * @param string $thumbUrl Thumbnail URL
1156 * @param array $params
1157 * @param int $flags
1158 * @return MediaTransformOutput
1160 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1161 $ignoreImageErrors = MediaWikiServices::getInstance()->getMainConfig()
1162 ->get( MainConfigNames::IgnoreImageErrors );
1164 $handler = $this->getHandler();
1165 if ( $handler && $ignoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1166 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1167 } else {
1168 return new MediaTransformError( 'thumbnail_error',
1169 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1174 * Transform a media file
1175 * @stable to override
1177 * @param array $params An associative array of handler-specific parameters.
1178 * Typical keys are width, height and page.
1179 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1180 * @return ThumbnailImage|MediaTransformOutput|false False on failure
1182 public function transform( $params, $flags = 0 ) {
1183 $thumbnailEpoch = MediaWikiServices::getInstance()->getMainConfig()
1184 ->get( MainConfigNames::ThumbnailEpoch );
1186 do {
1187 if ( !$this->canRender() ) {
1188 $thumb = $this->iconThumb();
1189 break; // not a bitmap or renderable image, don't try
1192 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1193 $descriptionUrl = $this->getDescriptionUrl();
1194 if ( $descriptionUrl ) {
1195 $params['descriptionUrl'] = MediaWikiServices::getInstance()->getUrlUtils()
1196 ->expand( $descriptionUrl, PROTO_CANONICAL );
1199 $handler = $this->getHandler();
1200 $script = $this->getTransformScript();
1201 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1202 // Use a script to transform on client request, if possible
1203 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1204 if ( $thumb ) {
1205 break;
1209 $normalisedParams = $params;
1210 $handler->normaliseParams( $this, $normalisedParams );
1212 $thumbName = $this->thumbName( $normalisedParams );
1213 $thumbUrl = $this->getThumbUrl( $thumbName );
1214 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1215 if ( isset( $normalisedParams['isFilePageThumb'] ) && $normalisedParams['isFilePageThumb'] ) {
1216 // Use a versioned URL on file description pages
1217 $thumbUrl = $this->getFilePageThumbUrl( $thumbUrl );
1220 if ( $this->repo ) {
1221 // Defer rendering if a 404 handler is set up...
1222 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1223 // XXX: Pass in the storage path even though we are not rendering anything
1224 // and the path is supposed to be an FS path. This is due to getScalerType()
1225 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1226 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1227 break;
1229 // Check if an up-to-date thumbnail already exists...
1230 wfDebug( __METHOD__ . ": Doing stat for $thumbPath" );
1231 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1232 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1233 if ( $timestamp !== false && $timestamp >= $thumbnailEpoch ) {
1234 // XXX: Pass in the storage path even though we are not rendering anything
1235 // and the path is supposed to be an FS path. This is due to getScalerType()
1236 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1237 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1238 $thumb->setStoragePath( $thumbPath );
1239 break;
1241 } elseif ( $flags & self::RENDER_FORCE ) {
1242 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE" );
1245 // If the backend is ready-only, don't keep generating thumbnails
1246 // only to return transformation errors, just return the error now.
1247 if ( $this->repo->getReadOnlyReason() !== false ) {
1248 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1249 break;
1252 // Check to see if local transformation is disabled.
1253 if ( !$this->repo->canTransformLocally() ) {
1254 LoggerFactory::getInstance( 'thumbnail' )
1255 ->error( 'Local transform denied by configuration' );
1256 $thumb = new MediaTransformError(
1257 wfMessage(
1258 'thumbnail_error',
1259 'MediaWiki is configured to disallow local image scaling'
1261 $params['width'],
1264 break;
1268 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1270 if ( !$tmpFile ) {
1271 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1272 } else {
1273 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1275 } while ( false );
1277 return is_object( $thumb ) ? $thumb : false;
1281 * Generates a thumbnail according to the given parameters and saves it to storage
1282 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1283 * @param array $transformParams
1284 * @param int $flags
1285 * @return MediaTransformOutput|false
1287 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1288 $ignoreImageErrors = MediaWikiServices::getInstance()->getMainConfig()
1289 ->get( MainConfigNames::IgnoreImageErrors );
1291 if ( !$this->repo->canTransformLocally() ) {
1292 LoggerFactory::getInstance( 'thumbnail' )
1293 ->error( 'Local transform denied by configuration' );
1294 return new MediaTransformError(
1295 wfMessage(
1296 'thumbnail_error',
1297 'MediaWiki is configured to disallow local image scaling'
1299 $transformParams['width'],
1304 $statsFactory = MediaWikiServices::getInstance()->getStatsFactory();
1306 $handler = $this->getHandler();
1308 $normalisedParams = $transformParams;
1309 $handler->normaliseParams( $this, $normalisedParams );
1311 $thumbName = $this->thumbName( $normalisedParams );
1312 $thumbUrl = $this->getThumbUrl( $thumbName );
1313 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1314 if ( isset( $normalisedParams['isFilePageThumb'] ) && $normalisedParams['isFilePageThumb'] ) {
1315 // Use a versioned URL on file description pages
1316 $thumbUrl = $this->getFilePageThumbUrl( $thumbUrl );
1319 $tmpThumbPath = $tmpFile->getPath();
1321 if ( $handler->supportsBucketing() ) {
1322 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1325 # T367110
1326 # Calls to doTransform() can recur back on $this->transform()
1327 # depending on implementation. One such example is PagedTiffHandler.
1328 # TimingMetric->start() and stop() cannot be used in this situation
1329 # so we will track the time manually.
1330 $starttime = microtime( true );
1332 // Actually render the thumbnail...
1333 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1334 $tmpFile->bind( $thumb ); // keep alive with $thumb
1336 $statsFactory->getTiming( 'media_thumbnail_generate_transform_seconds' )
1337 ->copyToStatsdAt( 'media.thumbnail.generate.transform' )
1338 ->observe( ( microtime( true ) - $starttime ) * 1000 );
1340 if ( !$thumb ) { // bad params?
1341 $thumb = false;
1342 } elseif ( $thumb->isError() ) { // transform error
1343 /** @var MediaTransformError $thumb */
1344 '@phan-var MediaTransformError $thumb';
1345 $this->lastError = $thumb->toText();
1346 // Ignore errors if requested
1347 if ( $ignoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1348 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1350 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1351 // Copy the thumbnail from the file system into storage...
1353 $timer = $statsFactory->getTiming( 'media_thumbnail_generate_store_seconds' )
1354 ->copyToStatsdAt( 'media.thumbnail.generate.store' );
1355 $timer->start();
1357 $disposition = $this->getThumbDisposition( $thumbName );
1358 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1359 if ( $status->isOK() ) {
1360 $thumb->setStoragePath( $thumbPath );
1361 } else {
1362 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1365 $timer->stop();
1367 // Give extensions a chance to do something with this thumbnail...
1368 $this->getHookRunner()->onFileTransformed( $this, $thumb, $tmpThumbPath, $thumbPath );
1371 return $thumb;
1375 * Generates chained bucketed thumbnails if needed
1376 * @param array $params
1377 * @param int $flags
1378 * @return bool Whether at least one bucket was generated
1380 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1381 if ( !$this->repo
1382 || !isset( $params['physicalWidth'] )
1383 || !isset( $params['physicalHeight'] )
1385 return false;
1388 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1390 if ( !$bucket || $bucket == $params['physicalWidth'] ) {
1391 return false;
1394 $bucketPath = $this->getBucketThumbPath( $bucket );
1396 if ( $this->repo->fileExists( $bucketPath ) ) {
1397 return false;
1400 $timer = MediaWikiServices::getInstance()->getStatsFactory()
1401 ->getTiming( 'media_thumbnail_generate_bucket_seconds' )
1402 ->copyToStatsdAt( 'media.thumbnail.generate.bucket' );
1403 $timer->start();
1405 $params['physicalWidth'] = $bucket;
1406 $params['width'] = $bucket;
1408 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1410 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1412 if ( !$tmpFile ) {
1413 return false;
1416 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1418 if ( !$thumb || $thumb->isError() ) {
1419 return false;
1422 $timer->stop();
1424 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1425 // For the caching to work, we need to make the tmp file survive as long as
1426 // this object exists
1427 $tmpFile->bind( $this );
1429 return true;
1433 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1434 * @param array $params
1435 * @return array Source path and width/height of the source
1437 public function getThumbnailSource( $params ) {
1438 if ( $this->repo
1439 && $this->getHandler()->supportsBucketing()
1440 && isset( $params['physicalWidth'] )
1442 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1443 if ( $bucket ) {
1444 if ( $this->getWidth() != 0 ) {
1445 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1446 } else {
1447 $bucketHeight = 0;
1450 // Try to avoid reading from storage if the file was generated by this script
1451 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1452 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1454 if ( file_exists( $tmpPath ) ) {
1455 return [
1456 'path' => $tmpPath,
1457 'width' => $bucket,
1458 'height' => $bucketHeight
1463 $bucketPath = $this->getBucketThumbPath( $bucket );
1465 if ( $this->repo->fileExists( $bucketPath ) ) {
1466 $fsFile = $this->repo->getLocalReference( $bucketPath );
1468 if ( $fsFile ) {
1469 return [
1470 'path' => $fsFile->getPath(),
1471 'width' => $bucket,
1472 'height' => $bucketHeight
1479 // Thumbnailing a very large file could result in network saturation if
1480 // everyone does it at once.
1481 if ( $this->getSize() >= 1e7 ) { // 10 MB
1482 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1484 'doWork' => function () {
1485 return $this->getLocalRefPath();
1489 $srcPath = $work->execute();
1490 } else {
1491 $srcPath = $this->getLocalRefPath();
1494 // Original file
1495 return [
1496 'path' => $srcPath,
1497 'width' => $this->getWidth(),
1498 'height' => $this->getHeight()
1503 * Returns the repo path of the thumb for a given bucket
1504 * @param int $bucket
1505 * @return string
1507 protected function getBucketThumbPath( $bucket ) {
1508 $thumbName = $this->getBucketThumbName( $bucket );
1509 return $this->getThumbPath( $thumbName );
1513 * Returns the name of the thumb for a given bucket
1514 * @param int $bucket
1515 * @return string
1517 protected function getBucketThumbName( $bucket ) {
1518 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1522 * Creates a temp FS file with the same extension and the thumbnail
1523 * @param string $thumbPath Thumbnail path
1524 * @return TempFSFile|null
1526 protected function makeTransformTmpFile( $thumbPath ) {
1527 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1528 return MediaWikiServices::getInstance()->getTempFSFileFactory()
1529 ->newTempFSFile( 'transform_', $thumbExt );
1533 * @param string $thumbName Thumbnail name
1534 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1535 * @return string Content-Disposition header value
1537 public function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1538 $fileName = $this->getName(); // file name to suggest
1539 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1540 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1541 $fileName .= ".$thumbExt";
1544 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1548 * Get a MediaHandler instance for this file
1550 * @return MediaHandler|false Registered MediaHandler for file's MIME type
1551 * or false if none found
1553 public function getHandler() {
1554 if ( !isset( $this->handler ) ) {
1555 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1558 return $this->handler;
1562 * Get a ThumbnailImage representing a file type icon
1564 * @return ThumbnailImage|null
1566 public function iconThumb() {
1567 global $IP;
1568 $resourceBasePath = MediaWikiServices::getInstance()->getMainConfig()
1569 ->get( MainConfigNames::ResourceBasePath );
1570 $assetsPath = "{$resourceBasePath}/resources/assets/file-type-icons/";
1571 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1573 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1574 foreach ( $try as $icon ) {
1575 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1576 $params = [ 'width' => 120, 'height' => 120 ];
1578 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1582 return null;
1586 * Get last thumbnailing error.
1587 * Largely obsolete.
1588 * @return string
1590 public function getLastError() {
1591 return $this->lastError;
1595 * Get all thumbnail names previously generated for this file
1596 * STUB
1597 * Overridden by LocalFile
1598 * @stable to override
1599 * @return string[]
1601 protected function getThumbnails() {
1602 return [];
1606 * Purge shared caches such as thumbnails and DB data caching
1607 * STUB
1608 * Overridden by LocalFile
1609 * @stable to override
1610 * @param array $options Options, which include:
1611 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1613 public function purgeCache( $options = [] ) {
1617 * Purge the file description page, but don't go after
1618 * pages using the file. Use when modifying file history
1619 * but not the current data.
1621 public function purgeDescription() {
1622 $title = $this->getTitle();
1623 if ( $title ) {
1624 $title->invalidateCache();
1625 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1626 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1631 * Purge metadata and all affected pages when the file is created,
1632 * deleted, or majorly updated.
1634 public function purgeEverything() {
1635 // Delete thumbnails and refresh file metadata cache
1636 $this->purgeCache();
1637 $this->purgeDescription();
1638 // Purge cache of all pages using this file
1639 $title = $this->getTitle();
1640 if ( $title ) {
1641 $job = HTMLCacheUpdateJob::newForBacklinks(
1642 $title,
1643 'imagelinks',
1644 [ 'causeAction' => 'file-purge' ]
1646 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $job );
1651 * Return a fragment of the history of file.
1653 * STUB
1654 * @stable to override
1655 * @param int|null $limit Limit of rows to return
1656 * @param string|int|null $start Only revisions older than $start will be returned
1657 * @param string|int|null $end Only revisions newer than $end will be returned
1658 * @param bool $inc Include the endpoints of the time range
1660 * @return File[] Guaranteed to be in descending order
1662 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1663 return [];
1667 * Return the history of this file, line by line. Starts with current version,
1668 * then old versions. Should return an object similar to an image/oldimage
1669 * database row.
1671 * STUB
1672 * @stable to override
1673 * Overridden in LocalFile
1674 * @return bool
1676 public function nextHistoryLine() {
1677 return false;
1681 * Reset the history pointer to the first element of the history.
1682 * Always call this function after using nextHistoryLine() to free db resources
1683 * STUB
1684 * Overridden in LocalFile.
1685 * @stable to override
1687 public function resetHistory() {
1691 * Get the filename hash component of the directory including trailing slash,
1692 * e.g. f/fa/
1693 * If the repository is not hashed, returns an empty string.
1695 * @return string
1697 public function getHashPath() {
1698 if ( $this->hashPath === null ) {
1699 $this->assertRepoDefined();
1700 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1703 return $this->hashPath;
1707 * Get the path of the file relative to the public zone root.
1708 * This function is overridden in OldLocalFile to be like getArchiveRel().
1710 * @stable to override
1711 * @return string
1713 public function getRel() {
1714 return $this->getHashPath() . $this->getName();
1718 * Get the path of an archived file relative to the public zone root
1719 * @stable to override
1721 * @param string|false $suffix If not false, the name of an archived thumbnail file
1723 * @return string
1725 public function getArchiveRel( $suffix = false ) {
1726 $path = 'archive/' . $this->getHashPath();
1727 if ( $suffix === false ) {
1728 $path = rtrim( $path, '/' );
1729 } else {
1730 $path .= $suffix;
1733 return $path;
1737 * Get the path, relative to the thumbnail zone root, of the
1738 * thumbnail directory or a particular file if $suffix is specified
1739 * @stable to override
1741 * @param string|false $suffix If not false, the name of a thumbnail file
1742 * @return string
1744 public function getThumbRel( $suffix = false ) {
1745 $path = $this->getRel();
1746 if ( $suffix !== false ) {
1747 $path .= '/' . $suffix;
1750 return $path;
1754 * Get urlencoded path of the file relative to the public zone root.
1755 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1756 * @stable to override
1758 * @return string
1760 public function getUrlRel() {
1761 return $this->getHashPath() . rawurlencode( $this->getName() );
1765 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1766 * or a specific thumb if the $suffix is given.
1768 * @param string $archiveName The timestamped name of an archived image
1769 * @param string|false $suffix If not false, the name of a thumbnail file
1770 * @return string
1772 private function getArchiveThumbRel( $archiveName, $suffix = false ) {
1773 $path = $this->getArchiveRel( $archiveName );
1774 if ( $suffix !== false ) {
1775 $path .= '/' . $suffix;
1778 return $path;
1782 * Get the path of the archived file.
1784 * @param string|false $suffix If not false, the name of an archived file.
1785 * @return string
1787 public function getArchivePath( $suffix = false ) {
1788 $this->assertRepoDefined();
1790 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1794 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1796 * @param string $archiveName The timestamped name of an archived image
1797 * @param string|false $suffix If not false, the name of a thumbnail file
1798 * @return string
1800 public function getArchiveThumbPath( $archiveName, $suffix = false ) {
1801 $this->assertRepoDefined();
1803 return $this->repo->getZonePath( 'thumb' ) . '/' .
1804 $this->getArchiveThumbRel( $archiveName, $suffix );
1808 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1809 * @stable to override
1811 * @param string|false $suffix If not false, the name of a thumbnail file
1812 * @return string
1814 public function getThumbPath( $suffix = false ) {
1815 $this->assertRepoDefined();
1817 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1821 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1823 * @param string|false $suffix If not false, the name of a media file
1824 * @return string
1826 public function getTranscodedPath( $suffix = false ) {
1827 $this->assertRepoDefined();
1829 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1833 * Get the URL of the archive directory, or a particular file if $suffix is specified
1834 * @stable to override
1836 * @param string|false $suffix If not false, the name of an archived file
1837 * @return string
1839 public function getArchiveUrl( $suffix = false ) {
1840 $this->assertRepoDefined();
1841 $ext = $this->getExtension();
1842 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1843 if ( $suffix === false ) {
1844 $path = rtrim( $path, '/' );
1845 } else {
1846 $path .= rawurlencode( $suffix );
1849 return $path;
1853 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1854 * @stable to override
1856 * @param string $archiveName The timestamped name of an archived image
1857 * @param string|false $suffix If not false, the name of a thumbnail file
1858 * @return string
1860 public function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1861 $this->assertRepoDefined();
1862 $ext = $this->getExtension();
1863 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1864 $this->getHashPath() . rawurlencode( $archiveName );
1865 if ( $suffix !== false ) {
1866 $path .= '/' . rawurlencode( $suffix );
1869 return $path;
1873 * Get the URL of the zone directory, or a particular file if $suffix is specified
1875 * @param string $zone Name of requested zone
1876 * @param string|false $suffix If not false, the name of a file in zone
1877 * @return string Path
1879 private function getZoneUrl( $zone, $suffix = false ) {
1880 $this->assertRepoDefined();
1881 $ext = $this->getExtension();
1882 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1883 if ( $suffix !== false ) {
1884 $path .= '/' . rawurlencode( $suffix );
1887 return $path;
1891 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1892 * @stable to override
1894 * @param string|false $suffix If not false, the name of a thumbnail file
1895 * @return string Path
1897 public function getThumbUrl( $suffix = false ) {
1898 return $this->getZoneUrl( 'thumb', $suffix );
1902 * Append a version parameter to the end of a file URL
1903 * Only to be used on File pages.
1904 * @internal
1906 * @param string $url Unversioned URL
1907 * @return string
1909 public function getFilePageThumbUrl( $url ) {
1910 if ( $this->repo->isLocal() ) {
1911 return wfAppendQuery( $url, urlencode( $this->getTimestamp() ) );
1912 } else {
1913 return $url;
1918 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1920 * @param string|false $suffix If not false, the name of a media file
1921 * @return string Path
1923 public function getTranscodedUrl( $suffix = false ) {
1924 return $this->getZoneUrl( 'transcoded', $suffix );
1928 * Get the public zone virtual URL for a current version source file
1929 * @stable to override
1931 * @param string|false $suffix If not false, the name of a thumbnail file
1932 * @return string
1934 public function getVirtualUrl( $suffix = false ) {
1935 $this->assertRepoDefined();
1936 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1937 if ( $suffix !== false ) {
1938 $path .= '/' . rawurlencode( $suffix );
1941 return $path;
1945 * Get the public zone virtual URL for an archived version source file
1946 * @stable to override
1948 * @param string|false $suffix If not false, the name of a thumbnail file
1949 * @return string
1951 public function getArchiveVirtualUrl( $suffix = false ) {
1952 $this->assertRepoDefined();
1953 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1954 if ( $suffix === false ) {
1955 $path = rtrim( $path, '/' );
1956 } else {
1957 $path .= rawurlencode( $suffix );
1960 return $path;
1964 * Get the virtual URL for a thumbnail file or directory
1965 * @stable to override
1967 * @param string|false $suffix If not false, the name of a thumbnail file
1968 * @return string
1970 public function getThumbVirtualUrl( $suffix = false ) {
1971 $this->assertRepoDefined();
1972 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1973 if ( $suffix !== false ) {
1974 $path .= '/' . rawurlencode( $suffix );
1977 return $path;
1981 * @return bool
1983 protected function isHashed() {
1984 $this->assertRepoDefined();
1986 return (bool)$this->repo->getHashLevels();
1990 * @return never
1992 protected function readOnlyError() {
1993 throw new LogicException( static::class . ': write operations are not supported' );
1997 * Move or copy a file to its public location. If a file exists at the
1998 * destination, move it to an archive. Returns a Status object with
1999 * the archive name in the "value" member on success.
2001 * The archive name should be passed through to recordUpload3 for database
2002 * registration.
2004 * Options to $options include:
2005 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
2007 * @param string|FSFile $src Local filesystem path to the source image
2008 * @param int $flags A bitwise combination of:
2009 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
2010 * @param array $options Optional additional parameters
2011 * @return Status On success, the value member contains the
2012 * archive name, or an empty string if it was a new file.
2014 * STUB
2015 * Overridden by LocalFile
2016 * @stable to override
2018 public function publish( $src, $flags = 0, array $options = [] ) {
2019 $this->readOnlyError();
2023 * @param IContextSource|false $context
2024 * @return array[]|false
2026 public function formatMetadata( $context = false ) {
2027 $handler = $this->getHandler();
2028 return $handler ? $handler->formatMetadata( $this, $context ) : false;
2032 * Returns true if the file comes from the local file repository.
2034 * @return bool
2036 public function isLocal() {
2037 return $this->repo && $this->repo->isLocal();
2041 * Returns the name of the repository.
2043 * @return string
2045 public function getRepoName() {
2046 return $this->repo ? $this->repo->getName() : 'unknown';
2050 * Returns the repository
2051 * @stable to override
2053 * @return FileRepo|false
2055 public function getRepo() {
2056 return $this->repo;
2060 * Returns true if the image is an old version
2061 * STUB
2063 * @stable to override
2064 * @return bool
2066 public function isOld() {
2067 return false;
2071 * Is this file a "deleted" file in a private archive?
2072 * STUB
2074 * @stable to override
2075 * @param int $field One of DELETED_* bitfield constants
2076 * @return bool
2078 public function isDeleted( $field ) {
2079 return false;
2083 * Return the deletion bitfield
2084 * STUB
2085 * @stable to override
2086 * @return int
2088 public function getVisibility() {
2089 return 0;
2093 * Was this file ever deleted from the wiki?
2095 * @return bool
2097 public function wasDeleted() {
2098 $title = $this->getTitle();
2100 return $title && $title->hasDeletedEdits();
2104 * Move file to the new title
2106 * Move current, old version and all thumbnails
2107 * to the new filename. Old file is deleted.
2109 * Cache purging is done; checks for validity
2110 * and logging are caller's responsibility
2112 * @stable to override
2113 * @param Title $target New file name
2114 * @return Status
2116 public function move( $target ) {
2117 $this->readOnlyError();
2121 * Delete all versions of the file.
2123 * @since 1.35
2125 * Moves the files into an archive directory (or deletes them)
2126 * and removes the database rows.
2128 * Cache purging is done; logging is caller's responsibility.
2130 * @param string $reason
2131 * @param UserIdentity $user
2132 * @param bool $suppress Hide content from sysops?
2133 * @return Status
2134 * STUB
2135 * Overridden by LocalFile
2136 * @stable to override
2138 public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2139 $this->readOnlyError();
2143 * Restore all or specified deleted revisions to the given file.
2144 * Permissions and logging are left to the caller.
2146 * May throw database exceptions on error.
2148 * @param int[] $versions Set of record ids of deleted items to restore,
2149 * or empty to restore all revisions.
2150 * @param bool $unsuppress Remove restrictions on content upon restoration?
2151 * @return Status
2152 * STUB
2153 * Overridden by LocalFile
2154 * @stable to override
2156 public function restore( $versions = [], $unsuppress = false ) {
2157 $this->readOnlyError();
2161 * Returns 'true' if this file is a type which supports multiple pages,
2162 * e.g. DJVU or PDF. Note that this may be true even if the file in
2163 * question only has a single page.
2165 * @stable to override
2166 * @return bool
2168 public function isMultipage() {
2169 return $this->getHandler() && $this->handler->isMultiPage( $this );
2173 * Returns the number of pages of a multipage document, or false for
2174 * documents which aren't multipage documents
2176 * @stable to override
2177 * @return int|false
2179 public function pageCount() {
2180 if ( !isset( $this->pageCount ) ) {
2181 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
2182 $this->pageCount = $this->handler->pageCount( $this );
2183 } else {
2184 $this->pageCount = false;
2188 return $this->pageCount;
2192 * Calculate the height of a thumbnail using the source and destination width
2194 * @param int $srcWidth
2195 * @param int $srcHeight
2196 * @param int $dstWidth
2198 * @return int
2200 public static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
2201 // Exact integer multiply followed by division
2202 if ( $srcWidth == 0 ) {
2203 return 0;
2204 } else {
2205 return (int)round( $srcHeight * $dstWidth / $srcWidth );
2210 * Get the URL of the image description page. May return false if it is
2211 * unknown or not applicable.
2213 * @stable to override
2214 * @return string|false
2216 public function getDescriptionUrl() {
2217 if ( $this->repo ) {
2218 return $this->repo->getDescriptionUrl( $this->getName() );
2219 } else {
2220 return false;
2225 * Get the HTML text of the description page, if available
2226 * @stable to override
2228 * @param Language|null $lang Optional language to fetch description in
2229 * @return string|false HTML
2230 * @return-taint escaped
2232 public function getDescriptionText( ?Language $lang = null ) {
2233 global $wgLang;
2235 if ( !$this->repo || !$this->repo->fetchDescription ) {
2236 return false;
2239 $lang ??= $wgLang;
2241 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2242 if ( $renderUrl ) {
2243 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2244 $key = $this->repo->getLocalCacheKey(
2245 'file-remote-description',
2246 $lang->getCode(),
2247 md5( $this->getName() )
2249 $fname = __METHOD__;
2251 return $cache->getWithSetCallback(
2252 $key,
2253 $this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
2254 static function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl, $fname ) {
2255 wfDebug( "Fetching shared description from $renderUrl" );
2256 $res = MediaWikiServices::getInstance()->getHttpRequestFactory()->
2257 get( $renderUrl, [], $fname );
2258 if ( !$res ) {
2259 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2262 return $res;
2267 return false;
2271 * Get the identity of the file uploader.
2273 * @note if the file does not exist, this will return null regardless of the permissions.
2275 * @stable to override
2276 * @since 1.37
2277 * @param int $audience One of:
2278 * File::FOR_PUBLIC to be displayed to all users
2279 * File::FOR_THIS_USER to be displayed to the given user
2280 * File::RAW get the description regardless of permissions
2281 * @param Authority|null $performer to check for, only if FOR_THIS_USER is
2282 * passed to the $audience parameter
2283 * @return UserIdentity|null
2285 public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
2286 return null;
2290 * Get description of file revision
2291 * STUB
2293 * @stable to override
2294 * @param int $audience One of:
2295 * File::FOR_PUBLIC to be displayed to all users
2296 * File::FOR_THIS_USER to be displayed to the given user
2297 * File::RAW get the description regardless of permissions
2298 * @param Authority|null $performer to check for, only if FOR_THIS_USER is
2299 * passed to the $audience parameter
2300 * @return null|string
2302 public function getDescription( $audience = self::FOR_PUBLIC, ?Authority $performer = null ) {
2303 return null;
2307 * Get the 14-character timestamp of the file upload
2309 * @stable to override
2310 * @return string|false TS_MW timestamp or false on failure
2312 public function getTimestamp() {
2313 $this->assertRepoDefined();
2315 return $this->repo->getFileTimestamp( $this->getPath() );
2319 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2320 * Returns false if the file does not have a description page, or retrieving the timestamp
2321 * would be expensive.
2322 * @since 1.25
2323 * @stable to override
2324 * @return string|false
2326 public function getDescriptionTouched() {
2327 return false;
2331 * Get the SHA-1 base 36 hash of the file
2333 * @stable to override
2334 * @return string|false
2336 public function getSha1() {
2337 $this->assertRepoDefined();
2339 return $this->repo->getFileSha1( $this->getPath() );
2343 * Get the deletion archive key, "<sha1>.<ext>"
2345 * @return string|false
2347 public function getStorageKey() {
2348 $hash = $this->getSha1();
2349 if ( !$hash ) {
2350 return false;
2352 $ext = $this->getExtension();
2353 $dotExt = $ext === '' ? '' : ".$ext";
2355 return $hash . $dotExt;
2359 * Determine if the current user is allowed to view a particular
2360 * field of this file, if it's marked as deleted.
2361 * STUB
2362 * @stable to override
2363 * @param int $field
2364 * @param Authority $performer user object to check
2365 * @return bool
2367 public function userCan( $field, Authority $performer ) {
2368 return true;
2372 * @return string[] HTTP header name/value map to use for HEAD/GET request responses
2373 * @since 1.30
2375 public function getContentHeaders() {
2376 $handler = $this->getHandler();
2377 if ( $handler ) {
2378 return $handler->getContentHeaders( $this->getMetadataArray() );
2381 return [];
2385 * @return string
2387 public function getLongDesc() {
2388 $handler = $this->getHandler();
2389 if ( $handler ) {
2390 return $handler->getLongDesc( $this );
2391 } else {
2392 return MediaHandler::getGeneralLongDesc( $this );
2397 * @return string
2399 public function getShortDesc() {
2400 $handler = $this->getHandler();
2401 if ( $handler ) {
2402 return $handler->getShortDesc( $this );
2403 } else {
2404 return MediaHandler::getGeneralShortDesc( $this );
2409 * @return string
2411 public function getDimensionsString() {
2412 $handler = $this->getHandler();
2413 if ( $handler ) {
2414 return $handler->getDimensionsString( $this );
2415 } else {
2416 return '';
2421 * @return ?string The name that was used to access the file, before
2422 * resolving redirects.
2424 public function getRedirected(): ?string {
2425 return $this->redirected;
2429 * @return Title|null
2431 protected function getRedirectedTitle() {
2432 if ( $this->redirected !== null ) {
2433 if ( !$this->redirectTitle ) {
2434 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2437 return $this->redirectTitle;
2440 return null;
2444 * @param string $from The name that was used to access the file, before
2445 * resolving redirects.
2447 public function redirectedFrom( string $from ) {
2448 $this->redirected = $from;
2452 * @stable to override
2453 * @return bool
2455 public function isMissing() {
2456 return false;
2460 * Check if this file object is small and can be cached
2461 * @stable to override
2462 * @return bool
2464 public function isCacheable() {
2465 return true;
2469 * Assert that $this->repo is set to a valid FileRepo instance
2471 protected function assertRepoDefined() {
2472 if ( !( $this->repo instanceof $this->repoClass ) ) {
2473 throw new LogicException( "A {$this->repoClass} object is not set for this File.\n" );
2478 * Assert that $this->title is set to a Title
2480 protected function assertTitleDefined() {
2481 if ( !( $this->title instanceof Title ) ) {
2482 throw new LogicException( "A Title object is not set for this File.\n" );
2487 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2488 * @return bool
2490 public function isExpensiveToThumbnail() {
2491 $handler = $this->getHandler();
2492 return $handler && $handler->isExpensiveToThumbnail( $this );
2496 * Whether the thumbnails created on the same server as this code is running.
2497 * @since 1.25
2498 * @stable to override
2499 * @return bool
2501 public function isTransformedLocally() {
2502 return true;