3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
8 use Wikimedia\AtEase\AtEase
;
9 use MediaWiki\MediaWikiServices
;
12 * Base code for files.
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License along
25 * with this program; if not, write to the Free Software Foundation, Inc.,
26 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 * http://www.gnu.org/copyleft/gpl.html
30 * @ingroup FileAbstraction
33 // @phan-file-suppress PhanTypeMissingReturn false positives
35 * Implements some public methods and some protected utility functions which
36 * are required by multiple child classes. Contains stub functionality for
37 * unimplemented public methods.
39 * Stub functions which should be overridden are marked with STUB. Some more
40 * concrete functions are also typically overridden by child classes.
42 * Note that only the repo object knows what its file class is called. You should
43 * never name a file class explictly outside of the repo class. Instead use the
44 * repo's factory functions to generate file objects, for example:
46 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
48 * Consider the services container below;
50 * $services = MediaWikiServices::getInstance();
52 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
53 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
55 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
56 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
57 * and $this->repoGroup->getLocalRepo()->newFile().
59 * @ingroup FileAbstraction
61 abstract class File
implements IDBAccessObject
{
62 // Bitfield values akin to the Revision deletion constants
63 const DELETED_FILE
= 1;
64 const DELETED_COMMENT
= 2;
65 const DELETED_USER
= 4;
66 const DELETED_RESTRICTED
= 8;
68 /** Force rendering in the current process */
71 * Force rendering even if thumbnail already exist and using RENDER_NOW
72 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
74 const RENDER_FORCE
= 2;
76 const DELETE_SOURCE
= 1;
78 // Audience options for File::getDescription()
80 const FOR_THIS_USER
= 2;
83 // Options for File::thumbName()
84 const THUMB_FULL_NAME
= 1;
87 * Some member variables can be lazy-initialised using __get(). The
88 * initialisation function for these variables is always a function named
89 * like getVar(), where Var is the variable name with upper-case first
92 * The following variables are initialised in this way in this base class:
93 * name, extension, handler, path, canRender, isSafeFile,
94 * transformScript, hashPath, pageCount, url
96 * Code within this class should generally use the accessor function
97 * directly, since __get() isn't re-entrant and therefore causes bugs that
98 * depend on initialisation order.
102 * The following member variables are not lazy-initialised
105 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
108 /** @var Title|string|bool */
111 /** @var string Text of last error */
112 protected $lastError;
114 /** @var string Main part of the title, with underscores (Title::getDBkey) */
115 protected $redirected;
118 protected $redirectedTitle;
120 /** @var FSFile|bool False if undefined */
123 /** @var MediaHandler */
126 /** @var string The URL corresponding to one of the four basic zones */
129 /** @var string File extension */
130 protected $extension;
132 /** @var string The name of a file from its title object */
135 /** @var string The storage path corresponding to one of the zones */
138 /** @var string Relative path including trailing slash */
141 /** @var string|false Number of pages of a multipage document, or false for
142 * documents which aren't multipage documents
144 protected $pageCount;
146 /** @var string URL of transformscript (for example thumb.php) */
147 protected $transformScript;
150 protected $redirectTitle;
152 /** @var bool Whether the output of transform() for this file is likely to be valid. */
153 protected $canRender;
155 /** @var bool Whether this media file is in a format that is unlikely to
156 * contain viruses or malicious content
158 protected $isSafeFile;
160 /** @var string Required Repository class type */
161 protected $repoClass = FileRepo
::class;
163 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
164 protected $tmpBucketedThumbCache = [];
167 * Call this constructor from child classes.
169 * Both $title and $repo are optional, though some functions
170 * may return false or throw exceptions if they are not set.
171 * Most subclasses will want to call assertRepoDefined() here.
173 * @param Title|string|bool $title
174 * @param FileRepo|bool $repo
176 function __construct( $title, $repo ) {
177 // Some subclasses do not use $title, but set name/title some other way
178 if ( $title !== false ) {
179 $title = self
::normalizeTitle( $title, 'exception' );
181 $this->title
= $title;
186 * Given a string or Title object return either a
187 * valid Title object with namespace NS_FILE or null
189 * @param Title|string $title
190 * @param string|bool $exception Use 'exception' to throw an error on bad titles
191 * @throws MWException
194 static function normalizeTitle( $title, $exception = false ) {
196 if ( $ret instanceof Title
) {
197 # Normalize NS_MEDIA -> NS_FILE
198 if ( $ret->getNamespace() == NS_MEDIA
) {
199 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
200 # Sanity check the title namespace
201 } elseif ( $ret->getNamespace() !== NS_FILE
) {
205 # Convert strings to Title objects
206 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
208 if ( !$ret && $exception !== false ) {
209 throw new MWException( "`$title` is not a valid file title." );
215 function __get( $name ) {
216 $function = [ $this, 'get' . ucfirst( $name ) ];
217 if ( !is_callable( $function ) ) {
220 $this->$name = $function();
227 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
228 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
229 * Keep in sync with mw.Title.normalizeExtension() in JS.
231 * @param string $extension File extension (without the leading dot)
232 * @return string File extension in canonical form
234 static function normalizeExtension( $extension ) {
235 $lower = strtolower( $extension );
242 if ( isset( $squish[$lower] ) ) {
243 return $squish[$lower];
244 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
252 * Checks if file extensions are compatible
254 * @param File $old Old file
255 * @param string $new New name
259 static function checkExtensionCompatibility( File
$old, $new ) {
260 $oldMime = $old->getMimeType();
261 $n = strrpos( $new, '.' );
262 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
263 $mimeMagic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
265 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
269 * Upgrade the database row if there is one
270 * Called by ImagePage
273 function upgradeRow() {
277 * Split an internet media type into its two components; if not
278 * a two-part name, set the minor type to 'unknown'.
280 * @param string $mime "text/html" etc
281 * @return string[] ("text", "html") etc
283 public static function splitMime( $mime ) {
284 if ( strpos( $mime, '/' ) !== false ) {
285 return explode( '/', $mime, 2 );
287 return [ $mime, 'unknown' ];
292 * Callback for usort() to do file sorts by name
296 * @return int Result of name comparison
298 public static function compare( File
$a, File
$b ) {
299 return strcmp( $a->getName(), $b->getName() );
303 * Return the name of this file
307 public function getName() {
308 if ( $this->name
=== null ) {
309 $this->assertRepoDefined();
310 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
317 * Get the file extension, e.g. "svg"
321 function getExtension() {
322 if ( !isset( $this->extension
) ) {
323 $n = strrpos( $this->getName(), '.' );
324 $this->extension
= self
::normalizeExtension(
325 $n ?
substr( $this->getName(), $n +
1 ) : '' );
328 return $this->extension
;
332 * Return the associated title object
336 public function getTitle() {
341 * Return the title used to find this file
345 public function getOriginalTitle() {
346 if ( $this->redirected
) {
347 return $this->getRedirectedTitle();
354 * Return the URL of the file
358 public function getUrl() {
359 if ( !isset( $this->url
) ) {
360 $this->assertRepoDefined();
361 $ext = $this->getExtension();
362 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
369 * Get short description URL for a files based on the page ID
371 * @return string|null
374 public function getDescriptionShortUrl() {
379 * Return a fully-qualified URL to the file.
380 * Upload URL paths _may or may not_ be fully qualified, so
381 * we check. Local paths are assumed to belong on $wgServer.
385 public function getFullUrl() {
386 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
392 public function getCanonicalUrl() {
393 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
399 function getViewURL() {
400 if ( $this->mustRender() ) {
401 if ( $this->canRender() ) {
402 return $this->createThumb( $this->getWidth() );
404 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
405 ' (' . $this->getMimeType() . "), but can't!\n" );
407 return $this->getUrl(); # hm... return NULL?
410 return $this->getUrl();
415 * Return the storage path to the file. Note that this does
416 * not mean that a file actually exists under that location.
418 * This path depends on whether directory hashing is active or not,
419 * i.e. whether the files are all found in the same directory,
420 * or in hashed paths like /images/3/3c.
422 * Most callers don't check the return value, but ForeignAPIFile::getPath
425 * @return string|bool ForeignAPIFile::getPath can return false
427 public function getPath() {
428 if ( !isset( $this->path
) ) {
429 $this->assertRepoDefined();
430 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
437 * Get an FS copy or original of this file and return the path.
438 * Returns false on failure. Callers must not alter the file.
439 * Temporary files are cleared automatically.
441 * @return string|bool False on failure
443 public function getLocalRefPath() {
444 $this->assertRepoDefined();
445 if ( !isset( $this->fsFile
) ) {
446 $starttime = microtime( true );
447 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
449 $statTiming = microtime( true ) - $starttime;
450 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
451 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
453 if ( !$this->fsFile
) {
454 $this->fsFile
= false; // null => false; cache negative hits
458 return ( $this->fsFile
)
459 ?
$this->fsFile
->getPath()
464 * Return the width of the image. Returns false if the width is unknown
468 * Overridden by LocalFile, UnregisteredLocalFile
473 public function getWidth( $page = 1 ) {
478 * Return the height of the image. Returns false if the height is unknown
482 * Overridden by LocalFile, UnregisteredLocalFile
485 * @return bool|int False on failure
487 public function getHeight( $page = 1 ) {
492 * Return the smallest bucket from $wgThumbnailBuckets which is at least
493 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
494 * will always be bigger than $desiredWidth.
496 * @param int $desiredWidth
500 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
501 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
503 $imageWidth = $this->getWidth( $page );
505 if ( $imageWidth === false ) {
509 if ( $desiredWidth > $imageWidth ) {
513 if ( !$wgThumbnailBuckets ) {
517 $sortedBuckets = $wgThumbnailBuckets;
519 sort( $sortedBuckets );
521 foreach ( $sortedBuckets as $bucket ) {
522 if ( $bucket >= $imageWidth ) {
526 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
531 // Image is bigger than any available bucket
536 * Returns ID or name of user who uploaded the file
539 * @param string $type 'text' or 'id'
542 public function getUser( $type = 'text' ) {
547 * Get the duration of a media file in seconds
551 public function getLength() {
552 $handler = $this->getHandler();
554 return $handler->getLength( $this );
561 * Return true if the file is vectorized
565 public function isVectorized() {
566 $handler = $this->getHandler();
568 return $handler->isVectorized( $this );
575 * Gives a (possibly empty) list of languages to render
578 * If the file doesn't have translations, or if the file
579 * format does not support that sort of thing, returns
585 public function getAvailableLanguages() {
586 $handler = $this->getHandler();
588 return $handler->getAvailableLanguages( $this );
595 * Get the language code from the available languages for this file that matches the language
596 * requested by the user
598 * @param string $userPreferredLanguage
599 * @return string|null
601 public function getMatchedLanguage( $userPreferredLanguage ) {
602 $handler = $this->getHandler();
604 return $handler->getMatchedLanguage(
605 $userPreferredLanguage,
606 $handler->getAvailableLanguages( $this )
614 * In files that support multiple language, what is the default language
615 * to use if none specified.
617 * @return string|null Lang code, or null if filetype doesn't support multiple languages.
620 public function getDefaultRenderLanguage() {
621 $handler = $this->getHandler();
623 return $handler->getDefaultRenderLanguage( $this );
630 * Will the thumbnail be animated if one would expect it to be.
632 * Currently used to add a warning to the image description page
634 * @return bool False if the main image is both animated
635 * and the thumbnail is not. In all other cases must return
636 * true. If image is not renderable whatsoever, should
639 public function canAnimateThumbIfAppropriate() {
640 $handler = $this->getHandler();
642 // We cannot handle image whatsoever, thus
643 // one would not expect it to be animated
648 return !$this->allowInlineDisplay()
649 // Image is not animated, so one would
650 // not expect thumb to be
651 ||
!$handler->isAnimatedImage( $this )
652 // Image is animated, but thumbnail isn't.
653 // This is unexpected to the user.
654 ||
$handler->canAnimateThumbnail( $this );
658 * Get handler-specific metadata
659 * Overridden by LocalFile, UnregisteredLocalFile
663 public function getMetadata() {
668 * Like getMetadata but returns a handler independent array of common values.
669 * @see MediaHandler::getCommonMetaArray()
670 * @return array|bool Array or false if not supported
673 public function getCommonMetaArray() {
674 $handler = $this->getHandler();
680 return $handler->getCommonMetaArray( $this );
684 * get versioned metadata
686 * @param array|string $metadata Array or string of (serialized) metadata
687 * @param int $version Version number.
688 * @return array Array containing metadata, or what was passed to it on fail
689 * (unserializing if not array)
691 public function convertMetadataVersion( $metadata, $version ) {
692 $handler = $this->getHandler();
693 if ( !is_array( $metadata ) ) {
694 // Just to make the return type consistent
695 $metadata = unserialize( $metadata );
698 return $handler->convertMetadataVersion( $metadata, $version );
705 * Return the bit depth of the file
706 * Overridden by LocalFile
710 public function getBitDepth() {
715 * Return the size of the image file, in bytes
716 * Overridden by LocalFile, UnregisteredLocalFile
720 public function getSize() {
725 * Returns the MIME type of the file.
726 * Overridden by LocalFile, UnregisteredLocalFile
731 function getMimeType() {
732 return 'unknown/unknown';
736 * Return the type of the media in the file.
737 * Use the value returned by this function with the MEDIATYPE_xxx constants.
738 * Overridden by LocalFile,
742 function getMediaType() {
743 return MEDIATYPE_UNKNOWN
;
747 * Checks if the output of transform() for this file is likely
748 * to be valid. If this is false, various user elements will
749 * display a placeholder instead.
751 * Currently, this checks if the file is an image format
752 * that can be converted to a format
753 * supported by all browsers (namely GIF, PNG and JPEG),
754 * or if it is an SVG image and SVG conversion is enabled.
758 function canRender() {
759 if ( !isset( $this->canRender
) ) {
760 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
763 return $this->canRender
;
767 * Accessor for __get()
770 protected function getCanRender() {
771 return $this->canRender();
775 * Return true if the file is of a type that can't be directly
776 * rendered by typical browsers and needs to be re-rasterized.
778 * This returns true for everything but the bitmap types
779 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
780 * also return true for any non-image formats.
784 function mustRender() {
785 return $this->getHandler() && $this->handler
->mustRender( $this );
789 * Alias for canRender()
793 function allowInlineDisplay() {
794 return $this->canRender();
798 * Determines if this media file is in a format that is unlikely to
799 * contain viruses or malicious content. It uses the global
800 * $wgTrustedMediaFormats list to determine if the file is safe.
802 * This is used to show a warning on the description page of non-safe files.
803 * It may also be used to disallow direct [[media:...]] links to such files.
805 * Note that this function will always return true if allowInlineDisplay()
806 * or isTrustedFile() is true for this file.
810 function isSafeFile() {
811 if ( !isset( $this->isSafeFile
) ) {
812 $this->isSafeFile
= $this->getIsSafeFileUncached();
815 return $this->isSafeFile
;
819 * Accessor for __get()
823 protected function getIsSafeFile() {
824 return $this->isSafeFile();
832 protected function getIsSafeFileUncached() {
833 global $wgTrustedMediaFormats;
835 if ( $this->allowInlineDisplay() ) {
838 if ( $this->isTrustedFile() ) {
842 $type = $this->getMediaType();
843 $mime = $this->getMimeType();
844 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
846 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
847 return false; # unknown type, not trusted
849 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
853 if ( $mime === "unknown/unknown" ) {
854 return false; # unknown type, not trusted
856 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
864 * Returns true if the file is flagged as trusted. Files flagged that way
865 * can be linked to directly, even if that is not allowed for this type of
868 * This is a dummy function right now and always returns false. It could be
869 * implemented to extract a flag from the database. The trusted flag could be
870 * set on upload, if the user has sufficient privileges, to bypass script-
871 * and html-filters. It may even be coupled with cryptographics signatures
876 function isTrustedFile() {
877 # this could be implemented to check a flag in the database,
878 # look for signatures, etc
883 * Load any lazy-loaded file object fields from source
885 * This is only useful when setting $flags
887 * Overridden by LocalFile to actually query the DB
889 * @param int $flags Bitfield of File::READ_* constants
891 public function load( $flags = 0 ) {
895 * Returns true if file exists in the repository.
897 * Overridden by LocalFile to avoid unnecessary stat calls.
899 * @return bool Whether file exists in the repository.
901 public function exists() {
902 return $this->getPath() && $this->repo
->fileExists( $this->path
);
906 * Returns true if file exists in the repository and can be included in a page.
907 * It would be unsafe to include private images, making public thumbnails inadvertently
909 * @return bool Whether file exists in the repository and is includable.
911 public function isVisible() {
912 return $this->exists();
918 function getTransformScript() {
919 if ( !isset( $this->transformScript
) ) {
920 $this->transformScript
= false;
922 $script = $this->repo
->getThumbScriptUrl();
924 $this->transformScript
= wfAppendQuery( $script, [ 'f' => $this->getName() ] );
929 return $this->transformScript
;
933 * Get a ThumbnailImage which is the same size as the source
935 * @param array $handlerParams
937 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
939 function getUnscaledThumb( $handlerParams = [] ) {
940 $hp =& $handlerParams;
941 $page = $hp['page'] ??
false;
942 $width = $this->getWidth( $page );
944 return $this->iconThumb();
946 $hp['width'] = $width;
947 // be sure to ignore any height specification as well (T64258)
948 unset( $hp['height'] );
950 return $this->transform( $hp );
954 * Return the file name of a thumbnail with the specified parameters.
955 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
956 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
958 * @param array $params Handler-specific parameters
959 * @param int $flags Bitfield that supports THUMB_* constants
960 * @return string|null
962 public function thumbName( $params, $flags = 0 ) {
963 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
964 ?
$this->repo
->nameForThumb( $this->getName() )
967 return $this->generateThumbName( $name, $params );
971 * Generate a thumbnail file name from a name and specified parameters
973 * @param string $name
974 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
975 * @return string|null
977 public function generateThumbName( $name, $params ) {
978 if ( !$this->getHandler() ) {
981 $extension = $this->getExtension();
982 list( $thumbExt, ) = $this->getHandler()->getThumbType(
983 $extension, $this->getMimeType(), $params );
984 $thumbName = $this->getHandler()->makeParamString( $params );
986 if ( $this->repo
->supportsSha1URLs() ) {
987 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
989 $thumbName .= '-' . $name;
991 if ( $thumbExt != $extension ) {
992 $thumbName .= ".$thumbExt";
1000 * Create a thumbnail of the image having the specified width/height.
1001 * The thumbnail will not be created if the width is larger than the
1002 * image's width. Let the browser do the scaling in this case.
1003 * The thumbnail is stored on disk and is only computed if the thumbnail
1004 * file does not exist OR if it is older than the image.
1007 * Keeps aspect ratio of original image. If both width and height are
1008 * specified, the generated image will be no bigger than width x height,
1009 * and will also have correct aspect ratio.
1011 * @param int $width Maximum width of the generated thumbnail
1012 * @param int $height Maximum height of the image (optional)
1016 public function createThumb( $width, $height = -1 ) {
1017 $params = [ 'width' => $width ];
1018 if ( $height != -1 ) {
1019 $params['height'] = $height;
1021 $thumb = $this->transform( $params );
1022 if ( !$thumb ||
$thumb->isError() ) {
1026 return $thumb->getUrl();
1030 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
1032 * @param string $thumbPath Thumbnail storage path
1033 * @param string $thumbUrl Thumbnail URL
1034 * @param array $params
1036 * @return MediaTransformOutput
1038 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1039 global $wgIgnoreImageErrors;
1041 $handler = $this->getHandler();
1042 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1043 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1045 return new MediaTransformError( 'thumbnail_error',
1046 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1051 * Transform a media file
1053 * @param array $params An associative array of handler-specific parameters.
1054 * Typical keys are width, height and page.
1055 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1056 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
1058 function transform( $params, $flags = 0 ) {
1059 global $wgThumbnailEpoch;
1062 if ( !$this->canRender() ) {
1063 $thumb = $this->iconThumb();
1064 break; // not a bitmap or renderable image, don't try
1067 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1068 $descriptionUrl = $this->getDescriptionUrl();
1069 if ( $descriptionUrl ) {
1070 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1073 $handler = $this->getHandler();
1074 $script = $this->getTransformScript();
1075 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1076 // Use a script to transform on client request, if possible
1077 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1083 $normalisedParams = $params;
1084 $handler->normaliseParams( $this, $normalisedParams );
1086 $thumbName = $this->thumbName( $normalisedParams );
1087 $thumbUrl = $this->getThumbUrl( $thumbName );
1088 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1090 if ( $this->repo
) {
1091 // Defer rendering if a 404 handler is set up...
1092 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1093 // XXX: Pass in the storage path even though we are not rendering anything
1094 // and the path is supposed to be an FS path. This is due to getScalerType()
1095 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1096 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1099 // Check if an up-to-date thumbnail already exists...
1100 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1101 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1102 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1103 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1104 // XXX: Pass in the storage path even though we are not rendering anything
1105 // and the path is supposed to be an FS path. This is due to getScalerType()
1106 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1107 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1108 $thumb->setStoragePath( $thumbPath );
1111 } elseif ( $flags & self
::RENDER_FORCE
) {
1112 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1115 // If the backend is ready-only, don't keep generating thumbnails
1116 // only to return transformation errors, just return the error now.
1117 if ( $this->repo
->getReadOnlyReason() !== false ) {
1118 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1123 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1126 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1128 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1132 return is_object( $thumb ) ?
$thumb : false;
1136 * Generates a thumbnail according to the given parameters and saves it to storage
1137 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1138 * @param array $transformParams
1140 * @return bool|MediaTransformOutput
1142 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1143 global $wgIgnoreImageErrors;
1145 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1147 $handler = $this->getHandler();
1149 $normalisedParams = $transformParams;
1150 $handler->normaliseParams( $this, $normalisedParams );
1152 $thumbName = $this->thumbName( $normalisedParams );
1153 $thumbUrl = $this->getThumbUrl( $thumbName );
1154 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1156 $tmpThumbPath = $tmpFile->getPath();
1158 if ( $handler->supportsBucketing() ) {
1159 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1162 $starttime = microtime( true );
1164 // Actually render the thumbnail...
1165 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1166 $tmpFile->bind( $thumb ); // keep alive with $thumb
1168 $statTiming = microtime( true ) - $starttime;
1169 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1171 if ( !$thumb ) { // bad params?
1173 } elseif ( $thumb->isError() ) { // transform error
1174 /** @var MediaTransformError $thumb */
1175 $this->lastError
= $thumb->toText();
1176 // Ignore errors if requested
1177 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1178 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1180 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1181 // Copy the thumbnail from the file system into storage...
1183 $starttime = microtime( true );
1185 $disposition = $this->getThumbDisposition( $thumbName );
1186 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1187 if ( $status->isOK() ) {
1188 $thumb->setStoragePath( $thumbPath );
1190 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1193 $statTiming = microtime( true ) - $starttime;
1194 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1196 // Give extensions a chance to do something with this thumbnail...
1197 Hooks
::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
1204 * Generates chained bucketed thumbnails if needed
1205 * @param array $params
1207 * @return bool Whether at least one bucket was generated
1209 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1211 ||
!isset( $params['physicalWidth'] )
1212 ||
!isset( $params['physicalHeight'] )
1217 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1219 if ( !$bucket ||
$bucket == $params['physicalWidth'] ) {
1223 $bucketPath = $this->getBucketThumbPath( $bucket );
1225 if ( $this->repo
->fileExists( $bucketPath ) ) {
1229 $starttime = microtime( true );
1231 $params['physicalWidth'] = $bucket;
1232 $params['width'] = $bucket;
1234 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1236 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1242 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1244 $buckettime = microtime( true ) - $starttime;
1246 if ( !$thumb ||
$thumb->isError() ) {
1250 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1251 // For the caching to work, we need to make the tmp file survive as long as
1252 // this object exists
1253 $tmpFile->bind( $this );
1255 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
1256 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1262 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1263 * @param array $params
1264 * @return array Source path and width/height of the source
1266 public function getThumbnailSource( $params ) {
1268 && $this->getHandler()->supportsBucketing()
1269 && isset( $params['physicalWidth'] )
1270 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1272 if ( $this->getWidth() != 0 ) {
1273 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1278 // Try to avoid reading from storage if the file was generated by this script
1279 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1280 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1282 if ( file_exists( $tmpPath ) ) {
1286 'height' => $bucketHeight
1291 $bucketPath = $this->getBucketThumbPath( $bucket );
1293 if ( $this->repo
->fileExists( $bucketPath ) ) {
1294 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1298 'path' => $fsFile->getPath(),
1300 'height' => $bucketHeight
1306 // Thumbnailing a very large file could result in network saturation if
1307 // everyone does it at once.
1308 if ( $this->getSize() >= 1e7
) { // 10MB
1309 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1311 'doWork' => function () {
1312 return $this->getLocalRefPath();
1316 $srcPath = $work->execute();
1318 $srcPath = $this->getLocalRefPath();
1324 'width' => $this->getWidth(),
1325 'height' => $this->getHeight()
1330 * Returns the repo path of the thumb for a given bucket
1331 * @param int $bucket
1334 protected function getBucketThumbPath( $bucket ) {
1335 $thumbName = $this->getBucketThumbName( $bucket );
1336 return $this->getThumbPath( $thumbName );
1340 * Returns the name of the thumb for a given bucket
1341 * @param int $bucket
1344 protected function getBucketThumbName( $bucket ) {
1345 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1349 * Creates a temp FS file with the same extension and the thumbnail
1350 * @param string $thumbPath Thumbnail path
1351 * @return TempFSFile|null
1353 protected function makeTransformTmpFile( $thumbPath ) {
1354 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1355 return MediaWikiServices
::getInstance()->getTempFSFileFactory()
1356 ->newTempFSFile( 'transform_', $thumbExt );
1360 * @param string $thumbName Thumbnail name
1361 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1362 * @return string Content-Disposition header value
1364 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1365 $fileName = $this->name
; // file name to suggest
1366 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1367 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1368 $fileName .= ".$thumbExt";
1371 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1375 * Hook into transform() to allow migration of thumbnail files
1377 * Overridden by LocalFile
1378 * @param string $thumbName
1380 function migrateThumbFile( $thumbName ) {
1384 * Get a MediaHandler instance for this file
1386 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1387 * or false if none found
1389 function getHandler() {
1390 if ( !isset( $this->handler
) ) {
1391 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1394 return $this->handler
;
1398 * Get a ThumbnailImage representing a file type icon
1400 * @return ThumbnailImage
1402 function iconThumb() {
1403 global $wgResourceBasePath, $IP;
1404 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1405 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1407 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1408 foreach ( $try as $icon ) {
1409 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1410 $params = [ 'width' => 120, 'height' => 120 ];
1412 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1420 * Get last thumbnailing error.
1424 function getLastError() {
1425 return $this->lastError
;
1429 * Get all thumbnail names previously generated for this file
1431 * Overridden by LocalFile
1434 function getThumbnails() {
1439 * Purge shared caches such as thumbnails and DB data caching
1441 * Overridden by LocalFile
1442 * @param array $options Options, which include:
1443 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1445 function purgeCache( $options = [] ) {
1449 * Purge the file description page, but don't go after
1450 * pages using the file. Use when modifying file history
1451 * but not the current data.
1453 function purgeDescription() {
1454 $title = $this->getTitle();
1456 $title->invalidateCache();
1457 $title->purgeSquid();
1462 * Purge metadata and all affected pages when the file is created,
1463 * deleted, or majorly updated.
1465 function purgeEverything() {
1466 // Delete thumbnails and refresh file metadata cache
1467 $this->purgeCache();
1468 $this->purgeDescription();
1470 // Purge cache of all pages using this file
1471 $title = $this->getTitle();
1473 DeferredUpdates
::addUpdate(
1474 new HTMLCacheUpdate( $title, 'imagelinks', 'file-purge' )
1480 * Return a fragment of the history of file.
1483 * @param int|null $limit Limit of rows to return
1484 * @param string|int|null $start Only revisions older than $start will be returned
1485 * @param string|int|null $end Only revisions newer than $end will be returned
1486 * @param bool $inc Include the endpoints of the time range
1490 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1495 * Return the history of this file, line by line. Starts with current version,
1496 * then old versions. Should return an object similar to an image/oldimage
1500 * Overridden in LocalFile
1503 public function nextHistoryLine() {
1508 * Reset the history pointer to the first element of the history.
1509 * Always call this function after using nextHistoryLine() to free db resources
1511 * Overridden in LocalFile.
1513 public function resetHistory() {
1517 * Get the filename hash component of the directory including trailing slash,
1519 * If the repository is not hashed, returns an empty string.
1523 function getHashPath() {
1524 if ( $this->hashPath
=== null ) {
1525 $this->assertRepoDefined();
1526 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1529 return $this->hashPath
;
1533 * Get the path of the file relative to the public zone root.
1534 * This function is overridden in OldLocalFile to be like getArchiveRel().
1539 return $this->getHashPath() . $this->getName();
1543 * Get the path of an archived file relative to the public zone root
1545 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1549 function getArchiveRel( $suffix = false ) {
1550 $path = 'archive/' . $this->getHashPath();
1551 if ( $suffix === false ) {
1552 $path = rtrim( $path, '/' );
1561 * Get the path, relative to the thumbnail zone root, of the
1562 * thumbnail directory or a particular file if $suffix is specified
1564 * @param bool|string $suffix If not false, the name of a thumbnail file
1567 function getThumbRel( $suffix = false ) {
1568 $path = $this->getRel();
1569 if ( $suffix !== false ) {
1570 $path .= '/' . $suffix;
1577 * Get urlencoded path of the file relative to the public zone root.
1578 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1582 function getUrlRel() {
1583 return $this->getHashPath() . rawurlencode( $this->getName() );
1587 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1588 * or a specific thumb if the $suffix is given.
1590 * @param string $archiveName The timestamped name of an archived image
1591 * @param bool|string $suffix If not false, the name of a thumbnail file
1594 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1595 $path = $this->getArchiveRel( $archiveName );
1596 if ( $suffix !== false ) {
1597 $path .= '/' . $suffix;
1604 * Get the path of the archived file.
1606 * @param bool|string $suffix If not false, the name of an archived file.
1609 function getArchivePath( $suffix = false ) {
1610 $this->assertRepoDefined();
1612 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1616 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1618 * @param string $archiveName The timestamped name of an archived image
1619 * @param bool|string $suffix If not false, the name of a thumbnail file
1622 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1623 $this->assertRepoDefined();
1625 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1626 $this->getArchiveThumbRel( $archiveName, $suffix );
1630 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1632 * @param bool|string $suffix If not false, the name of a thumbnail file
1635 function getThumbPath( $suffix = false ) {
1636 $this->assertRepoDefined();
1638 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1642 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1644 * @param bool|string $suffix If not false, the name of a media file
1647 function getTranscodedPath( $suffix = false ) {
1648 $this->assertRepoDefined();
1650 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1654 * Get the URL of the archive directory, or a particular file if $suffix is specified
1656 * @param bool|string $suffix If not false, the name of an archived file
1659 function getArchiveUrl( $suffix = false ) {
1660 $this->assertRepoDefined();
1661 $ext = $this->getExtension();
1662 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1663 if ( $suffix === false ) {
1664 $path = rtrim( $path, '/' );
1666 $path .= rawurlencode( $suffix );
1673 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1675 * @param string $archiveName The timestamped name of an archived image
1676 * @param bool|string $suffix If not false, the name of a thumbnail file
1679 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1680 $this->assertRepoDefined();
1681 $ext = $this->getExtension();
1682 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1683 $this->getHashPath() . rawurlencode( $archiveName );
1684 if ( $suffix !== false ) {
1685 $path .= '/' . rawurlencode( $suffix );
1692 * Get the URL of the zone directory, or a particular file if $suffix is specified
1694 * @param string $zone Name of requested zone
1695 * @param bool|string $suffix If not false, the name of a file in zone
1696 * @return string Path
1698 function getZoneUrl( $zone, $suffix = false ) {
1699 $this->assertRepoDefined();
1700 $ext = $this->getExtension();
1701 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1702 if ( $suffix !== false ) {
1703 $path .= '/' . rawurlencode( $suffix );
1710 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1712 * @param bool|string $suffix If not false, the name of a thumbnail file
1713 * @return string Path
1715 function getThumbUrl( $suffix = false ) {
1716 return $this->getZoneUrl( 'thumb', $suffix );
1720 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1722 * @param bool|string $suffix If not false, the name of a media file
1723 * @return string Path
1725 function getTranscodedUrl( $suffix = false ) {
1726 return $this->getZoneUrl( 'transcoded', $suffix );
1730 * Get the public zone virtual URL for a current version source file
1732 * @param bool|string $suffix If not false, the name of a thumbnail file
1735 function getVirtualUrl( $suffix = false ) {
1736 $this->assertRepoDefined();
1737 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1738 if ( $suffix !== false ) {
1739 $path .= '/' . rawurlencode( $suffix );
1746 * Get the public zone virtual URL for an archived version source file
1748 * @param bool|string $suffix If not false, the name of a thumbnail file
1751 function getArchiveVirtualUrl( $suffix = false ) {
1752 $this->assertRepoDefined();
1753 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1754 if ( $suffix === false ) {
1755 $path = rtrim( $path, '/' );
1757 $path .= rawurlencode( $suffix );
1764 * Get the virtual URL for a thumbnail file or directory
1766 * @param bool|string $suffix If not false, the name of a thumbnail file
1769 function getThumbVirtualUrl( $suffix = false ) {
1770 $this->assertRepoDefined();
1771 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1772 if ( $suffix !== false ) {
1773 $path .= '/' . rawurlencode( $suffix );
1782 function isHashed() {
1783 $this->assertRepoDefined();
1785 return (bool)$this->repo
->getHashLevels();
1789 * @throws MWException
1791 function readOnlyError() {
1792 throw new MWException( static::class . ': write operations are not supported' );
1796 * Record a file upload in the upload log and the image table
1798 * Overridden by LocalFile
1799 * @param string $oldver
1800 * @param string $desc
1801 * @param string $license
1802 * @param string $copyStatus
1803 * @param string $source
1804 * @param bool $watch
1805 * @param string|bool $timestamp
1806 * @param null|User $user User object or null to use $wgUser
1808 * @throws MWException
1810 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1811 $watch = false, $timestamp = false, User
$user = null
1813 $this->readOnlyError();
1817 * Move or copy a file to its public location. If a file exists at the
1818 * destination, move it to an archive. Returns a Status object with
1819 * the archive name in the "value" member on success.
1821 * The archive name should be passed through to recordUpload for database
1824 * Options to $options include:
1825 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1827 * @param string|FSFile $src Local filesystem path to the source image
1828 * @param int $flags A bitwise combination of:
1829 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1830 * @param array $options Optional additional parameters
1831 * @return Status On success, the value member contains the
1832 * archive name, or an empty string if it was a new file.
1835 * Overridden by LocalFile
1837 function publish( $src, $flags = 0, array $options = [] ) {
1838 $this->readOnlyError();
1842 * @param bool|IContextSource $context Context to use (optional)
1845 function formatMetadata( $context = false ) {
1846 if ( !$this->getHandler() ) {
1850 return $this->getHandler()->formatMetadata( $this, $context );
1854 * Returns true if the file comes from the local file repository.
1858 function isLocal() {
1859 return $this->repo
&& $this->repo
->isLocal();
1863 * Returns the name of the repository.
1867 function getRepoName() {
1868 return $this->repo ?
$this->repo
->getName() : 'unknown';
1872 * Returns the repository
1874 * @return FileRepo|LocalRepo|bool
1876 function getRepo() {
1881 * Returns true if the image is an old version
1891 * Is this file a "deleted" file in a private archive?
1894 * @param int $field One of DELETED_* bitfield constants
1897 function isDeleted( $field ) {
1902 * Return the deletion bitfield
1906 function getVisibility() {
1911 * Was this file ever deleted from the wiki?
1915 function wasDeleted() {
1916 $title = $this->getTitle();
1918 return $title && $title->isDeletedQuick();
1922 * Move file to the new title
1924 * Move current, old version and all thumbnails
1925 * to the new filename. Old file is deleted.
1927 * Cache purging is done; checks for validity
1928 * and logging are caller's responsibility
1930 * @param Title $target New file name
1933 function move( $target ) {
1934 $this->readOnlyError();
1938 * Delete all versions of the file.
1940 * Moves the files into an archive directory (or deletes them)
1941 * and removes the database rows.
1943 * Cache purging is done; logging is caller's responsibility.
1945 * @param string $reason
1946 * @param bool $suppress Hide content from sysops?
1947 * @param User|null $user
1950 * Overridden by LocalFile
1952 function delete( $reason, $suppress = false, $user = null ) {
1953 $this->readOnlyError();
1957 * Restore all or specified deleted revisions to the given file.
1958 * Permissions and logging are left to the caller.
1960 * May throw database exceptions on error.
1962 * @param array $versions Set of record ids of deleted items to restore,
1963 * or empty to restore all revisions.
1964 * @param bool $unsuppress Remove restrictions on content upon restoration?
1967 * Overridden by LocalFile
1969 function restore( $versions = [], $unsuppress = false ) {
1970 $this->readOnlyError();
1974 * Returns 'true' if this file is a type which supports multiple pages,
1975 * e.g. DJVU or PDF. Note that this may be true even if the file in
1976 * question only has a single page.
1980 function isMultipage() {
1981 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1985 * Returns the number of pages of a multipage document, or false for
1986 * documents which aren't multipage documents
1988 * @return string|bool|int
1990 function pageCount() {
1991 if ( !isset( $this->pageCount
) ) {
1992 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1993 $this->pageCount
= $this->handler
->pageCount( $this );
1995 $this->pageCount
= false;
1999 return $this->pageCount
;
2003 * Calculate the height of a thumbnail using the source and destination width
2005 * @param int $srcWidth
2006 * @param int $srcHeight
2007 * @param int $dstWidth
2011 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
2012 // Exact integer multiply followed by division
2013 if ( $srcWidth == 0 ) {
2016 return (int)round( $srcHeight * $dstWidth / $srcWidth );
2021 * Get an image size array like that returned by getImageSize(), or false if it
2022 * can't be determined. Loads the image size directly from the file ignoring caches.
2024 * @note Use getWidth()/getHeight() instead of this method unless you have a
2025 * a good reason. This method skips all caches.
2027 * @param string $filePath The path to the file (e.g. From getLocalRefPath() )
2028 * @return array|false The width, followed by height, with optionally more things after
2030 function getImageSize( $filePath ) {
2031 if ( !$this->getHandler() ) {
2035 return $this->getHandler()->getImageSize( $this, $filePath );
2039 * Get the URL of the image description page. May return false if it is
2040 * unknown or not applicable.
2044 function getDescriptionUrl() {
2045 if ( $this->repo
) {
2046 return $this->repo
->getDescriptionUrl( $this->getName() );
2053 * Get the HTML text of the description page, if available
2055 * @param Language|null $lang Optional language to fetch description in
2056 * @return string|false
2058 function getDescriptionText( Language
$lang = null ) {
2061 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
2065 $lang = $lang ??
$wgLang;
2067 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2069 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2070 $key = $this->repo
->getLocalCacheKey(
2071 'RemoteFileDescription',
2073 md5( $this->getName() )
2075 $fname = __METHOD__
;
2077 return $cache->getWithSetCallback(
2079 $this->repo
->descriptionCacheExpiry ?
: $cache::TTL_UNCACHEABLE
,
2080 function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl, $fname ) {
2081 wfDebug( "Fetching shared description from $renderUrl\n" );
2082 $res = MediaWikiServices
::getInstance()->getHttpRequestFactory()->
2083 get( $renderUrl, [], $fname );
2085 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2097 * Get description of file revision
2100 * @param int $audience One of:
2101 * File::FOR_PUBLIC to be displayed to all users
2102 * File::FOR_THIS_USER to be displayed to the given user
2103 * File::RAW get the description regardless of permissions
2104 * @param User|null $user User object to check for, only if FOR_THIS_USER is
2105 * passed to the $audience parameter
2106 * @return null|string
2108 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2113 * Get the 14-character timestamp of the file upload
2115 * @return string|bool TS_MW timestamp or false on failure
2117 function getTimestamp() {
2118 $this->assertRepoDefined();
2120 return $this->repo
->getFileTimestamp( $this->getPath() );
2124 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2125 * Returns false if the file does not have a description page, or retrieving the timestamp
2126 * would be expensive.
2128 * @return string|bool
2130 public function getDescriptionTouched() {
2135 * Get the SHA-1 base 36 hash of the file
2139 function getSha1() {
2140 $this->assertRepoDefined();
2142 return $this->repo
->getFileSha1( $this->getPath() );
2146 * Get the deletion archive key, "<sha1>.<ext>"
2148 * @return string|false
2150 function getStorageKey() {
2151 $hash = $this->getSha1();
2155 $ext = $this->getExtension();
2156 $dotExt = $ext === '' ?
'' : ".$ext";
2158 return $hash . $dotExt;
2162 * Determine if the current user is allowed to view a particular
2163 * field of this file, if it's marked as deleted.
2166 * @param User|null $user User object to check, or null to use $wgUser
2169 function userCan( $field, User
$user = null ) {
2174 * @return string[] HTTP header name/value map to use for HEAD/GET request responses
2177 function getContentHeaders() {
2178 $handler = $this->getHandler();
2180 $metadata = $this->getMetadata();
2182 if ( is_string( $metadata ) ) {
2183 $metadata = AtEase
::quietCall( 'unserialize', $metadata );
2186 if ( !is_array( $metadata ) ) {
2190 return $handler->getContentHeaders( $metadata );
2199 function getLongDesc() {
2200 $handler = $this->getHandler();
2202 return $handler->getLongDesc( $this );
2204 return MediaHandler
::getGeneralLongDesc( $this );
2211 function getShortDesc() {
2212 $handler = $this->getHandler();
2214 return $handler->getShortDesc( $this );
2216 return MediaHandler
::getGeneralShortDesc( $this );
2223 function getDimensionsString() {
2224 $handler = $this->getHandler();
2226 return $handler->getDimensionsString( $this );
2235 function getRedirected() {
2236 return $this->redirected
;
2240 * @return Title|null
2242 function getRedirectedTitle() {
2243 if ( $this->redirected
) {
2244 if ( !$this->redirectTitle
) {
2245 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
2248 return $this->redirectTitle
;
2255 * @param string $from
2258 function redirectedFrom( $from ) {
2259 $this->redirected
= $from;
2265 function isMissing() {
2270 * Check if this file object is small and can be cached
2273 public function isCacheable() {
2278 * Assert that $this->repo is set to a valid FileRepo instance
2279 * @throws MWException
2281 protected function assertRepoDefined() {
2282 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2283 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2288 * Assert that $this->title is set to a Title
2289 * @throws MWException
2291 protected function assertTitleDefined() {
2292 if ( !( $this->title
instanceof Title
) ) {
2293 throw new MWException( "A Title object is not set for this File.\n" );
2298 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2301 public function isExpensiveToThumbnail() {
2302 $handler = $this->getHandler();
2303 return $handler ?
$handler->isExpensiveToThumbnail( $this ) : false;
2307 * Whether the thumbnails created on the same server as this code is running.
2311 public function isTransformedLocally() {